instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_equiv_mode(acl, &inode->i_mode);
if (rc < 0)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
if (rc == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285 | static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (rc)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
| 166,975 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SMBC_server_internal(TALLOC_CTX *ctx,
SMBCCTX *context,
bool connect_if_not_found,
const char *server,
uint16_t port,
const char *share,
char **pp_workgroup,
char **pp_username,
char **pp_password,
bool *in_cache)
{
SMBCSRV *srv=NULL;
char *workgroup = NULL;
struct cli_state *c = NULL;
const char *server_n = server;
int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0);
uint32_t fs_attrs = 0;
const char *username_used;
NTSTATUS status;
char *newserver, *newshare;
int flags = 0;
struct smbXcli_tcon *tcon = NULL;
ZERO_STRUCT(c);
*in_cache = false;
if (server[0] == 0) {
errno = EPERM;
return NULL;
}
/* Look for a cached connection */
srv = SMBC_find_server(ctx, context, server, share,
pp_workgroup, pp_username, pp_password);
/*
* If we found a connection and we're only allowed one share per
* server...
*/
if (srv &&
share != NULL && *share != '\0' &&
smbc_getOptionOneSharePerServer(context)) {
/*
* ... then if there's no current connection to the share,
* connect to it. SMBC_find_server(), or rather the function
* pointed to by context->get_cached_srv_fn which
* was called by SMBC_find_server(), will have issued a tree
* disconnect if the requested share is not the same as the
* one that was already connected.
*/
/*
* Use srv->cli->desthost and srv->cli->share instead of
* server and share below to connect to the actual share,
* i.e., a normal share or a referred share from
* 'msdfs proxy' share.
*/
if (!cli_state_has_tcon(srv->cli)) {
/* Ensure we have accurate auth info */
SMBC_call_auth_fn(ctx, context,
smbXcli_conn_remote_name(srv->cli->conn),
srv->cli->share,
pp_workgroup,
pp_username,
pp_password);
if (!*pp_workgroup || !*pp_username || !*pp_password) {
errno = ENOMEM;
cli_shutdown(srv->cli);
srv->cli = NULL;
smbc_getFunctionRemoveCachedServer(context)(context,
srv);
return NULL;
}
/*
* We don't need to renegotiate encryption
* here as the encryption context is not per
* tid.
*/
status = cli_tree_connect(srv->cli,
srv->cli->share,
"?????",
*pp_password,
strlen(*pp_password)+1);
if (!NT_STATUS_IS_OK(status)) {
errno = map_errno_from_nt_status(status);
cli_shutdown(srv->cli);
srv->cli = NULL;
smbc_getFunctionRemoveCachedServer(context)(context,
srv);
srv = NULL;
}
/* Determine if this share supports case sensitivity */
if (is_ipc) {
DEBUG(4,
("IPC$ so ignore case sensitivity\n"));
status = NT_STATUS_OK;
} else {
status = cli_get_fs_attr_info(c, &fs_attrs);
}
if (!NT_STATUS_IS_OK(status)) {
DEBUG(4, ("Could not retrieve "
"case sensitivity flag: %s.\n",
nt_errstr(status)));
/*
* We can't determine the case sensitivity of
* the share. We have no choice but to use the
* user-specified case sensitivity setting.
*/
if (smbc_getOptionCaseSensitive(context)) {
cli_set_case_sensitive(c, True);
} else {
cli_set_case_sensitive(c, False);
}
} else if (!is_ipc) {
DEBUG(4,
("Case sensitive: %s\n",
(fs_attrs & FILE_CASE_SENSITIVE_SEARCH
? "True"
: "False")));
cli_set_case_sensitive(
c,
(fs_attrs & FILE_CASE_SENSITIVE_SEARCH
? True
: False));
}
/*
* Regenerate the dev value since it's based on both
* server and share
*/
if (srv) {
const char *remote_name =
smbXcli_conn_remote_name(srv->cli->conn);
srv->dev = (dev_t)(str_checksum(remote_name) ^
str_checksum(srv->cli->share));
}
}
}
/* If we have a connection... */
if (srv) {
/* ... then we're done here. Give 'em what they came for. */
*in_cache = true;
goto done;
}
/* If we're not asked to connect when a connection doesn't exist... */
if (! connect_if_not_found) {
/* ... then we're done here. */
return NULL;
}
if (!*pp_workgroup || !*pp_username || !*pp_password) {
errno = ENOMEM;
return NULL;
}
DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server));
DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
status = NT_STATUS_UNSUCCESSFUL;
if (smbc_getOptionUseKerberos(context)) {
flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
}
if (smbc_getOptionFallbackAfterKerberos(context)) {
flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
}
if (smbc_getOptionUseCCache(context)) {
flags |= CLI_FULL_CONNECTION_USE_CCACHE;
}
if (smbc_getOptionUseNTHash(context)) {
flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
}
if (port == 0) {
if (share == NULL || *share == '\0' || is_ipc) {
/*
}
*/
status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20,
smbc_getNetbiosName(context),
SMB_SIGNING_DEFAULT, flags, &c);
}
}
Commit Message:
CWE ID: CWE-20 | SMBC_server_internal(TALLOC_CTX *ctx,
SMBCCTX *context,
bool connect_if_not_found,
const char *server,
uint16_t port,
const char *share,
char **pp_workgroup,
char **pp_username,
char **pp_password,
bool *in_cache)
{
SMBCSRV *srv=NULL;
char *workgroup = NULL;
struct cli_state *c = NULL;
const char *server_n = server;
int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0);
uint32_t fs_attrs = 0;
const char *username_used;
NTSTATUS status;
char *newserver, *newshare;
int flags = 0;
struct smbXcli_tcon *tcon = NULL;
int signing_state = SMB_SIGNING_DEFAULT;
ZERO_STRUCT(c);
*in_cache = false;
if (server[0] == 0) {
errno = EPERM;
return NULL;
}
/* Look for a cached connection */
srv = SMBC_find_server(ctx, context, server, share,
pp_workgroup, pp_username, pp_password);
/*
* If we found a connection and we're only allowed one share per
* server...
*/
if (srv &&
share != NULL && *share != '\0' &&
smbc_getOptionOneSharePerServer(context)) {
/*
* ... then if there's no current connection to the share,
* connect to it. SMBC_find_server(), or rather the function
* pointed to by context->get_cached_srv_fn which
* was called by SMBC_find_server(), will have issued a tree
* disconnect if the requested share is not the same as the
* one that was already connected.
*/
/*
* Use srv->cli->desthost and srv->cli->share instead of
* server and share below to connect to the actual share,
* i.e., a normal share or a referred share from
* 'msdfs proxy' share.
*/
if (!cli_state_has_tcon(srv->cli)) {
/* Ensure we have accurate auth info */
SMBC_call_auth_fn(ctx, context,
smbXcli_conn_remote_name(srv->cli->conn),
srv->cli->share,
pp_workgroup,
pp_username,
pp_password);
if (!*pp_workgroup || !*pp_username || !*pp_password) {
errno = ENOMEM;
cli_shutdown(srv->cli);
srv->cli = NULL;
smbc_getFunctionRemoveCachedServer(context)(context,
srv);
return NULL;
}
/*
* We don't need to renegotiate encryption
* here as the encryption context is not per
* tid.
*/
status = cli_tree_connect(srv->cli,
srv->cli->share,
"?????",
*pp_password,
strlen(*pp_password)+1);
if (!NT_STATUS_IS_OK(status)) {
errno = map_errno_from_nt_status(status);
cli_shutdown(srv->cli);
srv->cli = NULL;
smbc_getFunctionRemoveCachedServer(context)(context,
srv);
srv = NULL;
}
/* Determine if this share supports case sensitivity */
if (is_ipc) {
DEBUG(4,
("IPC$ so ignore case sensitivity\n"));
status = NT_STATUS_OK;
} else {
status = cli_get_fs_attr_info(c, &fs_attrs);
}
if (!NT_STATUS_IS_OK(status)) {
DEBUG(4, ("Could not retrieve "
"case sensitivity flag: %s.\n",
nt_errstr(status)));
/*
* We can't determine the case sensitivity of
* the share. We have no choice but to use the
* user-specified case sensitivity setting.
*/
if (smbc_getOptionCaseSensitive(context)) {
cli_set_case_sensitive(c, True);
} else {
cli_set_case_sensitive(c, False);
}
} else if (!is_ipc) {
DEBUG(4,
("Case sensitive: %s\n",
(fs_attrs & FILE_CASE_SENSITIVE_SEARCH
? "True"
: "False")));
cli_set_case_sensitive(
c,
(fs_attrs & FILE_CASE_SENSITIVE_SEARCH
? True
: False));
}
/*
* Regenerate the dev value since it's based on both
* server and share
*/
if (srv) {
const char *remote_name =
smbXcli_conn_remote_name(srv->cli->conn);
srv->dev = (dev_t)(str_checksum(remote_name) ^
str_checksum(srv->cli->share));
}
}
}
/* If we have a connection... */
if (srv) {
/* ... then we're done here. Give 'em what they came for. */
*in_cache = true;
goto done;
}
/* If we're not asked to connect when a connection doesn't exist... */
if (! connect_if_not_found) {
/* ... then we're done here. */
return NULL;
}
if (!*pp_workgroup || !*pp_username || !*pp_password) {
errno = ENOMEM;
return NULL;
}
DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server));
DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
status = NT_STATUS_UNSUCCESSFUL;
if (smbc_getOptionUseKerberos(context)) {
flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
}
if (smbc_getOptionFallbackAfterKerberos(context)) {
flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
}
if (smbc_getOptionUseCCache(context)) {
flags |= CLI_FULL_CONNECTION_USE_CCACHE;
}
if (smbc_getOptionUseNTHash(context)) {
flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
}
if (context->internal->smb_encryption_level != SMBC_ENCRYPTLEVEL_NONE) {
signing_state = SMB_SIGNING_REQUIRED;
}
if (port == 0) {
if (share == NULL || *share == '\0' || is_ipc) {
/*
}
*/
status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20,
smbc_getNetbiosName(context),
signing_state, flags, &c);
}
}
| 164,677 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _asn1_extract_der_octet (asn1_node node, const unsigned char *der,
int der_len, unsigned flags)
{
int len2, len3;
int counter, counter_end;
int result;
len2 = asn1_get_length_der (der, der_len, &len3);
if (len2 < -1)
return ASN1_DER_ERROR;
counter = len3 + 1;
DECR_LEN(der_len, len3);
if (len2 == -1)
counter_end = der_len - 2;
else
counter_end = der_len;
while (counter < counter_end)
{
DECR_LEN(der_len, 1);
if (len2 >= 0)
{
DECR_LEN(der_len, len2+len3);
_asn1_append_value (node, der + counter + len3, len2);
}
else
{ /* indefinite */
DECR_LEN(der_len, len3);
result =
_asn1_extract_der_octet (node, der + counter + len3,
der_len, flags);
if (result != ASN1_SUCCESS)
return result;
len2 = 0;
}
counter += len2 + len3 + 1;
}
return ASN1_SUCCESS;
cleanup:
return result;
}
Commit Message:
CWE ID: CWE-399 | _asn1_extract_der_octet (asn1_node node, const unsigned char *der,
int der_len, unsigned flags)
{
int len2, len3;
int counter, counter_end;
int result;
len2 = asn1_get_length_der (der, der_len, &len3);
if (len2 < -1)
return ASN1_DER_ERROR;
counter = len3 + 1;
DECR_LEN(der_len, len3);
if (len2 == -1)
{
if (der_len < 2)
return ASN1_DER_ERROR;
counter_end = der_len - 2;
}
else
counter_end = der_len;
if (counter_end < counter)
return ASN1_DER_ERROR;
while (counter < counter_end)
{
DECR_LEN(der_len, 1);
if (len2 >= 0)
{
DECR_LEN(der_len, len2+len3);
_asn1_append_value (node, der + counter + len3, len2);
}
else
{ /* indefinite */
DECR_LEN(der_len, len3);
result =
_asn1_extract_der_octet (node, der + counter + len3,
der_len, flags);
if (result != ASN1_SUCCESS)
return result;
len2 = 0;
}
counter += len2 + len3 + 1;
}
return ASN1_SUCCESS;
cleanup:
return result;
}
| 165,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
ret = copy_to_user(param, ptr, sizeof(*ptr));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output
Do not leak kernel-only floppy_raw_cmd structure members to userspace.
This includes the linked-list pointer and the pointer to the allocated
DMA space.
Signed-off-by: Matthew Daley <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
struct floppy_raw_cmd cmd = *ptr;
cmd.next = NULL;
cmd.kernel_data = NULL;
ret = copy_to_user(param, &cmd, sizeof(cmd));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
| 166,434 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname)
{
gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem;
byte *ptr = 0;
#ifdef DEBUG
const char *msg;
static const char *const ok_msg = "OK";
# define set_msg(str) (msg = (str))
#else
# define set_msg(str) DO_NOTHING
#endif
/* Exclusive acces so our decisions and changes are 'atomic' */
if (mmem->monitor)
gx_monitor_enter(mmem->monitor);
if (size > mmem->limit - sizeof(gs_malloc_block_t)) {
/* Definitely too large to allocate; also avoids overflow. */
set_msg("exceeded limit");
} else {
uint added = size + sizeof(gs_malloc_block_t);
if (mmem->limit - added < mmem->used)
set_msg("exceeded limit");
else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0)
set_msg("failed");
else {
gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr;
/*
* We would like to check that malloc aligns blocks at least as
* strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD).
* However, Microsoft VC 6 does not satisfy this requirement.
* See gsmemory.h for more explanation.
*/
set_msg(ok_msg);
if (mmem->allocated)
mmem->allocated->prev = bp;
bp->next = mmem->allocated;
bp->prev = 0;
bp->size = size;
bp->type = &st_bytes;
bp->cname = cname;
mmem->allocated = bp;
ptr = (byte *) (bp + 1);
mmem->used += size + sizeof(gs_malloc_block_t);
if (mmem->used > mmem->max_used)
mmem->max_used = mmem->used;
}
}
if (mmem->monitor)
gx_monitor_leave(mmem->monitor); /* Done with exclusive access */
/* We don't want to 'fill' under mutex to keep the window smaller */
if (ptr)
gs_alloc_fill(ptr, gs_alloc_fill_alloc, size);
#ifdef DEBUG
if (gs_debug_c('a') || msg != ok_msg)
dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n",
client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used);
#endif
return ptr;
#undef set_msg
}
Commit Message:
CWE ID: CWE-189 | gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname)
{
gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem;
byte *ptr = 0;
#ifdef DEBUG
const char *msg;
static const char *const ok_msg = "OK";
# define set_msg(str) (msg = (str))
#else
# define set_msg(str) DO_NOTHING
#endif
/* Exclusive acces so our decisions and changes are 'atomic' */
if (mmem->monitor)
gx_monitor_enter(mmem->monitor);
if (size > mmem->limit - sizeof(gs_malloc_block_t)) {
/* Definitely too large to allocate; also avoids overflow. */
set_msg("exceeded limit");
} else {
uint added = size + sizeof(gs_malloc_block_t);
if (added <= size || mmem->limit - added < mmem->used)
set_msg("exceeded limit");
else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0)
set_msg("failed");
else {
gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr;
/*
* We would like to check that malloc aligns blocks at least as
* strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD).
* However, Microsoft VC 6 does not satisfy this requirement.
* See gsmemory.h for more explanation.
*/
set_msg(ok_msg);
if (mmem->allocated)
mmem->allocated->prev = bp;
bp->next = mmem->allocated;
bp->prev = 0;
bp->size = size;
bp->type = &st_bytes;
bp->cname = cname;
mmem->allocated = bp;
ptr = (byte *) (bp + 1);
mmem->used += size + sizeof(gs_malloc_block_t);
if (mmem->used > mmem->max_used)
mmem->max_used = mmem->used;
}
}
if (mmem->monitor)
gx_monitor_leave(mmem->monitor); /* Done with exclusive access */
/* We don't want to 'fill' under mutex to keep the window smaller */
if (ptr)
gs_alloc_fill(ptr, gs_alloc_fill_alloc, size);
#ifdef DEBUG
if (gs_debug_c('a') || msg != ok_msg)
dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n",
client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used);
#endif
return ptr;
#undef set_msg
}
| 164,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void filter_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
const int kInterp_Extend = 4;
const unsigned int intermediate_height =
(kInterp_Extend - 1) + output_height + kInterp_Extend;
/* Size of intermediate_buffer is max_intermediate_height * filter_max_width,
* where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height
* + kInterp_Extend
* = 3 + 16 + 4
* = 23
* and filter_max_width = 16
*/
uint8_t intermediate_buffer[71 * 64];
const int intermediate_next_stride = 1 - intermediate_height * output_width;
{
uint8_t *output_ptr = intermediate_buffer;
const int src_next_row_stride = src_stride - output_width;
unsigned int i, j;
src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1);
for (i = 0; i < intermediate_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * HFilter[0]) +
(src_ptr[1] * HFilter[1]) +
(src_ptr[2] * HFilter[2]) +
(src_ptr[3] * HFilter[3]) +
(src_ptr[4] * HFilter[4]) +
(src_ptr[5] * HFilter[5]) +
(src_ptr[6] * HFilter[6]) +
(src_ptr[7] * HFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT);
++src_ptr;
output_ptr += intermediate_height;
}
src_ptr += src_next_row_stride;
output_ptr += intermediate_next_stride;
}
}
{
uint8_t *src_ptr = intermediate_buffer;
const int dst_next_row_stride = dst_stride - output_width;
unsigned int i, j;
for (i = 0; i < output_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * VFilter[0]) +
(src_ptr[1] * VFilter[1]) +
(src_ptr[2] * VFilter[2]) +
(src_ptr[3] * VFilter[3]) +
(src_ptr[4] * VFilter[4]) +
(src_ptr[5] * VFilter[5]) +
(src_ptr[6] * VFilter[6]) +
(src_ptr[7] * VFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT);
src_ptr += intermediate_height;
}
src_ptr += intermediate_next_stride;
dst_ptr += dst_next_row_stride;
}
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void filter_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
const int kInterp_Extend = 4;
const unsigned int intermediate_height =
(kInterp_Extend - 1) + output_height + kInterp_Extend;
unsigned int i, j;
// Size of intermediate_buffer is max_intermediate_height * filter_max_width,
// where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height
// + kInterp_Extend
// = 3 + 16 + 4
// = 23
// and filter_max_width = 16
//
uint8_t intermediate_buffer[71 * kMaxDimension];
const int intermediate_next_stride = 1 - intermediate_height * output_width;
uint8_t *output_ptr = intermediate_buffer;
const int src_next_row_stride = src_stride - output_width;
src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1);
for (i = 0; i < intermediate_height; ++i) {
for (j = 0; j < output_width; ++j) {
// Apply filter...
const int temp = (src_ptr[0] * HFilter[0]) +
(src_ptr[1] * HFilter[1]) +
(src_ptr[2] * HFilter[2]) +
(src_ptr[3] * HFilter[3]) +
(src_ptr[4] * HFilter[4]) +
(src_ptr[5] * HFilter[5]) +
(src_ptr[6] * HFilter[6]) +
(src_ptr[7] * HFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
// Normalize back to 0-255...
*output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT);
++src_ptr;
output_ptr += intermediate_height;
}
src_ptr += src_next_row_stride;
output_ptr += intermediate_next_stride;
}
src_ptr = intermediate_buffer;
const int dst_next_row_stride = dst_stride - output_width;
for (i = 0; i < output_height; ++i) {
for (j = 0; j < output_width; ++j) {
// Apply filter...
const int temp = (src_ptr[0] * VFilter[0]) +
(src_ptr[1] * VFilter[1]) +
(src_ptr[2] * VFilter[2]) +
(src_ptr[3] * VFilter[3]) +
(src_ptr[4] * VFilter[4]) +
(src_ptr[5] * VFilter[5]) +
(src_ptr[6] * VFilter[6]) +
(src_ptr[7] * VFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
// Normalize back to 0-255...
*dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT);
src_ptr += intermediate_height;
}
src_ptr += intermediate_next_stride;
dst_ptr += dst_next_row_stride;
}
}
| 174,509 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> methodThatRequiresAllArgsAndThrowsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodThatRequiresAllArgsAndThrows");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
ExceptionCode ec = 0;
{
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0);
RefPtr<TestObj> result = imp->methodThatRequiresAllArgsAndThrows(strArg, objArg, ec);
if (UNLIKELY(ec))
goto fail;
return toV8(result.release(), args.GetIsolate());
}
fail:
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> methodThatRequiresAllArgsAndThrowsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodThatRequiresAllArgsAndThrows");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
ExceptionCode ec = 0;
{
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0);
RefPtr<TestObj> result = imp->methodThatRequiresAllArgsAndThrows(strArg, objArg, ec);
if (UNLIKELY(ec))
goto fail;
return toV8(result.release(), args.GetIsolate());
}
fail:
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
| 171,087 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((p > (datum+length-count)) || (count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
(void) WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int) profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
Commit Message: Fixed SEGV reported in https://github.com/ImageMagick/ImageMagick/issues/130
CWE ID: CWE-20 | static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((count < 0) || (p > (datum+length-count)) ||
(count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
(void) WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int) profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
| 168,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ip6t_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (s->target_offset == sizeof(struct ip6t_entry) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0 &&
unconditional(&s->ipv6)) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP6_TRACE_COMMENT_POLICY]
: comments[NF_IP6_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ip6t_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (unconditional(s) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP6_TRACE_COMMENT_POLICY]
: comments[NF_IP6_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
| 167,374 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GDataRootDirectory::ParseFromString(const std::string& serialized_proto) {
scoped_ptr<GDataRootDirectoryProto> proto(
new GDataRootDirectoryProto());
bool ok = proto->ParseFromString(serialized_proto);
if (ok) {
const std::string& title = proto->gdata_directory().gdata_entry().title();
if (title != "drive") {
LOG(ERROR) << "Incompatible proto detected: " << title;
return false;
}
FromProto(*proto.get());
set_origin(FROM_CACHE);
set_refresh_time(base::Time::Now());
}
return ok;
}
Commit Message: gdata: Define the resource ID for the root directory
Per the spec, the resource ID for the root directory is defined
as "folder:root". Add the resource ID to the root directory in our
file system representation so we can look up the root directory by
the resource ID.
BUG=127697
TEST=add unit tests
Review URL: https://chromiumcodereview.appspot.com/10332253
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool GDataRootDirectory::ParseFromString(const std::string& serialized_proto) {
scoped_ptr<GDataRootDirectoryProto> proto(
new GDataRootDirectoryProto());
bool ok = proto->ParseFromString(serialized_proto);
if (ok) {
const GDataEntryProto& entry_proto =
proto->gdata_directory().gdata_entry();
if (entry_proto.title() != "drive") {
LOG(ERROR) << "Incompatible proto detected (bad title): "
<< entry_proto.title();
return false;
}
// The title field for the root directory was originally empty. Discard
// the proto data if the older format is detected.
if (entry_proto.resource_id() != kGDataRootDirectoryResourceId) {
LOG(ERROR) << "Incompatible proto detected (bad resource ID): "
<< entry_proto.resource_id();
return false;
}
FromProto(*proto.get());
set_origin(FROM_CACHE);
set_refresh_time(base::Time::Now());
}
return ok;
}
| 170,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateString( const char *string )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_String;
item->valuestring = cJSON_strdup( string );
}
return item;
}
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 | cJSON *cJSON_CreateString( const char *string )
| 167,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int efx_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct efx_channel *channel;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &efx_netdev_ops;
SET_ETHTOOL_OPS(net_dev, &efx_ethtool_ops);
/* Clear MAC statistics */
efx->mac_op->update_stats(efx);
memset(&efx->mac_stats, 0, sizeof(efx->mac_stats));
rtnl_lock();
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
efx_update_name(efx);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
efx_for_each_channel(channel, efx) {
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_init_tx_queue_core_txq(tx_queue);
}
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(efx->net_dev);
rtnl_unlock();
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_phy_type);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
goto fail_registered;
}
return 0;
fail_locked:
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
fail_registered:
unregister_netdev(net_dev);
return rc;
}
Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size
[ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ]
Currently an skb requiring TSO may not fit within a minimum-size TX
queue. The TX queue selected for the skb may stall and trigger the TX
watchdog repeatedly (since the problem skb will be retried after the
TX reset). This issue is designated as CVE-2012-3412.
Set the maximum number of TSO segments for our devices to 100. This
should make no difference to behaviour unless the actual MSS is less
than about 700. Increase the minimum TX queue size accordingly to
allow for 2 worst-case skbs, so that there will definitely be space
to add an skb after we wake a queue.
To avoid invalidating existing configurations, change
efx_ethtool_set_ringparam() to fix up values that are too small rather
than returning -EINVAL.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
CWE ID: CWE-189 | static int efx_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct efx_channel *channel;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &efx_netdev_ops;
SET_ETHTOOL_OPS(net_dev, &efx_ethtool_ops);
net_dev->gso_max_segs = EFX_TSO_MAX_SEGS;
/* Clear MAC statistics */
efx->mac_op->update_stats(efx);
memset(&efx->mac_stats, 0, sizeof(efx->mac_stats));
rtnl_lock();
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
efx_update_name(efx);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
efx_for_each_channel(channel, efx) {
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_init_tx_queue_core_txq(tx_queue);
}
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(efx->net_dev);
rtnl_unlock();
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_phy_type);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
goto fail_registered;
}
return 0;
fail_locked:
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
fail_registered:
unregister_netdev(net_dev);
return rc;
}
| 165,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> methodWithNonCallbackArgAndCallbackArgCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodWithNonCallbackArgAndCallbackArg");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, nonCallback, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
if (args.Length() <= 1 || !args[1]->IsFunction())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
RefPtr<TestCallback> callback = V8TestCallback::create(args[1], getScriptExecutionContext());
imp->methodWithNonCallbackArgAndCallbackArg(nonCallback, callback);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> methodWithNonCallbackArgAndCallbackArgCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodWithNonCallbackArgAndCallbackArg");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, nonCallback, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
if (args.Length() <= 1 || !args[1]->IsFunction())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
RefPtr<TestCallback> callback = V8TestCallback::create(args[1], getScriptExecutionContext());
imp->methodWithNonCallbackArgAndCallbackArg(nonCallback, callback);
return v8::Handle<v8::Value>();
}
| 171,089 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
int num_text)
{
int i;
png_debug1(1, "in %s storage function", ((png_ptr == NULL ||
png_ptr->chunk_name[0] == '\0') ?
"text" : (png_const_charp)png_ptr->chunk_name));
if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
return(0);
/* Make sure we have enough space in the "text" array in info_struct
* to hold all of the incoming text_ptr objects.
*/
if (info_ptr->num_text + num_text > info_ptr->max_text)
{
int old_max_text = info_ptr->max_text;
int old_num_text = info_ptr->num_text;
if (info_ptr->text != NULL)
{
png_textp old_text;
info_ptr->max_text = info_ptr->num_text + num_text + 8;
old_text = info_ptr->text;
info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
(png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
if (info_ptr->text == NULL)
{
/* Restore to previous condition */
info_ptr->max_text = old_max_text;
info_ptr->text = old_text;
return(1);
}
png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max_text *
png_sizeof(png_text)));
png_free(png_ptr, old_text);
}
else
{
info_ptr->max_text = num_text + 8;
info_ptr->num_text = 0;
info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
(png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
if (info_ptr->text == NULL)
{
/* Restore to previous condition */
info_ptr->num_text = old_num_text;
info_ptr->max_text = old_max_text;
return(1);
}
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_TEXT;
#endif
}
png_debug1(3, "allocated %d entries for info_ptr->text",
info_ptr->max_text);
}
for (i = 0; i < num_text; i++)
{
png_size_t text_length, key_len;
png_size_t lang_len, lang_key_len;
png_textp textp = &(info_ptr->text[info_ptr->num_text]);
if (text_ptr[i].key == NULL)
continue;
key_len = png_strlen(text_ptr[i].key);
if (text_ptr[i].compression <= 0)
{
lang_len = 0;
lang_key_len = 0;
}
else
#ifdef PNG_iTXt_SUPPORTED
{
/* Set iTXt data */
if (text_ptr[i].lang != NULL)
lang_len = png_strlen(text_ptr[i].lang);
else
lang_len = 0;
if (text_ptr[i].lang_key != NULL)
lang_key_len = png_strlen(text_ptr[i].lang_key);
else
lang_key_len = 0;
}
#else /* PNG_iTXt_SUPPORTED */
{
png_warning(png_ptr, "iTXt chunk not supported.");
continue;
}
#endif
if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
{
text_length = 0;
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[i].compression > 0)
textp->compression = PNG_ITXT_COMPRESSION_NONE;
else
#endif
textp->compression = PNG_TEXT_COMPRESSION_NONE;
}
else
{
text_length = png_strlen(text_ptr[i].text);
textp->compression = text_ptr[i].compression;
}
textp->key = (png_charp)png_malloc_warn(png_ptr,
(png_uint_32)
(key_len + text_length + lang_len + lang_key_len + 4));
if (textp->key == NULL)
return(1);
png_debug2(2, "Allocated %lu bytes at %x in png_set_text",
(png_uint_32)
(key_len + lang_len + lang_key_len + text_length + 4),
(int)textp->key);
png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len));
*(textp->key + key_len) = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[i].compression > 0)
{
textp->lang = textp->key + key_len + 1;
png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
*(textp->lang + lang_len) = '\0';
textp->lang_key = textp->lang + lang_len + 1;
png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
*(textp->lang_key + lang_key_len) = '\0';
textp->text = textp->lang_key + lang_key_len + 1;
}
else
#endif
{
#ifdef PNG_iTXt_SUPPORTED
textp->lang=NULL;
textp->lang_key=NULL;
#endif
textp->text = textp->key + key_len + 1;
}
if (text_length)
png_memcpy(textp->text, text_ptr[i].text,
(png_size_t)(text_length));
*(textp->text + text_length) = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (textp->compression > 0)
{
textp->text_length = 0;
textp->itxt_length = text_length;
}
else
#endif
{
textp->text_length = text_length;
#ifdef PNG_iTXt_SUPPORTED
textp->itxt_length = 0;
#endif
}
info_ptr->num_text++;
png_debug1(3, "transferred text chunk %d", info_ptr->num_text);
}
return(0);
}
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_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
int num_text)
{
int i;
png_debug1(1, "in %s storage function", ((png_ptr == NULL ||
png_ptr->chunk_name[0] == '\0') ?
"text" : (png_const_charp)png_ptr->chunk_name));
if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
return(0);
/* Make sure we have enough space in the "text" array in info_struct
* to hold all of the incoming text_ptr objects.
*/
if (info_ptr->num_text + num_text > info_ptr->max_text)
{
int old_max_text = info_ptr->max_text;
int old_num_text = info_ptr->num_text;
if (info_ptr->text != NULL)
{
png_textp old_text;
info_ptr->max_text = info_ptr->num_text + num_text + 8;
old_text = info_ptr->text;
info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
(png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
if (info_ptr->text == NULL)
{
/* Restore to previous condition */
info_ptr->max_text = old_max_text;
info_ptr->text = old_text;
return(1);
}
png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max_text *
png_sizeof(png_text)));
png_free(png_ptr, old_text);
}
else
{
info_ptr->max_text = num_text + 8;
info_ptr->num_text = 0;
info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
(png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
if (info_ptr->text == NULL)
{
/* Restore to previous condition */
info_ptr->num_text = old_num_text;
info_ptr->max_text = old_max_text;
return(1);
}
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_TEXT;
#endif
}
png_debug1(3, "allocated %d entries for info_ptr->text",
info_ptr->max_text);
}
for (i = 0; i < num_text; i++)
{
png_size_t text_length, key_len;
png_size_t lang_len, lang_key_len;
png_textp textp = &(info_ptr->text[info_ptr->num_text]);
if (text_ptr[i].key == NULL)
continue;
key_len = png_strlen(text_ptr[i].key);
if (text_ptr[i].compression <= 0)
{
lang_len = 0;
lang_key_len = 0;
}
else
#ifdef PNG_iTXt_SUPPORTED
{
/* Set iTXt data */
if (text_ptr[i].lang != NULL)
lang_len = png_strlen(text_ptr[i].lang);
else
lang_len = 0;
if (text_ptr[i].lang_key != NULL)
lang_key_len = png_strlen(text_ptr[i].lang_key);
else
lang_key_len = 0;
}
#else /* PNG_iTXt_SUPPORTED */
{
png_warning(png_ptr, "iTXt chunk not supported.");
continue;
}
#endif
if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
{
text_length = 0;
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[i].compression > 0)
textp->compression = PNG_ITXT_COMPRESSION_NONE;
else
#endif
textp->compression = PNG_TEXT_COMPRESSION_NONE;
}
else
{
text_length = png_strlen(text_ptr[i].text);
textp->compression = text_ptr[i].compression;
}
textp->key = (png_charp)png_malloc_warn(png_ptr,
(png_uint_32)
(key_len + text_length + lang_len + lang_key_len + 4));
if (textp->key == NULL)
return(1);
png_debug2(2, "Allocated %lu bytes at %p in png_set_text",
(png_uint_32)
(key_len + lang_len + lang_key_len + text_length + 4),
textp->key);
png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len));
*(textp->key + key_len) = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[i].compression > 0)
{
textp->lang = textp->key + key_len + 1;
png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
*(textp->lang + lang_len) = '\0';
textp->lang_key = textp->lang + lang_len + 1;
png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
*(textp->lang_key + lang_key_len) = '\0';
textp->text = textp->lang_key + lang_key_len + 1;
}
else
#endif
{
#ifdef PNG_iTXt_SUPPORTED
textp->lang=NULL;
textp->lang_key=NULL;
#endif
textp->text = textp->key + key_len + 1;
}
if (text_length)
png_memcpy(textp->text, text_ptr[i].text,
(png_size_t)(text_length));
*(textp->text + text_length) = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (textp->compression > 0)
{
textp->text_length = 0;
textp->itxt_length = text_length;
}
else
#endif
{
textp->text_length = text_length;
#ifdef PNG_iTXt_SUPPORTED
textp->itxt_length = 0;
#endif
}
info_ptr->num_text++;
png_debug1(3, "transferred text chunk %d", info_ptr->num_text);
}
return(0);
}
| 172,185 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
Commit Message: make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-200 | static int run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (g_settings_privatereports)
{
struct stat statbuf;
if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
error_msg("Path '%s' isn't directory", dirname);
return 404; /* Not Found */
}
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (!gr)
{
error_msg("Group 'abrt' does not exist");
return 500;
}
if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 403;
}
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
| 170,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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: 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 | bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_,
bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id,
long long& val) {
if (!pReader || pos < 0)
return false;
long long total = 0;
long long available = 0;
const long status = pReader->Length(&total, &available);
if (status < 0 || (total >= 0 && available > total))
return false;
long len = 0;
const long long id = ReadID(pReader, pos, len);
if (id < 0 || (available - pos) > len)
return false;
if (static_cast<unsigned long>(id) != expected_id)
return false;
pos += len; // consume id
const long long size = ReadUInt(pReader, pos, len);
if (size < 0 || size > 8 || len < 1 || len > 8 || (available - pos) > len)
return false;
pos += len; // consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
if (val < 0)
return false;
pos += size; // consume size of payload
return true;
}
| 173,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: secret_core_crt (gcry_mpi_t M, gcry_mpi_t C,
gcry_mpi_t D, unsigned int Nlimbs,
gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U)
{
gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 );
gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 );
gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 );
/* m1 = c ^ (d mod (p-1)) mod p */
mpi_sub_ui ( h, P, 1 );
mpi_fdiv_r ( h, D, h );
mpi_powm ( m1, C, h, P );
/* m2 = c ^ (d mod (q-1)) mod q */
mpi_sub_ui ( h, Q, 1 );
mpi_fdiv_r ( h, D, h );
mpi_powm ( m2, C, h, Q );
/* h = u * ( m2 - m1 ) mod q */
mpi_sub ( h, m2, m1 );
/* Remove superfluous leading zeroes from INPUT. */
mpi_normalize (input);
if (!skey->p || !skey->q || !skey->u)
{
secret_core_std (output, input, skey->d, skey->n);
}
else
{
secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n),
skey->p, skey->q, skey->u);
}
}
Commit Message:
CWE ID: CWE-310 | secret_core_crt (gcry_mpi_t M, gcry_mpi_t C,
gcry_mpi_t D, unsigned int Nlimbs,
gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U)
{
gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 );
gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 );
gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 );
gcry_mpi_t D_blind = mpi_alloc_secure ( Nlimbs + 1 );
gcry_mpi_t r;
unsigned int r_nbits;
r_nbits = mpi_get_nbits (P) / 4;
if (r_nbits < 96)
r_nbits = 96;
r = mpi_alloc_secure ( (r_nbits + BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB );
/* d_blind = (d mod (p-1)) + (p-1) * r */
/* m1 = c ^ d_blind mod p */
_gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM);
mpi_set_highbit (r, r_nbits - 1);
mpi_sub_ui ( h, P, 1 );
mpi_mul ( D_blind, h, r );
mpi_fdiv_r ( h, D, h );
mpi_add ( D_blind, D_blind, h );
mpi_powm ( m1, C, D_blind, P );
/* d_blind = (d mod (q-1)) + (q-1) * r */
/* m2 = c ^ d_blind mod q */
_gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM);
mpi_set_highbit (r, r_nbits - 1);
mpi_sub_ui ( h, Q, 1 );
mpi_mul ( D_blind, h, r );
mpi_fdiv_r ( h, D, h );
mpi_add ( D_blind, D_blind, h );
mpi_powm ( m2, C, D_blind, Q );
mpi_free ( r );
mpi_free ( D_blind );
/* h = u * ( m2 - m1 ) mod q */
mpi_sub ( h, m2, m1 );
/* Remove superfluous leading zeroes from INPUT. */
mpi_normalize (input);
if (!skey->p || !skey->q || !skey->u)
{
secret_core_std (output, input, skey->d, skey->n);
}
else
{
secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n),
skey->p, skey->q, skey->u);
}
}
| 165,456 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
{
const sp<ProcessState> proc(ProcessState::self());
status_t err;
const uint8_t *data = parcel->mData;
const binder_size_t *objects = parcel->mObjects;
size_t size = parcel->mObjectsSize;
int startPos = mDataPos;
int firstIndex = -1, lastIndex = -2;
if (len == 0) {
return NO_ERROR;
}
if ((offset > parcel->mDataSize)
|| (len > parcel->mDataSize)
|| (offset + len > parcel->mDataSize)) {
return BAD_VALUE;
}
for (int i = 0; i < (int) size; i++) {
size_t off = objects[i];
if ((off >= offset) && (off < offset + len)) {
if (firstIndex == -1) {
firstIndex = i;
}
lastIndex = i;
}
}
int numObjects = lastIndex - firstIndex + 1;
if ((mDataSize+len) > mDataCapacity) {
err = growData(len);
if (err != NO_ERROR) {
return err;
}
}
memcpy(mData + mDataPos, data + offset, len);
mDataPos += len;
mDataSize += len;
err = NO_ERROR;
if (numObjects > 0) {
if (mObjectsCapacity < mObjectsSize + numObjects) {
int newSize = ((mObjectsSize + numObjects)*3)/2;
binder_size_t *objects =
(binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
if (objects == (binder_size_t*)0) {
return NO_MEMORY;
}
mObjects = objects;
mObjectsCapacity = newSize;
}
int idx = mObjectsSize;
for (int i = firstIndex; i <= lastIndex; i++) {
size_t off = objects[i] - offset + startPos;
mObjects[idx++] = off;
mObjectsSize++;
flat_binder_object* flat
= reinterpret_cast<flat_binder_object*>(mData + off);
acquire_object(proc, *flat, this);
if (flat->type == BINDER_TYPE_FD) {
flat->handle = dup(flat->handle);
flat->cookie = 1;
mHasFds = mFdsKnown = true;
if (!mAllowFds) {
err = FDS_NOT_ALLOWED;
}
}
}
}
return err;
}
Commit Message: Disregard alleged binder entities beyond parcel bounds
When appending one parcel's contents to another, ignore binder
objects within the source Parcel that appear to lie beyond the
formal bounds of that Parcel's data buffer.
Bug 17312693
Change-Id: If592a260f3fcd9a56fc160e7feb2c8b44c73f514
(cherry picked from commit 27182be9f20f4f5b48316666429f09b9ecc1f22e)
CWE ID: CWE-264 | status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
{
const sp<ProcessState> proc(ProcessState::self());
status_t err;
const uint8_t *data = parcel->mData;
const binder_size_t *objects = parcel->mObjects;
size_t size = parcel->mObjectsSize;
int startPos = mDataPos;
int firstIndex = -1, lastIndex = -2;
if (len == 0) {
return NO_ERROR;
}
if ((offset > parcel->mDataSize)
|| (len > parcel->mDataSize)
|| (offset + len > parcel->mDataSize)) {
return BAD_VALUE;
}
for (int i = 0; i < (int) size; i++) {
size_t off = objects[i];
if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
if (firstIndex == -1) {
firstIndex = i;
}
lastIndex = i;
}
}
int numObjects = lastIndex - firstIndex + 1;
if ((mDataSize+len) > mDataCapacity) {
err = growData(len);
if (err != NO_ERROR) {
return err;
}
}
memcpy(mData + mDataPos, data + offset, len);
mDataPos += len;
mDataSize += len;
err = NO_ERROR;
if (numObjects > 0) {
if (mObjectsCapacity < mObjectsSize + numObjects) {
int newSize = ((mObjectsSize + numObjects)*3)/2;
binder_size_t *objects =
(binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
if (objects == (binder_size_t*)0) {
return NO_MEMORY;
}
mObjects = objects;
mObjectsCapacity = newSize;
}
int idx = mObjectsSize;
for (int i = firstIndex; i <= lastIndex; i++) {
size_t off = objects[i] - offset + startPos;
mObjects[idx++] = off;
mObjectsSize++;
flat_binder_object* flat
= reinterpret_cast<flat_binder_object*>(mData + off);
acquire_object(proc, *flat, this);
if (flat->type == BINDER_TYPE_FD) {
flat->handle = dup(flat->handle);
flat->cookie = 1;
mHasFds = mFdsKnown = true;
if (!mAllowFds) {
err = FDS_NOT_ALLOWED;
}
}
}
}
return err;
}
| 173,342 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nft_flush_table(struct nft_ctx *ctx)
{
int err;
struct nft_chain *chain, *nc;
struct nft_set *set, *ns;
list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
ctx->chain = chain;
err = nft_delrule_by_chain(ctx);
if (err < 0)
goto out;
err = nft_delchain(ctx);
if (err < 0)
goto out;
}
list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
if (set->flags & NFT_SET_ANONYMOUS &&
!list_empty(&set->bindings))
continue;
err = nft_delset(ctx, set);
if (err < 0)
goto out;
}
err = nft_deltable(ctx);
out:
return err;
}
Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies
Jumping between chains doesn't mix well with flush ruleset. Rules
from a different chain and set elements may still refer to us.
[ 353.373791] ------------[ cut here ]------------
[ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159!
[ 353.373896] invalid opcode: 0000 [#1] SMP
[ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi
[ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98
[ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010
[...]
[ 353.375018] Call Trace:
[ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540
[ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0
[ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0
[ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790
[ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0
[ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70
[ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30
[ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0
[ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400
[ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90
[ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20
[ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0
[ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80
[ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d
[ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20
[ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b
Release objects in this order: rules -> sets -> chains -> tables, to
make sure no references to chains are held anymore.
Reported-by: Asbjoern Sloth Toennesen <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-19 | static int nft_flush_table(struct nft_ctx *ctx)
{
int err;
struct nft_chain *chain, *nc;
struct nft_set *set, *ns;
list_for_each_entry(chain, &ctx->table->chains, list) {
ctx->chain = chain;
err = nft_delrule_by_chain(ctx);
if (err < 0)
goto out;
}
list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
if (set->flags & NFT_SET_ANONYMOUS &&
!list_empty(&set->bindings))
continue;
err = nft_delset(ctx, set);
if (err < 0)
goto out;
}
list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
ctx->chain = chain;
err = nft_delchain(ctx);
if (err < 0)
goto out;
}
err = nft_deltable(ctx);
out:
return err;
}
| 167,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static pdf_creator_t *new_creator(int *n_elements)
{
pdf_creator_t *daddy;
static const pdf_creator_t creator_template[] =
{
{"Title", ""},
{"Author", ""},
{"Subject", ""},
{"Keywords", ""},
{"Creator", ""},
{"Producer", ""},
{"CreationDate", ""},
{"ModDate", ""},
{"Trapped", ""},
};
daddy = malloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
*n_elements = sizeof(creator_template) / sizeof(creator_template[0]);
return daddy;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787 | static pdf_creator_t *new_creator(int *n_elements)
{
pdf_creator_t *daddy;
static const pdf_creator_t creator_template[] =
{
{"Title", ""},
{"Author", ""},
{"Subject", ""},
{"Keywords", ""},
{"Creator", ""},
{"Producer", ""},
{"CreationDate", ""},
{"ModDate", ""},
{"Trapped", ""},
};
daddy = safe_calloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
*n_elements = sizeof(creator_template) / sizeof(creator_template[0]);
return daddy;
}
| 169,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC)
{
size_t length;
int tag, format, components;
char *value_ptr, tagname[64], cbuf[32], *outside=NULL;
size_t byte_count, offset_val, fpos, fgot;
int64_t byte_count_signed;
xp_field_type *tmp_xp;
#ifdef EXIF_DEBUG
char *dump_data;
int dump_free;
#endif /* EXIF_DEBUG */
/* Protect against corrupt headers */
if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached");
return FALSE;
}
ImageInfo->ifd_nesting_level++;
tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);
format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);
if (!format || format > NUM_FORMATS) {
/* (-1) catches illegal zero case as unsigned underflows to positive large. */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format);
format = TAG_FMT_BYTE;
/*return TRUE;*/
}
if (components < 0) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components);
return FALSE;
}
byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];
if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC));
return FALSE;
}
byte_count = (size_t)byte_count_signed;
if (byte_count > 4) {
offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
/* If its bigger than 4 bytes, the dir entry contains an offset. */
value_ptr = offset_base+offset_val;
/*
dir_entry is ImageInfo->file.list[sn].data+2+i*12
offset_base is ImageInfo->file.list[sn].data-dir_offset
dir_entry - offset_base is dir_offset+2+i*12
*/
if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {
/* It is important to check for IMAGE_FILETYPE_TIFF
* JPEG does not use absolute pointers instead its pointers are
* relative to the start of the TIFF header in APP1 section. */
if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {
if (value_ptr < dir_entry) {
/* we can read this if offset_val > 0 */
/* some files have their values in other parts of the file */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry);
} else {
/* this is for sure not allowed */
/* exception are IFD pointers */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength);
}
return FALSE;
}
if (byte_count>sizeof(cbuf)) {
/* mark as outside range and get buffer */
value_ptr = safe_emalloc(byte_count, 1, 0);
outside = value_ptr;
} else {
/* In most cases we only access a small range so
* it is faster to use a static buffer there
* BUT it offers also the possibility to have
* pointers read without the need to free them
* explicitley before returning. */
memset(&cbuf, 0, sizeof(cbuf));
value_ptr = cbuf;
}
fpos = php_stream_tell(ImageInfo->infile);
php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET);
fgot = php_stream_tell(ImageInfo->infile);
if (fgot!=offset_val) {
EFREE_IF(outside);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val);
return FALSE;
}
fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);
php_stream_seek(ImageInfo->infile, fpos, SEEK_SET);
if (fgot<byte_count) {
EFREE_IF(outside);
EXIF_ERRLOG_FILEEOF(ImageInfo)
return FALSE;
}
}
} else {
/* 4 bytes or less and value is in the dir entry itself */
value_ptr = dir_entry+8;
offset_val= value_ptr-offset_base;
}
ImageInfo->sections_found |= FOUND_ANY_TAG;
#ifdef EXIF_DEBUG
dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data);
if (dump_free) {
efree(dump_data);
}
#endif
if (section_index==SECTION_THUMBNAIL) {
if (!ImageInfo->Thumbnail.data) {
switch(tag) {
case TAG_IMAGEWIDTH:
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_IMAGEHEIGHT:
case TAG_COMP_IMAGE_HEIGHT:
ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_OFFSETS:
case TAG_JPEG_INTERCHANGE_FORMAT:
/* accept both formats */
ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_BYTE_COUNTS:
if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {
ImageInfo->Thumbnail.filetype = ImageInfo->FileType;
} else {
/* motorola is easier to read */
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;
}
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_JPEG_INTERCHANGE_FORMAT_LEN:
if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
}
break;
}
}
} else {
if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)
switch(tag) {
case TAG_COPYRIGHT:
/* check for "<photographer> NUL <editor> NUL" */
if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {
if (length<byte_count-1) {
/* When there are any characters after the first NUL */
ImageInfo->CopyrightPhotographer = estrdup(value_ptr);
ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1);
spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1);
/* format = TAG_FMT_UNDEFINED; this musn't be ASCII */
/* but we are not supposed to change this */
/* keep in mind that image_info does not store editor value */
} else {
ImageInfo->Copyright = estrndup(value_ptr, byte_count);
}
}
break;
case TAG_USERCOMMENT:
ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC);
break;
case TAG_XP_TITLE:
case TAG_XP_COMMENTS:
case TAG_XP_AUTHOR:
case TAG_XP_KEYWORDS:
case TAG_XP_SUBJECT:
tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);
ImageInfo->sections_found |= FOUND_WINXP;
ImageInfo->xp_fields.list = tmp_xp;
ImageInfo->xp_fields.count++;
exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC);
break;
case TAG_FNUMBER:
/* Simplest way of expressing aperture, so I trust it the most.
(overwrite previously computed value if there is one) */
ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_APERTURE:
case TAG_MAX_APERTURE:
/* More relevant info always comes earlier, so only use this field if we don't
have appropriate aperture information yet. */
if (ImageInfo->ApertureFNumber == 0) {
ImageInfo->ApertureFNumber
= (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5);
}
break;
case TAG_SHUTTERSPEED:
/* More complicated way of expressing exposure time, so only use
this value if we don't already have it from somewhere else.
SHUTTERSPEED comes after EXPOSURE TIME
*/
if (ImageInfo->ExposureTime == 0) {
ImageInfo->ExposureTime
= (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)));
}
break;
case TAG_EXPOSURETIME:
ImageInfo->ExposureTime = -1;
break;
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_X_RES:
ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_SUBJECT_DISTANCE:
/* Inidcates the distacne the autofocus camera is focused to.
Tends to be less accurate as distance increases. */
ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_RESOLUTION_UNIT:
switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) {
case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */
case 2:
/* According to the information I was using, 2 measn meters.
But looking at the Cannon powershot's files, inches is the only
sensible value. */
ImageInfo->FocalplaneUnits = 25.4;
break;
case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */
case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */
case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */
}
break;
case TAG_SUB_IFD:
if (format==TAG_FMT_IFD) {
/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */
/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */
/* JPEG do we have the data area and what to do with it */
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD");
}
break;
case TAG_MAKE:
ImageInfo->make = estrndup(value_ptr, byte_count);
break;
case TAG_MODEL:
ImageInfo->model = estrndup(value_ptr, byte_count);
break;
case TAG_MAKER_NOTE:
exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC);
break;
case TAG_EXIF_IFD_POINTER:
case TAG_GPS_IFD_POINTER:
case TAG_INTEROP_IFD_POINTER:
if (ReadNextIFD) {
char *Subdir_start;
int sub_section_index = 0;
switch(tag) {
case TAG_EXIF_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF");
#endif
ImageInfo->sections_found |= FOUND_EXIF;
sub_section_index = SECTION_EXIF;
break;
case TAG_GPS_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS");
#endif
ImageInfo->sections_found |= FOUND_GPS;
sub_section_index = SECTION_GPS;
break;
case TAG_INTEROP_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY");
#endif
ImageInfo->sections_found |= FOUND_INTEROP;
sub_section_index = SECTION_INTEROP;
break;
}
Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);
if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer");
return FALSE;
}
if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) {
return FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index));
#endif
}
}
}
exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC);
EFREE_IF(outside);
return TRUE;
}
Commit Message:
CWE ID: CWE-119 | static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC)
{
size_t length;
int tag, format, components;
char *value_ptr, tagname[64], cbuf[32], *outside=NULL;
size_t byte_count, offset_val, fpos, fgot;
int64_t byte_count_signed;
xp_field_type *tmp_xp;
#ifdef EXIF_DEBUG
char *dump_data;
int dump_free;
#endif /* EXIF_DEBUG */
/* Protect against corrupt headers */
if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached");
return FALSE;
}
ImageInfo->ifd_nesting_level++;
tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);
format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);
if (!format || format > NUM_FORMATS) {
/* (-1) catches illegal zero case as unsigned underflows to positive large. */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format);
format = TAG_FMT_BYTE;
/*return TRUE;*/
}
if (components < 0) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components);
return FALSE;
}
byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];
if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC));
return FALSE;
}
byte_count = (size_t)byte_count_signed;
if (byte_count > 4) {
offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
/* If its bigger than 4 bytes, the dir entry contains an offset. */
value_ptr = offset_base+offset_val;
/*
dir_entry is ImageInfo->file.list[sn].data+2+i*12
offset_base is ImageInfo->file.list[sn].data-dir_offset
dir_entry - offset_base is dir_offset+2+i*12
*/
if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {
/* It is important to check for IMAGE_FILETYPE_TIFF
* JPEG does not use absolute pointers instead its pointers are
* relative to the start of the TIFF header in APP1 section. */
if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {
if (value_ptr < dir_entry) {
/* we can read this if offset_val > 0 */
/* some files have their values in other parts of the file */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry);
} else {
/* this is for sure not allowed */
/* exception are IFD pointers */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength);
}
return FALSE;
}
if (byte_count>sizeof(cbuf)) {
/* mark as outside range and get buffer */
value_ptr = safe_emalloc(byte_count, 1, 0);
outside = value_ptr;
} else {
/* In most cases we only access a small range so
* it is faster to use a static buffer there
* BUT it offers also the possibility to have
* pointers read without the need to free them
* explicitley before returning. */
memset(&cbuf, 0, sizeof(cbuf));
value_ptr = cbuf;
}
fpos = php_stream_tell(ImageInfo->infile);
php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET);
fgot = php_stream_tell(ImageInfo->infile);
if (fgot!=offset_val) {
EFREE_IF(outside);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val);
return FALSE;
}
fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);
php_stream_seek(ImageInfo->infile, fpos, SEEK_SET);
if (fgot<byte_count) {
EFREE_IF(outside);
EXIF_ERRLOG_FILEEOF(ImageInfo)
return FALSE;
}
}
} else {
/* 4 bytes or less and value is in the dir entry itself */
value_ptr = dir_entry+8;
offset_val= value_ptr-offset_base;
}
ImageInfo->sections_found |= FOUND_ANY_TAG;
#ifdef EXIF_DEBUG
dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data);
if (dump_free) {
efree(dump_data);
}
#endif
if (section_index==SECTION_THUMBNAIL) {
if (!ImageInfo->Thumbnail.data) {
switch(tag) {
case TAG_IMAGEWIDTH:
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_IMAGEHEIGHT:
case TAG_COMP_IMAGE_HEIGHT:
ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_OFFSETS:
case TAG_JPEG_INTERCHANGE_FORMAT:
/* accept both formats */
ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_BYTE_COUNTS:
if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {
ImageInfo->Thumbnail.filetype = ImageInfo->FileType;
} else {
/* motorola is easier to read */
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;
}
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_JPEG_INTERCHANGE_FORMAT_LEN:
if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
}
break;
}
}
} else {
if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)
switch(tag) {
case TAG_COPYRIGHT:
/* check for "<photographer> NUL <editor> NUL" */
if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {
if (length<byte_count-1) {
/* When there are any characters after the first NUL */
ImageInfo->CopyrightPhotographer = estrdup(value_ptr);
ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1);
spprintf(&ImageInfo->Copyright, 0, "%s, %s", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor);
/* format = TAG_FMT_UNDEFINED; this musn't be ASCII */
/* but we are not supposed to change this */
/* keep in mind that image_info does not store editor value */
} else {
ImageInfo->Copyright = estrndup(value_ptr, byte_count);
}
}
break;
case TAG_USERCOMMENT:
ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC);
break;
case TAG_XP_TITLE:
case TAG_XP_COMMENTS:
case TAG_XP_AUTHOR:
case TAG_XP_KEYWORDS:
case TAG_XP_SUBJECT:
tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);
ImageInfo->sections_found |= FOUND_WINXP;
ImageInfo->xp_fields.list = tmp_xp;
ImageInfo->xp_fields.count++;
exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC);
break;
case TAG_FNUMBER:
/* Simplest way of expressing aperture, so I trust it the most.
(overwrite previously computed value if there is one) */
ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_APERTURE:
case TAG_MAX_APERTURE:
/* More relevant info always comes earlier, so only use this field if we don't
have appropriate aperture information yet. */
if (ImageInfo->ApertureFNumber == 0) {
ImageInfo->ApertureFNumber
= (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5);
}
break;
case TAG_SHUTTERSPEED:
/* More complicated way of expressing exposure time, so only use
this value if we don't already have it from somewhere else.
SHUTTERSPEED comes after EXPOSURE TIME
*/
if (ImageInfo->ExposureTime == 0) {
ImageInfo->ExposureTime
= (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)));
}
break;
case TAG_EXPOSURETIME:
ImageInfo->ExposureTime = -1;
break;
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_X_RES:
ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_SUBJECT_DISTANCE:
/* Inidcates the distacne the autofocus camera is focused to.
Tends to be less accurate as distance increases. */
ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_RESOLUTION_UNIT:
switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) {
case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */
case 2:
/* According to the information I was using, 2 measn meters.
But looking at the Cannon powershot's files, inches is the only
sensible value. */
ImageInfo->FocalplaneUnits = 25.4;
break;
case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */
case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */
case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */
}
break;
case TAG_SUB_IFD:
if (format==TAG_FMT_IFD) {
/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */
/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */
/* JPEG do we have the data area and what to do with it */
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD");
}
break;
case TAG_MAKE:
ImageInfo->make = estrndup(value_ptr, byte_count);
break;
case TAG_MODEL:
ImageInfo->model = estrndup(value_ptr, byte_count);
break;
case TAG_MAKER_NOTE:
exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC);
break;
case TAG_EXIF_IFD_POINTER:
case TAG_GPS_IFD_POINTER:
case TAG_INTEROP_IFD_POINTER:
if (ReadNextIFD) {
char *Subdir_start;
int sub_section_index = 0;
switch(tag) {
case TAG_EXIF_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF");
#endif
ImageInfo->sections_found |= FOUND_EXIF;
sub_section_index = SECTION_EXIF;
break;
case TAG_GPS_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS");
#endif
ImageInfo->sections_found |= FOUND_GPS;
sub_section_index = SECTION_GPS;
break;
case TAG_INTEROP_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY");
#endif
ImageInfo->sections_found |= FOUND_INTEROP;
sub_section_index = SECTION_INTEROP;
break;
}
Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);
if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer");
return FALSE;
}
if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) {
return FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index));
#endif
}
}
}
exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC);
EFREE_IF(outside);
return TRUE;
}
| 165,032 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(GetProcess(), nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
| 172,787 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
/* ...but clean it before doing the actual write */
vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
/* Check that the address is 32-byte aligned. */
if (vcpu->arch.time_offset &
(sizeof(struct pvclock_vcpu_time_info) - 1))
break;
vcpu->arch.time_page =
gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
if (is_error_page(vcpu->arch.time_page))
vcpu->arch.time_page = NULL;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)
There is a potential use after free issue with the handling of
MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable
memory such as frame buffers then KVM might continue to write to that
address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins
the page in memory so it's unlikely to cause an issue, but if the user
space component re-purposes the memory previously used for the guest, then
the guest will be able to corrupt that memory.
Tested: Tested against kvmclock unit test
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID: CWE-399 | int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
u64 gpa_offset;
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
gpa_offset = data & ~(PAGE_MASK | 1);
/* Check that the address is 32-byte aligned. */
if (gpa_offset & (sizeof(struct pvclock_vcpu_time_info) - 1))
break;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
&vcpu->arch.pv_time, data & ~1ULL))
vcpu->arch.pv_time_enabled = false;
else
vcpu->arch.pv_time_enabled = true;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
| 166,118 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: sf_open (const char *path, int mode, SF_INFO *sfinfo)
{ SF_PRIVATE *psf ;
/* Ultimate sanity check. */
assert (sizeof (sf_count_t) == 8) ;
if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf_log_printf (psf, "File : %s\n", path) ;
if (copy_filename (psf, path) != 0)
{ sf_errno = psf->error ;
return NULL ;
} ;
psf->file.mode = mode ;
if (strcmp (path, "-") == 0)
psf->error = psf_set_stdio (psf) ;
else
psf->error = psf_fopen (psf) ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | sf_open (const char *path, int mode, SF_INFO *sfinfo)
{ SF_PRIVATE *psf ;
/* Ultimate sanity check. */
assert (sizeof (sf_count_t) == 8) ;
if ((psf = psf_allocate ()) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf_log_printf (psf, "File : %s\n", path) ;
if (copy_filename (psf, path) != 0)
{ sf_errno = psf->error ;
return NULL ;
} ;
psf->file.mode = mode ;
if (strcmp (path, "-") == 0)
psf->error = psf_set_stdio (psf) ;
else
psf->error = psf_fopen (psf) ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open */
| 170,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int file_list_cpu(struct file *file)
{
#ifdef CONFIG_SMP
return file->f_sb_list_cpu;
#else
return smp_processor_id();
#endif
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | static inline int file_list_cpu(struct file *file)
| 166,797 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
count,
y;
size_t
length;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Convert HRZ raster image to pixel packets.
*/
image->columns=256;
image->rows=240;
image->depth=8;
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=(size_t) (3*image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if ((size_t) count != length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(4**p++));
SetPixelGreen(q,ScaleCharToQuantum(4**p++));
SetPixelBlue(q,ScaleCharToQuantum(4**p++));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
count,
y;
size_t
length;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Convert HRZ raster image to pixel packets.
*/
image->columns=256;
image->rows=240;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=(size_t) (3*image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if ((size_t) count != length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(4**p++));
SetPixelGreen(q,ScaleCharToQuantum(4**p++));
SetPixelBlue(q,ScaleCharToQuantum(4**p++));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,571 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.auth_capable = new->peer.auth_capable;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
Commit Message: net: sctp: fix slab corruption from use after free on INIT collisions
When hitting an INIT collision case during the 4WHS with AUTH enabled, as
already described in detail in commit 1be9a950c646 ("net: sctp: inherit
auth_capable on INIT collisions"), it can happen that we occasionally
still remotely trigger the following panic on server side which seems to
have been uncovered after the fix from commit 1be9a950c646 ...
[ 533.876389] BUG: unable to handle kernel paging request at 00000000ffffffff
[ 533.913657] IP: [<ffffffff811ac385>] __kmalloc+0x95/0x230
[ 533.940559] PGD 5030f2067 PUD 0
[ 533.957104] Oops: 0000 [#1] SMP
[ 533.974283] Modules linked in: sctp mlx4_en [...]
[ 534.939704] Call Trace:
[ 534.951833] [<ffffffff81294e30>] ? crypto_init_shash_ops+0x60/0xf0
[ 534.984213] [<ffffffff81294e30>] crypto_init_shash_ops+0x60/0xf0
[ 535.015025] [<ffffffff8128c8ed>] __crypto_alloc_tfm+0x6d/0x170
[ 535.045661] [<ffffffff8128d12c>] crypto_alloc_base+0x4c/0xb0
[ 535.074593] [<ffffffff8160bd42>] ? _raw_spin_lock_bh+0x12/0x50
[ 535.105239] [<ffffffffa0418c11>] sctp_inet_listen+0x161/0x1e0 [sctp]
[ 535.138606] [<ffffffff814e43bd>] SyS_listen+0x9d/0xb0
[ 535.166848] [<ffffffff816149a9>] system_call_fastpath+0x16/0x1b
... or depending on the the application, for example this one:
[ 1370.026490] BUG: unable to handle kernel paging request at 00000000ffffffff
[ 1370.026506] IP: [<ffffffff811ab455>] kmem_cache_alloc+0x75/0x1d0
[ 1370.054568] PGD 633c94067 PUD 0
[ 1370.070446] Oops: 0000 [#1] SMP
[ 1370.085010] Modules linked in: sctp kvm_amd kvm [...]
[ 1370.963431] Call Trace:
[ 1370.974632] [<ffffffff8120f7cf>] ? SyS_epoll_ctl+0x53f/0x960
[ 1371.000863] [<ffffffff8120f7cf>] SyS_epoll_ctl+0x53f/0x960
[ 1371.027154] [<ffffffff812100d3>] ? anon_inode_getfile+0xd3/0x170
[ 1371.054679] [<ffffffff811e3d67>] ? __alloc_fd+0xa7/0x130
[ 1371.080183] [<ffffffff816149a9>] system_call_fastpath+0x16/0x1b
With slab debugging enabled, we can see that the poison has been overwritten:
[ 669.826368] BUG kmalloc-128 (Tainted: G W ): Poison overwritten
[ 669.826385] INFO: 0xffff880228b32e50-0xffff880228b32e50. First byte 0x6a instead of 0x6b
[ 669.826414] INFO: Allocated in sctp_auth_create_key+0x23/0x50 [sctp] age=3 cpu=0 pid=18494
[ 669.826424] __slab_alloc+0x4bf/0x566
[ 669.826433] __kmalloc+0x280/0x310
[ 669.826453] sctp_auth_create_key+0x23/0x50 [sctp]
[ 669.826471] sctp_auth_asoc_create_secret+0xcb/0x1e0 [sctp]
[ 669.826488] sctp_auth_asoc_init_active_key+0x68/0xa0 [sctp]
[ 669.826505] sctp_do_sm+0x29d/0x17c0 [sctp] [...]
[ 669.826629] INFO: Freed in kzfree+0x31/0x40 age=1 cpu=0 pid=18494
[ 669.826635] __slab_free+0x39/0x2a8
[ 669.826643] kfree+0x1d6/0x230
[ 669.826650] kzfree+0x31/0x40
[ 669.826666] sctp_auth_key_put+0x19/0x20 [sctp]
[ 669.826681] sctp_assoc_update+0x1ee/0x2d0 [sctp]
[ 669.826695] sctp_do_sm+0x674/0x17c0 [sctp]
Since this only triggers in some collision-cases with AUTH, the problem at
heart is that sctp_auth_key_put() on asoc->asoc_shared_key is called twice
when having refcnt 1, once directly in sctp_assoc_update() and yet again
from within sctp_auth_asoc_init_active_key() via sctp_assoc_update() on
the already kzfree'd memory, which is also consistent with the observation
of the poison decrease from 0x6b to 0x6a (note: the overwrite is detected
at a later point in time when poison is checked on new allocation).
Reference counting of auth keys revisited:
Shared keys for AUTH chunks are being stored in endpoints and associations
in endpoint_shared_keys list. On endpoint creation, a null key is being
added; on association creation, all endpoint shared keys are being cached
and thus cloned over to the association. struct sctp_shared_key only holds
a pointer to the actual key bytes, that is, struct sctp_auth_bytes which
keeps track of users internally through refcounting. Naturally, on assoc
or enpoint destruction, sctp_shared_key are being destroyed directly and
the reference on sctp_auth_bytes dropped.
User space can add keys to either list via setsockopt(2) through struct
sctp_authkey and by passing that to sctp_auth_set_key() which replaces or
adds a new auth key. There, sctp_auth_create_key() creates a new sctp_auth_bytes
with refcount 1 and in case of replacement drops the reference on the old
sctp_auth_bytes. A key can be set active from user space through setsockopt()
on the id via sctp_auth_set_active_key(), which iterates through either
endpoint_shared_keys and in case of an assoc, invokes (one of various places)
sctp_auth_asoc_init_active_key().
sctp_auth_asoc_init_active_key() computes the actual secret from local's
and peer's random, hmac and shared key parameters and returns a new key
directly as sctp_auth_bytes, that is asoc->asoc_shared_key, plus drops
the reference if there was a previous one. The secret, which where we
eventually double drop the ref comes from sctp_auth_asoc_set_secret() with
intitial refcount of 1, which also stays unchanged eventually in
sctp_assoc_update(). This key is later being used for crypto layer to
set the key for the hash in crypto_hash_setkey() from sctp_auth_calculate_hmac().
To close the loop: asoc->asoc_shared_key is freshly allocated secret
material and independant of the sctp_shared_key management keeping track
of only shared keys in endpoints and assocs. Hence, also commit 4184b2a79a76
("net: sctp: fix memory leak in auth key management") is independant of
this bug here since it concerns a different layer (though same structures
being used eventually). asoc->asoc_shared_key is reference dropped correctly
on assoc destruction in sctp_association_free() and when active keys are
being replaced in sctp_auth_asoc_init_active_key(), it always has a refcount
of 1. Hence, it's freed prematurely in sctp_assoc_update(). Simple fix is
to remove that sctp_auth_key_put() from there which fixes these panics.
Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing")
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.auth_capable = new->peer.auth_capable;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
| 166,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_snmp_object_free_storage(void *object TSRMLS_DC)
{
php_snmp_object *intern = (php_snmp_object *)object;
if (!intern) {
return;
}
netsnmp_session_free(&(intern->session));
zend_object_std_dtor(&intern->zo TSRMLS_CC);
efree(intern);
}
Commit Message:
CWE ID: CWE-416 | static void php_snmp_object_free_storage(void *object TSRMLS_DC)
{
php_snmp_object *intern = (php_snmp_object *)object;
if (!intern) {
return;
}
netsnmp_session_free(&(intern->session));
zend_object_std_dtor(&intern->zo TSRMLS_CC);
efree(intern);
}
| 164,977 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline quint32 swapBgrToRgb(quint32 pixel)
{
return ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00);
}
Commit Message: [Qt] Remove an unnecessary masking from swapBgrToRgb()
https://bugs.webkit.org/show_bug.cgi?id=103630
Reviewed by Zoltan Herczeg.
Get rid of a masking command in swapBgrToRgb() to speed up a little bit.
* platform/graphics/qt/GraphicsContext3DQt.cpp:
(WebCore::swapBgrToRgb):
git-svn-id: svn://svn.chromium.org/blink/trunk@136375 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | static inline quint32 swapBgrToRgb(quint32 pixel)
{
return (((pixel << 16) | (pixel >> 16)) & 0x00ff00ff) | (pixel & 0xff00ff00);
}
| 170,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PreconnectManager::Start(const GURL& url,
std::vector<PreconnectRequest> requests) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const std::string host = url.host();
if (preresolve_info_.find(host) != preresolve_info_.end())
return;
auto iterator_and_whether_inserted = preresolve_info_.emplace(
host, std::make_unique<PreresolveInfo>(url, requests.size()));
PreresolveInfo* info = iterator_and_whether_inserted.first->second.get();
for (auto request_it = requests.begin(); request_it != requests.end();
++request_it) {
DCHECK(request_it->origin.GetOrigin() == request_it->origin);
PreresolveJobId job_id = preresolve_jobs_.Add(
std::make_unique<PreresolveJob>(std::move(*request_it), info));
queued_jobs_.push_back(job_id);
}
TryToLaunchPreresolveJobs();
}
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 PreconnectManager::Start(const GURL& url,
std::vector<PreconnectRequest> requests) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const std::string host = url.host();
if (preresolve_info_.find(host) != preresolve_info_.end())
return;
auto iterator_and_whether_inserted = preresolve_info_.emplace(
host, std::make_unique<PreresolveInfo>(url, requests.size()));
PreresolveInfo* info = iterator_and_whether_inserted.first->second.get();
for (auto request_it = requests.begin(); request_it != requests.end();
++request_it) {
PreresolveJobId job_id = preresolve_jobs_.Add(
std::make_unique<PreresolveJob>(std::move(*request_it), info));
queued_jobs_.push_back(job_id);
}
TryToLaunchPreresolveJobs();
}
| 172,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vorbis_book_unpack(oggpack_buffer *opb,codebook *s){
char *lengthlist=NULL;
int quantvals=0;
long i,j;
int maptype;
memset(s,0,sizeof(*s));
/* make sure alignment is correct */
if(oggpack_read(opb,24)!=0x564342)goto _eofout;
/* first the basic parameters */
s->dim=oggpack_read(opb,16);
s->dec_buf=_ogg_malloc(sizeof(ogg_int32_t)*s->dim);
if (s->dec_buf == NULL)
goto _errout;
s->entries=oggpack_read(opb,24);
if(s->entries<=0)goto _eofout;
if(s->dim<=0)goto _eofout;
if(_ilog(s->dim)+_ilog(s->entries)>24)goto _eofout;
if (s->dim > INT_MAX/s->entries) goto _eofout;
/* codeword ordering.... length ordered or unordered? */
switch((int)oggpack_read(opb,1)){
case 0:
/* unordered */
lengthlist=(char *)calloc(s->entries, sizeof(*lengthlist));
if(!lengthlist) goto _eofout;
/* allocated but unused entries? */
if(oggpack_read(opb,1)){
/* yes, unused entries */
for(i=0;i<s->entries;i++){
if(oggpack_read(opb,1)){
long num=oggpack_read(opb,5);
if(num==-1)goto _eofout;
lengthlist[i]=(char)(num+1);
s->used_entries++;
if(num+1>s->dec_maxlength)s->dec_maxlength=num+1;
}else
lengthlist[i]=0;
}
}else{
/* all entries used; no tagging */
s->used_entries=s->entries;
for(i=0;i<s->entries;i++){
long num=oggpack_read(opb,5);
if(num==-1)goto _eofout;
lengthlist[i]=(char)(num+1);
if(num+1>s->dec_maxlength)s->dec_maxlength=num+1;
}
}
break;
case 1:
/* ordered */
{
long length=oggpack_read(opb,5)+1;
s->used_entries=s->entries;
lengthlist=(char *)calloc(s->entries, sizeof(*lengthlist));
if (!lengthlist) goto _eofout;
for(i=0;i<s->entries;){
long num=oggpack_read(opb,_ilog(s->entries-i));
if(num<0)goto _eofout;
for(j=0;j<num && i<s->entries;j++,i++)
lengthlist[i]=(char)length;
s->dec_maxlength=length;
length++;
}
}
break;
default:
/* EOF */
goto _eofout;
}
/* Do we have a mapping to unpack? */
if((maptype=oggpack_read(opb,4))>0){
s->q_min=_float32_unpack(oggpack_read(opb,32),&s->q_minp);
s->q_del=_float32_unpack(oggpack_read(opb,32),&s->q_delp);
s->q_bits=oggpack_read(opb,4)+1;
s->q_seq=oggpack_read(opb,1);
s->q_del>>=s->q_bits;
s->q_delp+=s->q_bits;
}
switch(maptype){
case 0:
/* no mapping; decode type 0 */
/* how many bytes for the indexing? */
/* this is the correct boundary here; we lose one bit to
node/leaf mark */
s->dec_nodeb=_determine_node_bytes(s->used_entries,_ilog(s->entries)/8+1);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,_ilog(s->entries)/8+1);
s->dec_type=0;
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype)) goto _errout;
break;
case 1:
/* mapping type 1; implicit values by lattice position */
quantvals=_book_maptype1_quantvals(s);
/* dec_type choices here are 1,2; 3 doesn't make sense */
{
/* packed values */
long total1=(s->q_bits*s->dim+8)/8; /* remember flag bit */
if (s->dim > (INT_MAX-8)/s->q_bits) goto _eofout;
/* vector of column offsets; remember flag bit */
long total2=(_ilog(quantvals-1)*s->dim+8)/8+(s->q_bits+7)/8;
if(total1<=4 && total1<=total2){
/* use dec_type 1: vector of packed values */
/* need quantized values before */
s->q_val=calloc(sizeof(ogg_uint16_t), quantvals);
if (!s->q_val) goto _eofout;
for(i=0;i<quantvals;i++)
((ogg_uint16_t *)s->q_val)[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits);
if(oggpack_eop(opb)){
goto _eofout;
}
s->dec_type=1;
s->dec_nodeb=_determine_node_bytes(s->used_entries,
(s->q_bits*s->dim+8)/8);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,
(s->q_bits*s->dim+8)/8);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype)){
goto _errout;
}
free(s->q_val);
s->q_val=0;
}else{
/* use dec_type 2: packed vector of column offsets */
/* need quantized values before */
if(s->q_bits<=8){
s->q_val=_ogg_malloc(quantvals);
if (!s->q_val) goto _eofout;
for(i=0;i<quantvals;i++)
((unsigned char *)s->q_val)[i]=(unsigned char)oggpack_read(opb,s->q_bits);
}else{
s->q_val=_ogg_malloc(quantvals*2);
if (!s->q_val) goto _eofout;
for(i=0;i<quantvals;i++)
((ogg_uint16_t *)s->q_val)[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits);
}
if(oggpack_eop(opb))goto _eofout;
s->q_pack=_ilog(quantvals-1);
s->dec_type=2;
s->dec_nodeb=_determine_node_bytes(s->used_entries,
(_ilog(quantvals-1)*s->dim+8)/8);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,
(_ilog(quantvals-1)*s->dim+8)/8);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout;
}
}
break;
case 2:
/* mapping type 2; explicit array of values */
quantvals=s->entries*s->dim;
/* dec_type choices here are 1,3; 2 is not possible */
if( (s->q_bits*s->dim+8)/8 <=4){ /* remember flag bit */
/* use dec_type 1: vector of packed values */
s->dec_type=1;
s->dec_nodeb=_determine_node_bytes(s->used_entries,(s->q_bits*s->dim+8)/8);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,(s->q_bits*s->dim+8)/8);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout;
}else{
/* use dec_type 3: scalar offset into packed value array */
s->dec_type=3;
s->dec_nodeb=_determine_node_bytes(s->used_entries,_ilog(s->used_entries-1)/8+1);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,_ilog(s->used_entries-1)/8+1);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout;
/* get the vals & pack them */
s->q_pack=(s->q_bits+7)/8*s->dim;
s->q_val=_ogg_malloc(s->q_pack*s->used_entries);
if(s->q_bits<=8){
for(i=0;i<s->used_entries*s->dim;i++)
((unsigned char *)(s->q_val))[i]=(unsigned char)oggpack_read(opb,s->q_bits);
}else{
for(i=0;i<s->used_entries*s->dim;i++)
((ogg_uint16_t *)(s->q_val))[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits);
}
}
break;
default:
goto _errout;
}
if (s->dec_nodeb==1)
if (s->dec_leafw == 1)
s->dec_method = 0;
else
s->dec_method = 1;
else if (s->dec_nodeb==2)
if (s->dec_leafw == 1)
s->dec_method = 2;
else
s->dec_method = 3;
else
s->dec_method = 4;
if(oggpack_eop(opb))goto _eofout;
free(lengthlist);
return 0;
_errout:
_eofout:
vorbis_book_clear(s);
free(lengthlist);
free(s->q_val);
return -1;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200 | int vorbis_book_unpack(oggpack_buffer *opb,codebook *s){
char *lengthlist=NULL;
int quantvals=0;
long i,j;
int maptype;
memset(s,0,sizeof(*s));
/* make sure alignment is correct */
if(oggpack_read(opb,24)!=0x564342)goto _eofout;
/* first the basic parameters */
s->dim=oggpack_read(opb,16);
s->dec_buf=_ogg_malloc(sizeof(ogg_int32_t)*s->dim);
if (s->dec_buf == NULL)
goto _errout;
s->entries=oggpack_read(opb,24);
if(s->entries<=0)goto _eofout;
if(s->dim<=0)goto _eofout;
if(_ilog(s->dim)+_ilog(s->entries)>24)goto _eofout;
if (s->dim > INT_MAX/s->entries) goto _eofout;
/* codeword ordering.... length ordered or unordered? */
switch((int)oggpack_read(opb,1)){
case 0:
/* unordered */
lengthlist=(char *)calloc(s->entries, sizeof(*lengthlist));
if(!lengthlist) goto _eofout;
/* allocated but unused entries? */
if(oggpack_read(opb,1)){
/* yes, unused entries */
for(i=0;i<s->entries;i++){
if(oggpack_read(opb,1)){
long num=oggpack_read(opb,5);
if(num==-1)goto _eofout;
lengthlist[i]=(char)(num+1);
s->used_entries++;
if(num+1>s->dec_maxlength)s->dec_maxlength=num+1;
}else
lengthlist[i]=0;
}
}else{
/* all entries used; no tagging */
s->used_entries=s->entries;
for(i=0;i<s->entries;i++){
long num=oggpack_read(opb,5);
if(num==-1)goto _eofout;
lengthlist[i]=(char)(num+1);
if(num+1>s->dec_maxlength)s->dec_maxlength=num+1;
}
}
break;
case 1:
/* ordered */
{
long length=oggpack_read(opb,5)+1;
s->used_entries=s->entries;
lengthlist=(char *)calloc(s->entries, sizeof(*lengthlist));
if (!lengthlist) goto _eofout;
for(i=0;i<s->entries;){
long num=oggpack_read(opb,_ilog(s->entries-i));
if(num<0)goto _eofout;
for(j=0;j<num && i<s->entries;j++,i++)
lengthlist[i]=(char)length;
s->dec_maxlength=length;
length++;
}
}
break;
default:
/* EOF */
goto _eofout;
}
/* Do we have a mapping to unpack? */
if((maptype=oggpack_read(opb,4))>0){
s->q_min=_float32_unpack(oggpack_read(opb,32),&s->q_minp);
s->q_del=_float32_unpack(oggpack_read(opb,32),&s->q_delp);
s->q_bits=oggpack_read(opb,4)+1;
s->q_seq=oggpack_read(opb,1);
s->q_del>>=s->q_bits;
s->q_delp+=s->q_bits;
}
switch(maptype){
case 0:
/* no mapping; decode type 0 */
/* how many bytes for the indexing? */
/* this is the correct boundary here; we lose one bit to
node/leaf mark */
s->dec_nodeb=_determine_node_bytes(s->used_entries,_ilog(s->entries)/8+1);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,_ilog(s->entries)/8+1);
s->dec_type=0;
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype)) goto _errout;
break;
case 1:
/* mapping type 1; implicit values by lattice position */
quantvals=_book_maptype1_quantvals(s);
/* dec_type choices here are 1,2; 3 doesn't make sense */
{
/* packed values */
long total1=(s->q_bits*s->dim+8)/8; /* remember flag bit */
if (s->dim > (INT_MAX-8)/s->q_bits) goto _eofout;
/* vector of column offsets; remember flag bit */
long total2=(_ilog(quantvals-1)*s->dim+8)/8+(s->q_bits+7)/8;
if(total1<=4 && total1<=total2){
/* use dec_type 1: vector of packed values */
/* need quantized values before */
s->q_val=calloc(sizeof(ogg_uint16_t), quantvals);
if (!s->q_val) goto _eofout;
for(i=0;i<quantvals;i++)
((ogg_uint16_t *)s->q_val)[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits);
if(oggpack_eop(opb)){
goto _eofout;
}
s->dec_type=1;
s->dec_nodeb=_determine_node_bytes(s->used_entries,
(s->q_bits*s->dim+8)/8);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,
(s->q_bits*s->dim+8)/8);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype)){
goto _errout;
}
free(s->q_val);
s->q_val=0;
}else{
/* use dec_type 2: packed vector of column offsets */
/* need quantized values before */
if(s->q_bits<=8){
s->q_val=_ogg_malloc(quantvals);
if (!s->q_val) goto _eofout;
for(i=0;i<quantvals;i++)
((unsigned char *)s->q_val)[i]=(unsigned char)oggpack_read(opb,s->q_bits);
}else{
s->q_val=_ogg_malloc(quantvals*2);
if (!s->q_val) goto _eofout;
for(i=0;i<quantvals;i++)
((ogg_uint16_t *)s->q_val)[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits);
}
if(oggpack_eop(opb))goto _eofout;
s->q_pack=_ilog(quantvals-1);
s->dec_type=2;
s->dec_nodeb=_determine_node_bytes(s->used_entries,
(_ilog(quantvals-1)*s->dim+8)/8);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,
(_ilog(quantvals-1)*s->dim+8)/8);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout;
}
}
break;
case 2:
/* mapping type 2; explicit array of values */
quantvals=s->entries*s->dim;
/* dec_type choices here are 1,3; 2 is not possible */
if( (s->q_bits*s->dim+8)/8 <=4){ /* remember flag bit */
/* use dec_type 1: vector of packed values */
s->dec_type=1;
s->dec_nodeb=_determine_node_bytes(s->used_entries,(s->q_bits*s->dim+8)/8);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,(s->q_bits*s->dim+8)/8);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout;
}else{
/* use dec_type 3: scalar offset into packed value array */
s->dec_type=3;
s->dec_nodeb=_determine_node_bytes(s->used_entries,_ilog(s->used_entries-1)/8+1);
s->dec_leafw=_determine_leaf_words(s->dec_nodeb,_ilog(s->used_entries-1)/8+1);
if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout;
/* get the vals & pack them */
s->q_pack=(s->q_bits+7)/8*s->dim;
s->q_val=_ogg_malloc(s->q_pack*s->used_entries);
if(s->q_bits<=8){
for(i=0;i<s->used_entries*s->dim;i++)
((unsigned char *)(s->q_val))[i]=(unsigned char)oggpack_read(opb,s->q_bits);
}else{
for(i=0;i<s->used_entries*s->dim;i++)
((ogg_uint16_t *)(s->q_val))[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits);
}
}
break;
default:
goto _errout;
}
if (s->dec_nodeb==1)
if (s->dec_leafw == 1)
s->dec_method = 0;
else
s->dec_method = 1;
else if (s->dec_nodeb==2)
if (s->dec_leafw == 1)
s->dec_method = 2;
else
s->dec_method = 3;
else
s->dec_method = 4;
if(oggpack_eop(opb))goto _eofout;
free(lengthlist);
return 0;
_errout:
_eofout:
vorbis_book_clear(s);
free(lengthlist);
free(s->q_val);
return -1;
}
| 173,990 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces)
{
if (!element->isFrameOwnerElement())
return;
HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element);
Frame* frame = frameOwner->contentFrame();
if (!frame)
return;
KURL url = frame->document()->url();
if (url.isValid() && !url.isBlankURL())
return;
url = m_serializer->urlForBlankFrame(frame);
appendAttribute(result, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces)
void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, Element* element, Namespaces* namespaces)
{
if (!element->isFrameOwnerElement())
return;
HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element);
Frame* frame = frameOwner->contentFrame();
if (!frame)
return;
KURL url = frame->document()->url();
if (url.isValid() && !url.isBlankURL())
return;
url = m_serializer->urlForBlankFrame(frame);
appendAttribute(out, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces);
}
| 171,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WarmupURLFetcher::FetchWarmupURLNow(
const DataReductionProxyServer& proxy_server) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1,
2);
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Sends a request to the Data Reduction Proxy server to warm up "
"the connection to the proxy."
trigger:
"A network change while the data reduction proxy is enabled will "
"trigger this request."
data: "A specific URL, not related to user data."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via the 'Data Saver' "
"setting. Data Saver is not available on iOS, and on desktop it "
"is enabled by installing the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
GURL warmup_url_with_query_params;
GetWarmupURLWithQueryParam(&warmup_url_with_query_params);
url_loader_.reset();
fetch_timeout_timer_.Stop();
is_fetch_in_flight_ = true;
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = warmup_url_with_query_params;
resource_request->load_flags = net::LOAD_BYPASS_CACHE;
resource_request->render_frame_id = MSG_ROUTING_CONTROL;
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE);
url_loader_->SetAllowHttpErrorResults(true);
fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this,
&WarmupURLFetcher::OnFetchTimeout);
url_loader_->SetOnResponseStartedCallback(base::BindOnce(
&WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this)));
url_loader_->SetOnRedirectCallback(base::BindRepeating(
&WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this)));
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
GetNetworkServiceURLLoaderFactory(proxy_server),
base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete,
base::Unretained(this)));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | void WarmupURLFetcher::FetchWarmupURLNow(
const DataReductionProxyServer& proxy_server) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1,
2);
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Sends a request to the Data Reduction Proxy server to warm up "
"the connection to the proxy."
trigger:
"A network change while the data reduction proxy is enabled will "
"trigger this request."
data: "A specific URL, not related to user data."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via the 'Data Saver' "
"setting. Data Saver is not available on iOS, and on desktop it "
"is enabled by installing the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
GURL warmup_url_with_query_params;
GetWarmupURLWithQueryParam(&warmup_url_with_query_params);
url_loader_.reset();
fetch_timeout_timer_.Stop();
is_fetch_in_flight_ = true;
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = warmup_url_with_query_params;
resource_request->load_flags = net::LOAD_BYPASS_CACHE;
resource_request->render_frame_id = MSG_ROUTING_CONTROL;
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE);
url_loader_->SetAllowHttpErrorResults(true);
fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this,
&WarmupURLFetcher::OnFetchTimeout);
url_loader_->SetOnResponseStartedCallback(base::BindOnce(
&WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this)));
url_loader_->SetOnRedirectCallback(base::BindRepeating(
&WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this)));
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
GetNetworkServiceURLLoaderFactory(proxy_server),
base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete,
base::Unretained(this)));
}
| 172,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
GC_REFCOUNT(ht) = 1;
GC_TYPE_INFO(ht) = IS_ARRAY;
ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;
ht->nTableSize = zend_hash_check_size(nSize);
ht->nTableMask = HT_MIN_MASK;
HT_SET_DATA_ADDR(ht, &uninitialized_bucket);
ht->nNumUsed = 0;
ht->nNumOfElements = 0;
ht->nInternalPointer = HT_INVALID_IDX;
ht->nNextFreeElement = 0;
ht->pDestructor = pDestructor;
}
Commit Message: Fix #73832 - leave the table in a safe state if the size is too big.
CWE ID: CWE-190 | ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
GC_REFCOUNT(ht) = 1;
GC_TYPE_INFO(ht) = IS_ARRAY;
ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;
ht->nTableMask = HT_MIN_MASK;
HT_SET_DATA_ADDR(ht, &uninitialized_bucket);
ht->nNumUsed = 0;
ht->nNumOfElements = 0;
ht->nInternalPointer = HT_INVALID_IDX;
ht->nNextFreeElement = 0;
ht->pDestructor = pDestructor;
ht->nTableSize = zend_hash_check_size(nSize);
}
| 168,410 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
Commit Message: fix error from commit 13585f15c7f7dc28bbbba1661efb280d530d114c
CWE ID: CWE-476 | GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !rem_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
| 170,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mojo::ScopedSharedBufferMapping FakePlatformSensorProvider::GetMapping(
mojom::SensorType type) {
return CreateSharedBufferIfNeeded() ? MapSharedBufferForType(type) : nullptr;
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | mojo::ScopedSharedBufferMapping FakePlatformSensorProvider::GetMapping(
SensorReadingSharedBuffer* FakePlatformSensorProvider::GetSensorReadingBuffer(
mojom::SensorType type) {
return CreateSharedBufferIfNeeded()
? GetSensorReadingSharedBufferForType(type)
: nullptr;
}
| 172,820 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_session_destroy(TSRMLS_D) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
return FAILURE;
}
if (PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
}
php_rinit_session_globals(TSRMLS_C);
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */
{
zval **sym_track = NULL;
IF_SESSION_VARS() {
zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track);
} else {
return;
}
if (sym_track == NULL) {
zval *empty_var;
ALLOC_INIT_ZVAL(empty_var);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0);
}
}
/* }}} */
PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var);
}
return ret;
}
/* }}} */
static void php_session_track_init(TSRMLS_D) /* {{{ */
{
zval *session_vars = NULL;
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
MAKE_STD_ZVAL(session_vars);
array_init(session_vars);
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1);
}
/* }}} */
static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
static void php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return;
}
if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) {
php_session_destroy(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed");
}
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
enum {
Commit Message:
CWE ID: CWE-264 | static int php_session_destroy(TSRMLS_D) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
return FAILURE;
}
if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
}
php_rinit_session_globals(TSRMLS_C);
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */
{
zval **sym_track = NULL;
IF_SESSION_VARS() {
zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track);
} else {
return;
}
if (sym_track == NULL) {
zval *empty_var;
ALLOC_INIT_ZVAL(empty_var);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0);
}
}
/* }}} */
PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var);
}
return ret;
}
/* }}} */
static void php_session_track_init(TSRMLS_D) /* {{{ */
{
zval *session_vars = NULL;
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
MAKE_STD_ZVAL(session_vars);
array_init(session_vars);
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1);
}
/* }}} */
static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
static void php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return;
}
if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) {
php_session_destroy(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed");
}
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
enum {
| 164,873 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void filter_average_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
uint8_t tmp[64 * 64];
assert(output_width <= 64);
assert(output_height <= 64);
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64,
output_width, output_height);
block2d_average_c(tmp, 64, dst_ptr, dst_stride,
output_width, output_height);
}
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 filter_average_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
uint8_t tmp[kMaxDimension * kMaxDimension];
assert(output_width <= kMaxDimension);
assert(output_height <= kMaxDimension);
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64,
output_width, output_height);
block2d_average_c(tmp, 64, dst_ptr, dst_stride,
output_width, output_height);
}
| 174,508 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state,
const BluetoothLEScanOptions* options,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
DCHECK(context);
context->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kInfo,
"Web Bluetooth Scanning is experimental on this platform. See "
"https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/"
"implementation-status.md"));
CHECK(context->IsSecureContext());
auto& doc = *To<Document>(context);
auto* frame = doc.GetFrame();
if (!frame) {
return ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "Document not active"));
}
if (!LocalFrame::HasTransientUserActivation(frame)) {
return ScriptPromise::RejectWithDOMException(
script_state,
MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Must be handling a user gesture to show a permission request."));
}
if (!service_) {
frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest(
&service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI)));
}
auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New();
ConvertRequestLEScanOptions(options, scan_options, exception_state);
if (exception_state.HadException())
return ScriptPromise();
Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url());
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
mojom::blink::WebBluetoothScanClientAssociatedPtrInfo client;
mojo::BindingId id = client_bindings_.AddBinding(
this, mojo::MakeRequest(&client),
context->GetTaskRunner(TaskType::kMiscPlatformAPI));
service_->RequestScanningStart(
std::move(client), std::move(scan_options),
WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this),
WrapPersistent(resolver), id));
return promise;
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <[email protected]>
Reviewed-by: Giovanni Ortuño Urquidi <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119 | ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state,
const BluetoothLEScanOptions* options,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
DCHECK(context);
context->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kInfo,
"Web Bluetooth Scanning is experimental on this platform. See "
"https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/"
"implementation-status.md"));
CHECK(context->IsSecureContext());
auto& doc = *To<Document>(context);
auto* frame = doc.GetFrame();
if (!frame) {
return ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "Document not active"));
}
if (!LocalFrame::HasTransientUserActivation(frame)) {
return ScriptPromise::RejectWithDOMException(
script_state,
MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Must be handling a user gesture to show a permission request."));
}
EnsureServiceConnection();
auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New();
ConvertRequestLEScanOptions(options, scan_options, exception_state);
if (exception_state.HadException())
return ScriptPromise();
Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url());
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
mojom::blink::WebBluetoothScanClientAssociatedPtrInfo client;
mojo::BindingId id = client_bindings_.AddBinding(
this, mojo::MakeRequest(&client),
context->GetTaskRunner(TaskType::kMiscPlatformAPI));
service_->RequestScanningStart(
std::move(client), std::move(scan_options),
WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this),
WrapPersistent(resolver), id));
return promise;
}
| 172,449 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ceph_x_decrypt(struct ceph_crypto_key *secret,
void **p, void *end, void *obuf, size_t olen)
{
struct ceph_x_encrypt_header head;
size_t head_len = sizeof(head);
int len, ret;
len = ceph_decode_32(p);
if (*p + len > end)
return -EINVAL;
dout("ceph_x_decrypt len %d\n", len);
ret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,
*p, len);
if (ret)
return ret;
if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)
return -EPERM;
*p += len;
return olen;
}
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_decrypt(struct ceph_crypto_key *secret,
void **p, void *end, void **obuf, size_t olen)
{
struct ceph_x_encrypt_header head;
size_t head_len = sizeof(head);
int len, ret;
len = ceph_decode_32(p);
if (*p + len > end)
return -EINVAL;
dout("ceph_x_decrypt len %d\n", len);
if (*obuf == NULL) {
*obuf = kmalloc(len, GFP_NOFS);
if (!*obuf)
return -ENOMEM;
olen = len;
}
ret = ceph_decrypt2(secret, &head, &head_len, *obuf, &olen, *p, len);
if (ret)
return ret;
if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)
return -EPERM;
*p += len;
return olen;
}
| 166,262 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProfileImplIOData::LazyInitializeInternal(
ProfileParams* profile_params) const {
clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit;
ChromeURLRequestContext* main_context = main_request_context();
ChromeURLRequestContext* extensions_context = extensions_request_context();
media_request_context_ = new ChromeURLRequestContext;
IOThread* const io_thread = profile_params->io_thread;
IOThread::Globals* const io_thread_globals = io_thread->globals();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool record_mode = chrome::kRecordModeEnabled &&
command_line.HasSwitch(switches::kRecordMode);
bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode);
ApplyProfileParamsToContext(main_context);
ApplyProfileParamsToContext(media_request_context_);
ApplyProfileParamsToContext(extensions_context);
if (http_server_properties_manager_.get())
http_server_properties_manager_->InitializeOnIOThread();
main_context->set_transport_security_state(transport_security_state());
media_request_context_->set_transport_security_state(
transport_security_state());
extensions_context->set_transport_security_state(transport_security_state());
main_context->set_net_log(io_thread->net_log());
media_request_context_->set_net_log(io_thread->net_log());
extensions_context->set_net_log(io_thread->net_log());
main_context->set_network_delegate(network_delegate());
media_request_context_->set_network_delegate(network_delegate());
main_context->set_http_server_properties(http_server_properties());
media_request_context_->set_http_server_properties(http_server_properties());
main_context->set_host_resolver(
io_thread_globals->host_resolver.get());
media_request_context_->set_host_resolver(
io_thread_globals->host_resolver.get());
main_context->set_cert_verifier(
io_thread_globals->cert_verifier.get());
media_request_context_->set_cert_verifier(
io_thread_globals->cert_verifier.get());
main_context->set_http_auth_handler_factory(
io_thread_globals->http_auth_handler_factory.get());
media_request_context_->set_http_auth_handler_factory(
io_thread_globals->http_auth_handler_factory.get());
main_context->set_fraudulent_certificate_reporter(
fraudulent_certificate_reporter());
media_request_context_->set_fraudulent_certificate_reporter(
fraudulent_certificate_reporter());
main_context->set_proxy_service(proxy_service());
media_request_context_->set_proxy_service(proxy_service());
scoped_refptr<net::CookieStore> cookie_store = NULL;
net::OriginBoundCertService* origin_bound_cert_service = NULL;
if (record_mode || playback_mode) {
cookie_store = new net::CookieMonster(
NULL, profile_params->cookie_monster_delegate);
origin_bound_cert_service = new net::OriginBoundCertService(
new net::DefaultOriginBoundCertStore(NULL));
}
if (!cookie_store) {
DCHECK(!lazy_params_->cookie_path.empty());
scoped_refptr<SQLitePersistentCookieStore> cookie_db =
new SQLitePersistentCookieStore(
lazy_params_->cookie_path,
lazy_params_->restore_old_session_cookies);
cookie_db->SetClearLocalStateOnExit(
profile_params->clear_local_state_on_exit);
cookie_store =
new net::CookieMonster(cookie_db.get(),
profile_params->cookie_monster_delegate);
if (command_line.HasSwitch(switches::kEnableRestoreSessionState))
cookie_store->GetCookieMonster()->SetPersistSessionCookies(true);
}
net::CookieMonster* extensions_cookie_store =
new net::CookieMonster(
new SQLitePersistentCookieStore(
lazy_params_->extensions_cookie_path,
lazy_params_->restore_old_session_cookies), NULL);
const char* schemes[] = {chrome::kChromeDevToolsScheme,
chrome::kExtensionScheme};
extensions_cookie_store->SetCookieableSchemes(schemes, 2);
main_context->set_cookie_store(cookie_store);
media_request_context_->set_cookie_store(cookie_store);
extensions_context->set_cookie_store(extensions_cookie_store);
if (!origin_bound_cert_service) {
DCHECK(!lazy_params_->origin_bound_cert_path.empty());
scoped_refptr<SQLiteOriginBoundCertStore> origin_bound_cert_db =
new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path);
origin_bound_cert_db->SetClearLocalStateOnExit(
profile_params->clear_local_state_on_exit);
origin_bound_cert_service = new net::OriginBoundCertService(
new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get()));
}
set_origin_bound_cert_service(origin_bound_cert_service);
main_context->set_origin_bound_cert_service(origin_bound_cert_service);
media_request_context_->set_origin_bound_cert_service(
origin_bound_cert_service);
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
lazy_params_->cache_path,
lazy_params_->cache_max_size,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpCache* main_cache = new net::HttpCache(
main_context->host_resolver(),
main_context->cert_verifier(),
main_context->origin_bound_cert_service(),
main_context->transport_security_state(),
main_context->proxy_service(),
"", // pass empty ssl_session_cache_shard to share the SSL session cache
main_context->ssl_config_service(),
main_context->http_auth_handler_factory(),
main_context->network_delegate(),
main_context->http_server_properties(),
main_context->net_log(),
main_backend);
net::HttpCache::DefaultBackend* media_backend =
new net::HttpCache::DefaultBackend(
net::MEDIA_CACHE, lazy_params_->media_cache_path,
lazy_params_->media_cache_max_size,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpNetworkSession* main_network_session = main_cache->GetSession();
net::HttpCache* media_cache =
new net::HttpCache(main_network_session, media_backend);
if (record_mode || playback_mode) {
main_cache->set_mode(
record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
}
main_http_factory_.reset(main_cache);
media_http_factory_.reset(media_cache);
main_context->set_http_transaction_factory(main_cache);
media_request_context_->set_http_transaction_factory(media_cache);
ftp_factory_.reset(
new net::FtpNetworkLayer(io_thread_globals->host_resolver.get()));
main_context->set_ftp_transaction_factory(ftp_factory_.get());
main_context->set_chrome_url_data_manager_backend(
chrome_url_data_manager_backend());
main_context->set_job_factory(job_factory());
media_request_context_->set_job_factory(job_factory());
extensions_context->set_job_factory(job_factory());
job_factory()->AddInterceptor(
new chrome_browser_net::ConnectInterceptor(predictor_.get()));
lazy_params_.reset();
}
Commit Message: Give the media context an ftp job factory; prevent a browser crash.
BUG=112983
TEST=none
Review URL: http://codereview.chromium.org/9372002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@121378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void ProfileImplIOData::LazyInitializeInternal(
ProfileParams* profile_params) const {
clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit;
ChromeURLRequestContext* main_context = main_request_context();
ChromeURLRequestContext* extensions_context = extensions_request_context();
media_request_context_ = new ChromeURLRequestContext;
IOThread* const io_thread = profile_params->io_thread;
IOThread::Globals* const io_thread_globals = io_thread->globals();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool record_mode = chrome::kRecordModeEnabled &&
command_line.HasSwitch(switches::kRecordMode);
bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode);
ApplyProfileParamsToContext(main_context);
ApplyProfileParamsToContext(media_request_context_);
ApplyProfileParamsToContext(extensions_context);
if (http_server_properties_manager_.get())
http_server_properties_manager_->InitializeOnIOThread();
main_context->set_transport_security_state(transport_security_state());
media_request_context_->set_transport_security_state(
transport_security_state());
extensions_context->set_transport_security_state(transport_security_state());
main_context->set_net_log(io_thread->net_log());
media_request_context_->set_net_log(io_thread->net_log());
extensions_context->set_net_log(io_thread->net_log());
main_context->set_network_delegate(network_delegate());
media_request_context_->set_network_delegate(network_delegate());
main_context->set_http_server_properties(http_server_properties());
media_request_context_->set_http_server_properties(http_server_properties());
main_context->set_host_resolver(
io_thread_globals->host_resolver.get());
media_request_context_->set_host_resolver(
io_thread_globals->host_resolver.get());
main_context->set_cert_verifier(
io_thread_globals->cert_verifier.get());
media_request_context_->set_cert_verifier(
io_thread_globals->cert_verifier.get());
main_context->set_http_auth_handler_factory(
io_thread_globals->http_auth_handler_factory.get());
media_request_context_->set_http_auth_handler_factory(
io_thread_globals->http_auth_handler_factory.get());
main_context->set_fraudulent_certificate_reporter(
fraudulent_certificate_reporter());
media_request_context_->set_fraudulent_certificate_reporter(
fraudulent_certificate_reporter());
main_context->set_proxy_service(proxy_service());
media_request_context_->set_proxy_service(proxy_service());
scoped_refptr<net::CookieStore> cookie_store = NULL;
net::OriginBoundCertService* origin_bound_cert_service = NULL;
if (record_mode || playback_mode) {
cookie_store = new net::CookieMonster(
NULL, profile_params->cookie_monster_delegate);
origin_bound_cert_service = new net::OriginBoundCertService(
new net::DefaultOriginBoundCertStore(NULL));
}
if (!cookie_store) {
DCHECK(!lazy_params_->cookie_path.empty());
scoped_refptr<SQLitePersistentCookieStore> cookie_db =
new SQLitePersistentCookieStore(
lazy_params_->cookie_path,
lazy_params_->restore_old_session_cookies);
cookie_db->SetClearLocalStateOnExit(
profile_params->clear_local_state_on_exit);
cookie_store =
new net::CookieMonster(cookie_db.get(),
profile_params->cookie_monster_delegate);
if (command_line.HasSwitch(switches::kEnableRestoreSessionState))
cookie_store->GetCookieMonster()->SetPersistSessionCookies(true);
}
net::CookieMonster* extensions_cookie_store =
new net::CookieMonster(
new SQLitePersistentCookieStore(
lazy_params_->extensions_cookie_path,
lazy_params_->restore_old_session_cookies), NULL);
const char* schemes[] = {chrome::kChromeDevToolsScheme,
chrome::kExtensionScheme};
extensions_cookie_store->SetCookieableSchemes(schemes, 2);
main_context->set_cookie_store(cookie_store);
media_request_context_->set_cookie_store(cookie_store);
extensions_context->set_cookie_store(extensions_cookie_store);
if (!origin_bound_cert_service) {
DCHECK(!lazy_params_->origin_bound_cert_path.empty());
scoped_refptr<SQLiteOriginBoundCertStore> origin_bound_cert_db =
new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path);
origin_bound_cert_db->SetClearLocalStateOnExit(
profile_params->clear_local_state_on_exit);
origin_bound_cert_service = new net::OriginBoundCertService(
new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get()));
}
set_origin_bound_cert_service(origin_bound_cert_service);
main_context->set_origin_bound_cert_service(origin_bound_cert_service);
media_request_context_->set_origin_bound_cert_service(
origin_bound_cert_service);
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
lazy_params_->cache_path,
lazy_params_->cache_max_size,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpCache* main_cache = new net::HttpCache(
main_context->host_resolver(),
main_context->cert_verifier(),
main_context->origin_bound_cert_service(),
main_context->transport_security_state(),
main_context->proxy_service(),
"", // pass empty ssl_session_cache_shard to share the SSL session cache
main_context->ssl_config_service(),
main_context->http_auth_handler_factory(),
main_context->network_delegate(),
main_context->http_server_properties(),
main_context->net_log(),
main_backend);
net::HttpCache::DefaultBackend* media_backend =
new net::HttpCache::DefaultBackend(
net::MEDIA_CACHE, lazy_params_->media_cache_path,
lazy_params_->media_cache_max_size,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpNetworkSession* main_network_session = main_cache->GetSession();
net::HttpCache* media_cache =
new net::HttpCache(main_network_session, media_backend);
if (record_mode || playback_mode) {
main_cache->set_mode(
record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
}
main_http_factory_.reset(main_cache);
media_http_factory_.reset(media_cache);
main_context->set_http_transaction_factory(main_cache);
media_request_context_->set_http_transaction_factory(media_cache);
ftp_factory_.reset(
new net::FtpNetworkLayer(io_thread_globals->host_resolver.get()));
main_context->set_ftp_transaction_factory(ftp_factory_.get());
media_request_context_->set_ftp_transaction_factory(ftp_factory_.get());
main_context->set_chrome_url_data_manager_backend(
chrome_url_data_manager_backend());
main_context->set_job_factory(job_factory());
media_request_context_->set_job_factory(job_factory());
extensions_context->set_job_factory(job_factory());
job_factory()->AddInterceptor(
new chrome_browser_net::ConnectInterceptor(predictor_.get()));
lazy_params_.reset();
}
| 171,005 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_skcipher(name, type, mask);
}
Commit Message: crypto: algif_skcipher - Require setkey before accept(2)
Some cipher implementations will crash if you try to use them
without calling setkey first. This patch adds a check so that
the accept(2) call will fail with -ENOKEY if setkey hasn't been
done on the socket yet.
Cc: [email protected]
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
CWE ID: CWE-476 | static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
struct skcipher_tfm *tfm;
struct crypto_skcipher *skcipher;
tfm = kzalloc(sizeof(*tfm), GFP_KERNEL);
if (!tfm)
return ERR_PTR(-ENOMEM);
skcipher = crypto_alloc_skcipher(name, type, mask);
if (IS_ERR(skcipher)) {
kfree(tfm);
return ERR_CAST(skcipher);
}
tfm->skcipher = skcipher;
return tfm;
}
| 167,455 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: fbPictureInit (ScreenPtr pScreen, PictFormatPtr formats, int nformats)
{
srcRepeat = FALSE;
if (maskTransform)
maskRepeat = FALSE;
if (!miComputeCompositeRegion (®ion, pSrc, pMask, pDst, xSrc, ySrc,
xMask, yMask, xDst, yDst, width, height))
return;
n = REGION_NUM_RECTS (®ion);
pbox = REGION_RECTS (®ion);
while (n--)
{
h = pbox->y2 - pbox->y1;
y_src = pbox->y1 - yDst + ySrc;
y_msk = pbox->y1 - yDst + yMask;
y_dst = pbox->y1;
while (h)
{
h_this = h;
w = pbox->x2 - pbox->x1;
x_src = pbox->x1 - xDst + xSrc;
x_msk = pbox->x1 - xDst + xMask;
x_dst = pbox->x1;
if (maskRepeat)
{
y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height);
if (h_this > pMask->pDrawable->height - y_msk)
h_this = pMask->pDrawable->height - y_msk;
y_msk += pMask->pDrawable->y;
}
if (srcRepeat)
{
y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height);
if (h_this > pSrc->pDrawable->height - y_src)
h_this = pSrc->pDrawable->height - y_src;
y_src += pSrc->pDrawable->y;
}
while (w)
{
w_this = w;
if (maskRepeat)
{
x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width);
if (w_this > pMask->pDrawable->width - x_msk)
w_this = pMask->pDrawable->width - x_msk;
x_msk += pMask->pDrawable->x;
}
if (srcRepeat)
{
x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width);
if (w_this > pSrc->pDrawable->width - x_src)
w_this = pSrc->pDrawable->width - x_src;
x_src += pSrc->pDrawable->x;
}
(*func) (op, pSrc, pMask, pDst,
x_src, y_src, x_msk, y_msk, x_dst, y_dst,
w_this, h_this);
w -= w_this;
x_src += w_this;
x_msk += w_this;
x_dst += w_this;
}
h -= h_this;
y_src += h_this;
y_msk += h_this;
y_dst += h_this;
}
pbox++;
}
REGION_UNINIT (pDst->pDrawable->pScreen, ®ion);
}
Commit Message:
CWE ID: CWE-189 | fbPictureInit (ScreenPtr pScreen, PictFormatPtr formats, int nformats)
{
srcRepeat = FALSE;
if (maskTransform)
maskRepeat = FALSE;
fbWalkCompositeRegion (op, pSrc, pMask, pDst, xSrc, ySrc,
xMask, yMask, xDst, yDst, width, height,
srcRepeat, maskRepeat, func);
}
| 165,130 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(locale_get_display_region)
{
get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_get_display_region)
PHP_FUNCTION(locale_get_display_region)
{
get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,188 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)
{
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
}
/* Copy overread bytes from last frame into buffer. */
for(; pc->overread>0; pc->overread--){
pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
}
/* flush remaining if EOF */
if(!*buf_size && next == END_NOT_FOUND){
next= 0;
}
pc->last_index= pc->index;
/* copy into buffer end return */
if(next == END_NOT_FOUND){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer)
return AVERROR(ENOMEM);
pc->buffer = new_buffer;
memcpy(&pc->buffer[pc->index], *buf, *buf_size);
pc->index += *buf_size;
return -1;
}
*buf_size=
pc->overread_index= pc->index + next;
/* append to buffer */
if(pc->index){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer)
return AVERROR(ENOMEM);
pc->buffer = new_buffer;
if (next > -FF_INPUT_BUFFER_PADDING_SIZE)
memcpy(&pc->buffer[pc->index], *buf,
next + FF_INPUT_BUFFER_PADDING_SIZE);
pc->index = 0;
*buf= pc->buffer;
}
/* store overread bytes */
for(;next < 0; next++){
pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next];
pc->overread++;
}
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
}
return 0;
}
Commit Message: avcodec/parser: reset indexes on realloc failure
Fixes Ticket2982
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)
{
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
}
/* Copy overread bytes from last frame into buffer. */
for(; pc->overread>0; pc->overread--){
pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
}
/* flush remaining if EOF */
if(!*buf_size && next == END_NOT_FOUND){
next= 0;
}
pc->last_index= pc->index;
/* copy into buffer end return */
if(next == END_NOT_FOUND){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer) {
pc->index = 0;
return AVERROR(ENOMEM);
}
pc->buffer = new_buffer;
memcpy(&pc->buffer[pc->index], *buf, *buf_size);
pc->index += *buf_size;
return -1;
}
*buf_size=
pc->overread_index= pc->index + next;
/* append to buffer */
if(pc->index){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer) {
pc->overread_index =
pc->index = 0;
return AVERROR(ENOMEM);
}
pc->buffer = new_buffer;
if (next > -FF_INPUT_BUFFER_PADDING_SIZE)
memcpy(&pc->buffer[pc->index], *buf,
next + FF_INPUT_BUFFER_PADDING_SIZE);
pc->index = 0;
*buf= pc->buffer;
}
/* store overread bytes */
for(;next < 0; next++){
pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next];
pc->overread++;
}
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
}
return 0;
}
| 165,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: construct_command_line(struct manager_ctx *manager, struct server *server)
{
static char cmd[BUF_SIZE];
char *method = manager->method;
int i;
build_config(working_dir, server);
if (server->method) method = server->method;
memset(cmd, 0, BUF_SIZE);
snprintf(cmd, BUF_SIZE,
"%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf",
executable, method, manager->manager_address,
working_dir, server->port, working_dir, server->port);
if (manager->acl != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl);
}
if (manager->timeout != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout);
}
#ifdef HAVE_SETRLIMIT
if (manager->nofile) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile);
}
#endif
if (manager->user != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user);
}
if (manager->verbose) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -v");
}
if (server->mode == NULL && manager->mode == UDP_ONLY) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -U");
}
if (server->mode == NULL && manager->mode == TCP_AND_UDP) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -u");
}
if (server->fast_open[0] == 0 && manager->fast_open) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --fast-open");
}
if (manager->ipv6first) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -6");
}
if (manager->mtu) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu);
}
if (server->plugin == NULL && manager->plugin) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin);
}
if (server->plugin_opts == NULL && manager->plugin_opts) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts);
}
for (i = 0; i < manager->nameserver_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]);
}
for (i = 0; i < manager->host_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]);
}
{
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --reuse-port");
}
if (verbose) {
LOGI("cmd: %s", cmd);
}
return cmd;
}
Commit Message: Fix #1734
CWE ID: CWE-78 | construct_command_line(struct manager_ctx *manager, struct server *server)
{
static char cmd[BUF_SIZE];
int i;
int port;
port = atoi(server->port);
build_config(working_dir, manager, server);
memset(cmd, 0, BUF_SIZE);
snprintf(cmd, BUF_SIZE,
"%s --manager-address %s -f %s/.shadowsocks_%d.pid -c %s/.shadowsocks_%d.conf",
executable, manager->manager_address, working_dir, port, working_dir, port);
if (manager->acl != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl);
}
if (manager->timeout != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout);
}
#ifdef HAVE_SETRLIMIT
if (manager->nofile) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile);
}
#endif
if (manager->user != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user);
}
if (manager->verbose) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -v");
}
if (server->mode == NULL && manager->mode == UDP_ONLY) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -U");
}
if (server->mode == NULL && manager->mode == TCP_AND_UDP) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -u");
}
if (server->fast_open[0] == 0 && manager->fast_open) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --fast-open");
}
if (manager->ipv6first) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -6");
}
if (manager->mtu) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu);
}
if (server->plugin == NULL && manager->plugin) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin);
}
if (server->plugin_opts == NULL && manager->plugin_opts) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts);
}
for (i = 0; i < manager->nameserver_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]);
}
for (i = 0; i < manager->host_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]);
}
{
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --reuse-port");
}
if (verbose) {
LOGI("cmd: %s", cmd);
}
return cmd;
}
| 167,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL JSTestInterfaceConstructor::constructJSTestInterface(ExecState* exec)
{
JSTestInterfaceConstructor* castedThis = jsCast<JSTestInterfaceConstructor*>(exec->callee());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
ScriptExecutionContext* context = castedThis->scriptExecutionContext();
if (!context)
return throwVMError(exec, createReferenceError(exec, "TestInterface constructor associated document is unavailable"));
RefPtr<TestInterface> object = TestInterface::create(context, str1, str2, ec);
if (ec) {
setDOMException(exec, ec);
return JSValue::encode(JSValue());
}
return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL JSTestInterfaceConstructor::constructJSTestInterface(ExecState* exec)
{
JSTestInterfaceConstructor* castedThis = jsCast<JSTestInterfaceConstructor*>(exec->callee());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
ExceptionCode ec = 0;
const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
ScriptExecutionContext* context = castedThis->scriptExecutionContext();
if (!context)
return throwVMError(exec, createReferenceError(exec, "TestInterface constructor associated document is unavailable"));
RefPtr<TestInterface> object = TestInterface::create(context, str1, str2, ec);
if (ec) {
setDOMException(exec, ec);
return JSValue::encode(JSValue());
}
return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));
}
| 170,574 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int kwajd_read_headers(struct mspack_system *sys,
struct mspack_file *fh,
struct mskwajd_header *hdr)
{
unsigned char buf[16];
int i;
/* read in the header */
if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check for "KWAJ" signature */
if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) ||
((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088))
{
return MSPACK_ERR_SIGNATURE;
}
/* basic header fields */
hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]);
hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]);
hdr->headers = EndGetI16(&buf[kwajh_Flags]);
hdr->length = 0;
hdr->filename = NULL;
hdr->extra = NULL;
hdr->extra_length = 0;
/* optional headers */
/* 4 bytes: length of unpacked file */
if (hdr->headers & MSKWAJ_HDR_HASLENGTH) {
if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;
hdr->length = EndGetI32(&buf[0]);
}
/* 2 bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
}
/* 2 bytes: length of section, then [length] bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK;
}
/* filename and extension */
if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) {
off_t pos = sys->tell(fh);
char *fn = (char *) sys->alloc(sys, (size_t) 13);
/* allocate memory for maximum length filename */
if (! fn) return MSPACK_ERR_NOMEMORY;
hdr->filename = fn;
/* copy filename if present */
if (hdr->headers & MSKWAJ_HDR_HASFILENAME) {
if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ;
for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break;
pos += (i < 9) ? i+1 : 9;
if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START))
return MSPACK_ERR_SEEK;
}
/* copy extension if present */
if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) {
*fn++ = '.';
if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;
for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break;
pos += (i < 4) ? i+1 : 4;
if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START))
return MSPACK_ERR_SEEK;
}
*fn = '\0';
}
/* 2 bytes: extra text length then [length] bytes of extra text data */
if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
hdr->extra = (char *) sys->alloc(sys, (size_t)i+1);
if (! hdr->extra) return MSPACK_ERR_NOMEMORY;
if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ;
hdr->extra[i] = '\0';
hdr->extra_length = i;
}
return MSPACK_ERR_OK;
}
Commit Message: kwaj_read_headers(): fix handling of non-terminated strings
CWE ID: CWE-787 | static int kwajd_read_headers(struct mspack_system *sys,
struct mspack_file *fh,
struct mskwajd_header *hdr)
{
unsigned char buf[16];
int i;
/* read in the header */
if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check for "KWAJ" signature */
if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) ||
((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088))
{
return MSPACK_ERR_SIGNATURE;
}
/* basic header fields */
hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]);
hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]);
hdr->headers = EndGetI16(&buf[kwajh_Flags]);
hdr->length = 0;
hdr->filename = NULL;
hdr->extra = NULL;
hdr->extra_length = 0;
/* optional headers */
/* 4 bytes: length of unpacked file */
if (hdr->headers & MSKWAJ_HDR_HASLENGTH) {
if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;
hdr->length = EndGetI32(&buf[0]);
}
/* 2 bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
}
/* 2 bytes: length of section, then [length] bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK;
}
/* filename and extension */
if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) {
int len;
/* allocate memory for maximum length filename */
char *fn = (char *) sys->alloc(sys, (size_t) 13);
if (!(hdr->filename = fn)) return MSPACK_ERR_NOMEMORY;
/* copy filename if present */
if (hdr->headers & MSKWAJ_HDR_HASFILENAME) {
/* read and copy up to 9 bytes of a null terminated string */
if ((len = sys->read(fh, &buf[0], 9)) < 2) return MSPACK_ERR_READ;
for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break;
/* if string was 9 bytes with no null terminator, reject it */
if (i == 9 && buf[8] != '\0') return MSPACK_ERR_DATAFORMAT;
/* seek to byte after string ended in file */
if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR))
return MSPACK_ERR_SEEK;
fn--; /* remove the null terminator */
}
/* copy extension if present */
if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) {
*fn++ = '.';
/* read and copy up to 4 bytes of a null terminated string */
if ((len = sys->read(fh, &buf[0], 4)) < 2) return MSPACK_ERR_READ;
for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break;
/* if string was 4 bytes with no null terminator, reject it */
if (i == 4 && buf[3] != '\0') return MSPACK_ERR_DATAFORMAT;
/* seek to byte after string ended in file */
if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR))
return MSPACK_ERR_SEEK;
fn--; /* remove the null terminator */
}
*fn = '\0';
}
/* 2 bytes: extra text length then [length] bytes of extra text data */
if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
hdr->extra = (char *) sys->alloc(sys, (size_t)i+1);
if (! hdr->extra) return MSPACK_ERR_NOMEMORY;
if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ;
hdr->extra[i] = '\0';
hdr->extra_length = i;
}
return MSPACK_ERR_OK;
}
| 169,111 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gss_iakerbmechglue_init(void)
{
struct gss_mech_config mech_iakerb;
struct gss_config iakerb_mechanism = krb5_mechanism;
/* IAKERB mechanism mirrors krb5, but with different context SPIs */
iakerb_mechanism.gss_accept_sec_context = iakerb_gss_accept_sec_context;
iakerb_mechanism.gss_init_sec_context = iakerb_gss_init_sec_context;
iakerb_mechanism.gss_delete_sec_context = iakerb_gss_delete_sec_context;
iakerb_mechanism.gss_acquire_cred = iakerb_gss_acquire_cred;
iakerb_mechanism.gssspi_acquire_cred_with_password
= iakerb_gss_acquire_cred_with_password;
memset(&mech_iakerb, 0, sizeof(mech_iakerb));
mech_iakerb.mech = &iakerb_mechanism;
mech_iakerb.mechNameStr = "iakerb";
mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb;
gssint_register_mechinfo(&mech_iakerb);
return 0;
}
Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696]
The IAKERB mechanism currently replaces its context handle with the
krb5 mechanism handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the IAKERB context structure after context
establishment and add new IAKERB entry points to refer to it with that
type. Add initiate and established flags to the IAKERB context
structure for use in gss_inquire_context() prior to context
establishment.
CVE-2015-2696:
In MIT krb5 1.9 and later, applications which call
gss_inquire_context() on a partially-established IAKERB context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. Java server applications using the
native JGSS provider are vulnerable to this bug. A carefully crafted
IAKERB packet might allow the gss_inquire_context() call to succeed
with attacker-determined results, but applications should not make
access control decisions based on gss_inquire_context() results prior
to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | static int gss_iakerbmechglue_init(void)
{
struct gss_mech_config mech_iakerb;
memset(&mech_iakerb, 0, sizeof(mech_iakerb));
mech_iakerb.mech = &iakerb_mechanism;
mech_iakerb.mechNameStr = "iakerb";
mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb;
gssint_register_mechinfo(&mech_iakerb);
return 0;
}
| 166,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION,
SyncPromoUI::SOURCE_UNKNOWN);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
| 171,247 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
Commit Message: Should not call `initialize_copy` for `TT_ICLASS`; fix #4027
Since `TT_ICLASS` is a internal object that should never be revealed
to Ruby world.
CWE ID: CWE-824 | init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_ICLASS:
copy_class(mrb, dest, obj);
return;
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
| 169,206 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> uniformMatrixHelper(const v8::Arguments& args,
int matrixSize)
{
if (args.Length() != 3)
return V8Proxy::throwNotEnoughArgumentsError();
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
bool ok = false;
WebGLUniformLocation* location = toWebGLUniformLocation(args[0], ok);
bool transpose = args[1]->BooleanValue();
if (V8Float32Array::HasInstance(args[2])) {
Float32Array* array = V8Float32Array::toNative(args[2]->ToObject());
ASSERT(array != NULL);
ExceptionCode ec = 0;
switch (matrixSize) {
case 2: context->uniformMatrix2fv(location, transpose, array, ec); break;
case 3: context->uniformMatrix3fv(location, transpose, array, ec); break;
case 4: context->uniformMatrix4fv(location, transpose, array, ec); break;
default: ASSERT_NOT_REACHED(); break;
}
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
if (args[2].IsEmpty() || !args[2]->IsArray()) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
v8::Handle<v8::Array> array =
v8::Local<v8::Array>::Cast(args[2]);
uint32_t len = array->Length();
float* data = jsArrayToFloatArray(array, len);
if (!data) {
V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate());
return notHandledByInterceptor();
}
ExceptionCode ec = 0;
switch (matrixSize) {
case 2: context->uniformMatrix2fv(location, transpose, data, len, ec); break;
case 3: context->uniformMatrix3fv(location, transpose, data, len, ec); break;
case 4: context->uniformMatrix4fv(location, transpose, data, len, ec); break;
default: ASSERT_NOT_REACHED(); break;
}
fastFree(data);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> uniformMatrixHelper(const v8::Arguments& args,
int matrixSize)
{
if (args.Length() != 3)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
bool ok = false;
WebGLUniformLocation* location = toWebGLUniformLocation(args[0], ok);
bool transpose = args[1]->BooleanValue();
if (V8Float32Array::HasInstance(args[2])) {
Float32Array* array = V8Float32Array::toNative(args[2]->ToObject());
ASSERT(array != NULL);
ExceptionCode ec = 0;
switch (matrixSize) {
case 2: context->uniformMatrix2fv(location, transpose, array, ec); break;
case 3: context->uniformMatrix3fv(location, transpose, array, ec); break;
case 4: context->uniformMatrix4fv(location, transpose, array, ec); break;
default: ASSERT_NOT_REACHED(); break;
}
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
if (args[2].IsEmpty() || !args[2]->IsArray()) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
v8::Handle<v8::Array> array =
v8::Local<v8::Array>::Cast(args[2]);
uint32_t len = array->Length();
float* data = jsArrayToFloatArray(array, len);
if (!data) {
V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate());
return notHandledByInterceptor();
}
ExceptionCode ec = 0;
switch (matrixSize) {
case 2: context->uniformMatrix2fv(location, transpose, data, len, ec); break;
case 3: context->uniformMatrix3fv(location, transpose, data, len, ec); break;
case 4: context->uniformMatrix4fv(location, transpose, data, len, ec); break;
default: ASSERT_NOT_REACHED(); break;
}
fastFree(data);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
| 171,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const SystemProfileProto& MetricsLog::RecordEnvironment(
DelegatingProvider* delegating_provider) {
DCHECK(!has_environment_);
has_environment_ = true;
SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
system_profile);
std::string brand_code;
if (client_->GetBrand(&brand_code))
system_profile->set_brand_code(brand_code);
SystemProfileProto::Hardware::CPU* cpu =
system_profile->mutable_hardware()->mutable_cpu();
base::CPU cpu_info;
cpu->set_vendor_name(cpu_info.vendor_name());
cpu->set_signature(cpu_info.signature());
cpu->set_num_cores(base::SysInfo::NumberOfProcessors());
delegating_provider->ProvideSystemProfileMetrics(system_profile);
return *system_profile;
}
Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM.
Bug: 907674
Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2
Reviewed-on: https://chromium-review.googlesource.com/c/1381376
Commit-Queue: Nik Bhagat <[email protected]>
Reviewed-by: Robert Kaplow <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618037}
CWE ID: CWE-79 | const SystemProfileProto& MetricsLog::RecordEnvironment(
DelegatingProvider* delegating_provider) {
DCHECK(!has_environment_);
has_environment_ = true;
SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
system_profile);
std::string brand_code;
if (client_->GetBrand(&brand_code))
system_profile->set_brand_code(brand_code);
delegating_provider->ProvideSystemProfileMetrics(system_profile);
return *system_profile;
}
| 172,072 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: monitor_apply_keystate(struct monitor *pmonitor)
{
struct ssh *ssh = active_state; /* XXX */
struct kex *kex;
int r;
debug3("%s: packet_set_state", __func__);
if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
sshbuf_free(child_state);
child_state = NULL;
if ((kex = ssh->kex) != NULL) {
/* XXX set callbacks */
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
#endif
kex->kex[KEX_C25519_SHA256] = kexc25519_server;
kex->load_host_public_key=&get_hostkey_public_by_type;
kex->load_host_private_key=&get_hostkey_private_by_type;
kex->host_key_index=&get_hostkey_index;
kex->sign = sshd_hostkey_sign;
}
/* Update with new address */
if (options.compression) {
ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | monitor_apply_keystate(struct monitor *pmonitor)
{
struct ssh *ssh = active_state; /* XXX */
struct kex *kex;
int r;
debug3("%s: packet_set_state", __func__);
if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
sshbuf_free(child_state);
child_state = NULL;
if ((kex = ssh->kex) != NULL) {
/* XXX set callbacks */
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
#endif
kex->kex[KEX_C25519_SHA256] = kexc25519_server;
kex->load_host_public_key=&get_hostkey_public_by_type;
kex->load_host_private_key=&get_hostkey_private_by_type;
kex->host_key_index=&get_hostkey_index;
kex->sign = sshd_hostkey_sign;
}
}
| 168,648 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request,
ProfileIOData* io_data,
int child_id,
int route_id) {
std::string google_chrome_signin_value;
std::string google_accounts_signin_value;
request->GetResponseHeaderByName("Google-Chrome-SignIn",
&google_chrome_signin_value);
request->GetResponseHeaderByName("Google-Accounts-SignIn",
&google_accounts_signin_value);
if (!google_accounts_signin_value.empty() ||
!google_chrome_signin_value.empty()) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " g-a-s='" << google_accounts_signin_value << "'"
<< " g-c-s='" << google_chrome_signin_value << "'";
}
if (!gaia::IsGaiaSignonRealm(request->original_url().GetOrigin()))
return;
std::vector<std::pair<std::string, std::string> > pairs;
base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',',
&pairs);
std::string session_index;
std::string email;
for (size_t i = 0; i < pairs.size(); ++i) {
const std::pair<std::string, std::string>& pair = pairs[i];
const std::string& key = pair.first;
const std::string& value = pair.second;
if (key == "email") {
TrimString(value, "\"", &email);
} else if (key == "sessionindex") {
session_index = value;
}
}
if (!email.empty())
io_data->set_reverse_autologin_pending_email(email);
if (!email.empty() || !session_index.empty()) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " email=" << email
<< " sessionindex=" << session_index;
}
AutoAccept auto_accept = AUTO_ACCEPT_NONE;
signin::Source source = signin::SOURCE_UNKNOWN;
GURL continue_url;
std::vector<std::string> tokens;
base::SplitString(google_chrome_signin_value, ',', &tokens);
for (size_t i = 0; i < tokens.size(); ++i) {
const std::string& token = tokens[i];
if (token == "accepted") {
auto_accept = AUTO_ACCEPT_ACCEPTED;
} else if (token == "configure") {
auto_accept = AUTO_ACCEPT_CONFIGURE;
} else if (token == "rejected-for-profile") {
auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE;
}
}
source = GetSigninSource(request->url(), &continue_url);
if (source != signin::SOURCE_UNKNOWN)
auto_accept = AUTO_ACCEPT_EXPLICIT;
if (auto_accept != AUTO_ACCEPT_NONE) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " auto_accept=" << auto_accept;
}
if (session_index.empty() && email.empty() &&
auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) {
return;
}
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index,
email, auto_accept, source, continue_url, child_id, route_id));
}
Commit Message: During redirects in the one click sign in flow, check the current URL
instead of original URL to validate gaia http headers.
BUG=307159
Review URL: https://codereview.chromium.org/77343002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@236563 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | void OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request,
ProfileIOData* io_data,
int child_id,
int route_id) {
std::string google_chrome_signin_value;
std::string google_accounts_signin_value;
request->GetResponseHeaderByName("Google-Chrome-SignIn",
&google_chrome_signin_value);
request->GetResponseHeaderByName("Google-Accounts-SignIn",
&google_accounts_signin_value);
if (!google_accounts_signin_value.empty() ||
!google_chrome_signin_value.empty()) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " g-a-s='" << google_accounts_signin_value << "'"
<< " g-c-s='" << google_chrome_signin_value << "'";
}
if (!gaia::IsGaiaSignonRealm(request->url().GetOrigin()))
return;
std::vector<std::pair<std::string, std::string> > pairs;
base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',',
&pairs);
std::string session_index;
std::string email;
for (size_t i = 0; i < pairs.size(); ++i) {
const std::pair<std::string, std::string>& pair = pairs[i];
const std::string& key = pair.first;
const std::string& value = pair.second;
if (key == "email") {
TrimString(value, "\"", &email);
} else if (key == "sessionindex") {
session_index = value;
}
}
if (!email.empty())
io_data->set_reverse_autologin_pending_email(email);
if (!email.empty() || !session_index.empty()) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " email=" << email
<< " sessionindex=" << session_index;
}
AutoAccept auto_accept = AUTO_ACCEPT_NONE;
signin::Source source = signin::SOURCE_UNKNOWN;
GURL continue_url;
std::vector<std::string> tokens;
base::SplitString(google_chrome_signin_value, ',', &tokens);
for (size_t i = 0; i < tokens.size(); ++i) {
const std::string& token = tokens[i];
if (token == "accepted") {
auto_accept = AUTO_ACCEPT_ACCEPTED;
} else if (token == "configure") {
auto_accept = AUTO_ACCEPT_CONFIGURE;
} else if (token == "rejected-for-profile") {
auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE;
}
}
source = GetSigninSource(request->url(), &continue_url);
if (source != signin::SOURCE_UNKNOWN)
auto_accept = AUTO_ACCEPT_EXPLICIT;
if (auto_accept != AUTO_ACCEPT_NONE) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " auto_accept=" << auto_accept;
}
if (session_index.empty() && email.empty() &&
auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) {
return;
}
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index,
email, auto_accept, source, continue_url, child_id, route_id));
}
| 171,136 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
if (pkt->size >= 7 &&
pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
uint8_t desc[256];
int score = AVPROBE_SCORE_EXTENSION, ret;
AVIStream *ast = st->priv_data;
AVInputFormat *sub_demuxer;
AVRational time_base;
int size;
AVIOContext *pb = avio_alloc_context(pkt->data + 7,
pkt->size - 7,
0, NULL, NULL, NULL, NULL);
AVProbeData pd;
unsigned int desc_len = avio_rl32(pb);
if (desc_len > pb->buf_end - pb->buf_ptr)
goto error;
ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
avio_skip(pb, desc_len - ret);
if (*desc)
av_dict_set(&st->metadata, "title", desc, 0);
avio_rl16(pb); /* flags? */
avio_rl32(pb); /* data size */
size = pb->buf_end - pb->buf_ptr;
pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
.buf_size = size };
if (!pd.buf)
goto error;
memcpy(pd.buf, pb->buf_ptr, size);
sub_demuxer = av_probe_input_format2(&pd, 1, &score);
av_freep(&pd.buf);
if (!sub_demuxer)
goto error;
if (!(ast->sub_ctx = avformat_alloc_context()))
goto error;
ast->sub_ctx->pb = pb;
if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
goto error;
if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
if (ast->sub_ctx->nb_streams != 1)
goto error;
ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
time_base = ast->sub_ctx->streams[0]->time_base;
avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
}
ast->sub_buffer = pkt->data;
memset(pkt, 0, sizeof(*pkt));
return 1;
error:
av_freep(&ast->sub_ctx);
av_freep(&pb);
}
return 0;
}
Commit Message: avformat/avidec: Limit formats in gab2 to srt and ass/ssa
This prevents part of one exploit leading to an information leak
Found-by: Emil Lerner and Pavel Cheremushkin
Reported-by: Thierry Foucu <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-200 | static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
if (pkt->size >= 7 &&
pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
uint8_t desc[256];
int score = AVPROBE_SCORE_EXTENSION, ret;
AVIStream *ast = st->priv_data;
AVInputFormat *sub_demuxer;
AVRational time_base;
int size;
AVIOContext *pb = avio_alloc_context(pkt->data + 7,
pkt->size - 7,
0, NULL, NULL, NULL, NULL);
AVProbeData pd;
unsigned int desc_len = avio_rl32(pb);
if (desc_len > pb->buf_end - pb->buf_ptr)
goto error;
ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
avio_skip(pb, desc_len - ret);
if (*desc)
av_dict_set(&st->metadata, "title", desc, 0);
avio_rl16(pb); /* flags? */
avio_rl32(pb); /* data size */
size = pb->buf_end - pb->buf_ptr;
pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
.buf_size = size };
if (!pd.buf)
goto error;
memcpy(pd.buf, pb->buf_ptr, size);
sub_demuxer = av_probe_input_format2(&pd, 1, &score);
av_freep(&pd.buf);
if (!sub_demuxer)
goto error;
if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass"))
goto error;
if (!(ast->sub_ctx = avformat_alloc_context()))
goto error;
ast->sub_ctx->pb = pb;
if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
goto error;
if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
if (ast->sub_ctx->nb_streams != 1)
goto error;
ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
time_base = ast->sub_ctx->streams[0]->time_base;
avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
}
ast->sub_buffer = pkt->data;
memset(pkt, 0, sizeof(*pkt));
return 1;
error:
av_freep(&ast->sub_ctx);
av_freep(&pb);
}
return 0;
}
| 168,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long gfs2_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
loff_t bytes, max_bytes;
struct gfs2_alloc *al;
int error;
loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1);
loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift;
next = (next + 1) << sdp->sd_sb.sb_bsize_shift;
/* We only support the FALLOC_FL_KEEP_SIZE mode */
if (mode & ~FALLOC_FL_KEEP_SIZE)
return -EOPNOTSUPP;
offset &= bsize_mask;
len = next - offset;
bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2;
if (!bytes)
bytes = UINT_MAX;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh);
error = gfs2_glock_nq(&ip->i_gh);
if (unlikely(error))
goto out_uninit;
if (!gfs2_write_alloc_required(ip, offset, len))
goto out_unlock;
while (len > 0) {
if (len < bytes)
bytes = len;
al = gfs2_alloc_get(ip);
if (!al) {
error = -ENOMEM;
goto out_unlock;
}
error = gfs2_quota_lock_check(ip);
if (error)
goto out_alloc_put;
retry:
gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
error = gfs2_inplace_reserve(ip);
if (error) {
if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) {
bytes >>= 1;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
goto retry;
}
goto out_qunlock;
}
max_bytes = bytes;
calc_max_reserv(ip, len, &max_bytes, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +
RES_RG_HDR + gfs2_rg_blocks(ip);
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
error = gfs2_trans_begin(sdp, rblocks,
PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize);
if (error)
goto out_trans_fail;
error = fallocate_chunk(inode, offset, max_bytes, mode);
gfs2_trans_end(sdp);
if (error)
goto out_trans_fail;
len -= max_bytes;
offset += max_bytes;
gfs2_inplace_release(ip);
gfs2_quota_unlock(ip);
gfs2_alloc_put(ip);
}
goto out_unlock;
out_trans_fail:
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
out_alloc_put:
gfs2_alloc_put(ip);
out_unlock:
gfs2_glock_dq(&ip->i_gh);
out_uninit:
gfs2_holder_uninit(&ip->i_gh);
return error;
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <[email protected]>
Signed-off-by: Steven Whitehouse <[email protected]>
CWE ID: CWE-119 | static long gfs2_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
loff_t bytes, max_bytes;
struct gfs2_alloc *al;
int error;
loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1);
loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift;
loff_t max_chunk_size = UINT_MAX & bsize_mask;
next = (next + 1) << sdp->sd_sb.sb_bsize_shift;
/* We only support the FALLOC_FL_KEEP_SIZE mode */
if (mode & ~FALLOC_FL_KEEP_SIZE)
return -EOPNOTSUPP;
offset &= bsize_mask;
len = next - offset;
bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2;
if (!bytes)
bytes = UINT_MAX;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh);
error = gfs2_glock_nq(&ip->i_gh);
if (unlikely(error))
goto out_uninit;
if (!gfs2_write_alloc_required(ip, offset, len))
goto out_unlock;
while (len > 0) {
if (len < bytes)
bytes = len;
al = gfs2_alloc_get(ip);
if (!al) {
error = -ENOMEM;
goto out_unlock;
}
error = gfs2_quota_lock_check(ip);
if (error)
goto out_alloc_put;
retry:
gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
error = gfs2_inplace_reserve(ip);
if (error) {
if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) {
bytes >>= 1;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
goto retry;
}
goto out_qunlock;
}
max_bytes = bytes;
calc_max_reserv(ip, (len > max_chunk_size)? max_chunk_size: len,
&max_bytes, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +
RES_RG_HDR + gfs2_rg_blocks(ip);
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
error = gfs2_trans_begin(sdp, rblocks,
PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize);
if (error)
goto out_trans_fail;
error = fallocate_chunk(inode, offset, max_bytes, mode);
gfs2_trans_end(sdp);
if (error)
goto out_trans_fail;
len -= max_bytes;
offset += max_bytes;
gfs2_inplace_release(ip);
gfs2_quota_unlock(ip);
gfs2_alloc_put(ip);
}
goto out_unlock;
out_trans_fail:
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
out_alloc_put:
gfs2_alloc_put(ip);
out_unlock:
gfs2_glock_dq(&ip->i_gh);
out_uninit:
gfs2_holder_uninit(&ip->i_gh);
return error;
}
| 166,213 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::CancelPairing() {
if (!RunPairingCallbacks(CANCELLED)) {
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
UnregisterAgent();
}
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::CancelPairing() {
if (!pairing_context_.get() || !pairing_context_->CancelPairing()) {
VLOG(1) << object_path_.value() << ": No pairing context or callback. "
<< "Sending explicit cancel";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
// delegate is going to be freed before things complete, so clear out the
// context holding it.
pairing_context_.reset();
}
}
| 171,219 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mkvparser::IMkvReader::~IMkvReader()
{
//// Disable MSVC warnings that suggest making code non-portable.
}
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 | mkvparser::IMkvReader::~IMkvReader()
#ifdef _MSC_VER
//// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
mkvparser::IMkvReader::~IMkvReader() {}
void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) {
major = 1;
minor = 0;
build = 0;
revision = 28;
}
| 174,467 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: findoprnd(ITEM *ptr, int32 *pos)
{
#ifdef BS_DEBUG
elog(DEBUG3, (ptr[*pos].type == OPR) ?
"%d %c" : "%d %d", *pos, ptr[*pos].val);
#endif
if (ptr[*pos].type == VAL)
{
ptr[*pos].left = 0;
(*pos)--;
}
else if (ptr[*pos].val == (int32) '!')
{
ptr[*pos].left = -1;
(*pos)--;
findoprnd(ptr, pos);
}
else
{
ITEM *curitem = &ptr[*pos];
int32 tmp = *pos;
(*pos)--;
findoprnd(ptr, pos);
curitem->left = *pos - tmp;
findoprnd(ptr, pos);
}
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | findoprnd(ITEM *ptr, int32 *pos)
{
/* since this function recurses, it could be driven to stack overflow. */
check_stack_depth();
#ifdef BS_DEBUG
elog(DEBUG3, (ptr[*pos].type == OPR) ?
"%d %c" : "%d %d", *pos, ptr[*pos].val);
#endif
if (ptr[*pos].type == VAL)
{
ptr[*pos].left = 0;
(*pos)--;
}
else if (ptr[*pos].val == (int32) '!')
{
ptr[*pos].left = -1;
(*pos)--;
findoprnd(ptr, pos);
}
else
{
ITEM *curitem = &ptr[*pos];
int32 tmp = *pos;
(*pos)--;
findoprnd(ptr, pos);
curitem->left = *pos - tmp;
findoprnd(ptr, pos);
}
}
| 166,403 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void x86_assign_hw_event(struct perf_event *event,
struct cpu_hw_events *cpuc, int i)
{
struct hw_perf_event *hwc = &event->hw;
hwc->idx = cpuc->assign[i];
hwc->last_cpu = smp_processor_id();
hwc->last_tag = ++cpuc->tags[i];
if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
hwc->config_base = 0;
hwc->event_base = 0;
} else if (hwc->idx >= X86_PMC_IDX_FIXED) {
hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0;
} else {
hwc->config_base = x86_pmu_config_addr(hwc->idx);
hwc->event_base = x86_pmu_event_addr(hwc->idx);
}
}
Commit Message: perf, x86: Fix Intel fixed counters base initialization
The following patch solves the problems introduced by Robert's
commit 41bf498 and reported by Arun Sharma. This commit gets rid
of the base + index notation for reading and writing PMU msrs.
The problem is that for fixed counters, the new calculation for
the base did not take into account the fixed counter indexes,
thus all fixed counters were read/written from fixed counter 0.
Although all fixed counters share the same config MSR, they each
have their own counter register.
Without:
$ task -e unhalted_core_cycles -e instructions_retired -e baclears noploop 1 noploop for 1 seconds
242202299 unhalted_core_cycles (0.00% scaling, ena=1000790892, run=1000790892)
2389685946 instructions_retired (0.00% scaling, ena=1000790892, run=1000790892)
49473 baclears (0.00% scaling, ena=1000790892, run=1000790892)
With:
$ task -e unhalted_core_cycles -e instructions_retired -e baclears noploop 1 noploop for 1 seconds
2392703238 unhalted_core_cycles (0.00% scaling, ena=1000840809, run=1000840809)
2389793744 instructions_retired (0.00% scaling, ena=1000840809, run=1000840809)
47863 baclears (0.00% scaling, ena=1000840809, run=1000840809)
Signed-off-by: Stephane Eranian <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
LKML-Reference: <20110319172005.GB4978@quad>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-189 | static inline void x86_assign_hw_event(struct perf_event *event,
struct cpu_hw_events *cpuc, int i)
{
struct hw_perf_event *hwc = &event->hw;
hwc->idx = cpuc->assign[i];
hwc->last_cpu = smp_processor_id();
hwc->last_tag = ++cpuc->tags[i];
if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
hwc->config_base = 0;
hwc->event_base = 0;
} else if (hwc->idx >= X86_PMC_IDX_FIXED) {
hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
} else {
hwc->config_base = x86_pmu_config_addr(hwc->idx);
hwc->event_base = x86_pmu_event_addr(hwc->idx);
}
}
| 165,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _bdf_parse_glyphs( char* line,
unsigned long linelen,
unsigned long lineno,
void* call_data,
void* client_data )
{
int c, mask_index;
char* s;
unsigned char* bp;
unsigned long i, slen, nibbles;
_bdf_parse_t* p;
bdf_glyph_t* glyph;
bdf_font_t* font;
FT_Memory memory;
FT_Error error = BDF_Err_Ok;
FT_UNUSED( call_data );
FT_UNUSED( lineno ); /* only used in debug mode */
p = (_bdf_parse_t *)client_data;
font = p->font;
memory = font->memory;
/* Check for a comment. */
if ( ft_memcmp( line, "COMMENT", 7 ) == 0 )
{
linelen -= 7;
s = line + 7;
if ( *s != 0 )
{
s++;
linelen--;
}
error = _bdf_add_comment( p->font, s, linelen );
goto Exit;
}
/* The very first thing expected is the number of glyphs. */
if ( !( p->flags & _BDF_GLYPHS ) )
{
if ( ft_memcmp( line, "CHARS", 5 ) != 0 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" ));
error = BDF_Err_Missing_Chars_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 );
/* Make sure the number of glyphs is non-zero. */
if ( p->cnt == 0 )
font->glyphs_size = 64;
/* Limit ourselves to 1,114,112 glyphs in the font (this is the */
/* number of code points available in Unicode). */
if ( p->cnt >= 0x110000UL )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" ));
error = BDF_Err_Invalid_Argument;
goto Exit;
}
if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) )
goto Exit;
p->flags |= _BDF_GLYPHS;
goto Exit;
}
/* Check for the ENDFONT field. */
if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 )
{
/* Sort the glyphs by encoding. */
ft_qsort( (char *)font->glyphs,
font->glyphs_used,
sizeof ( bdf_glyph_t ),
by_encoding );
p->flags &= ~_BDF_START;
goto Exit;
}
/* Check for the ENDCHAR field. */
if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 )
{
p->glyph_enc = 0;
p->flags &= ~_BDF_GLYPH_BITS;
goto Exit;
}
/* Check whether a glyph is being scanned but should be */
/* ignored because it is an unencoded glyph. */
if ( ( p->flags & _BDF_GLYPH ) &&
p->glyph_enc == -1 &&
p->opts->keep_unencoded == 0 )
goto Exit;
/* Check for the STARTCHAR field. */
if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 )
{
/* Set the character name in the parse info first until the */
/* encoding can be checked for an unencoded character. */
FT_FREE( p->glyph_name );
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
_bdf_list_shift( &p->list, 1 );
s = _bdf_list_join( &p->list, ' ', &slen );
if ( !s )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) )
goto Exit;
FT_MEM_COPY( p->glyph_name, s, slen + 1 );
p->flags |= _BDF_GLYPH;
FT_TRACE4(( DBGMSG1, lineno, s ));
goto Exit;
}
/* Check for the ENCODING field. */
if ( ft_memcmp( line, "ENCODING", 8 ) == 0 )
{
if ( !( p->flags & _BDF_GLYPH ) )
{
/* Missing STARTCHAR field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" ));
error = BDF_Err_Missing_Startchar_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 );
/* Normalize negative encoding values. The specification only */
/* allows -1, but we can be more generous here. */
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
/* Check for alternative encoding format. */
if ( p->glyph_enc == -1 && p->list.used > 2 )
p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 );
FT_TRACE4(( DBGMSG2, p->glyph_enc ));
/* Check that the encoding is in the Unicode range because */
sizeof ( unsigned long ) * 32 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
/* Check whether this encoding has already been encountered. */
/* If it has then change it to unencoded so it gets added if */
/* indicated. */
if ( p->glyph_enc >= 0 )
{
if ( _bdf_glyph_modified( p->have, p->glyph_enc ) )
{
/* Emit a message saying a glyph has been moved to the */
/* unencoded area. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12,
p->glyph_enc, p->glyph_name ));
p->glyph_enc = -1;
font->modified = 1;
}
else
_bdf_set_glyph_modified( p->have, p->glyph_enc );
}
if ( p->glyph_enc >= 0 )
{
/* Make sure there are enough glyphs allocated in case the */
/* number of characters happen to be wrong. */
if ( font->glyphs_used == font->glyphs_size )
{
if ( FT_RENEW_ARRAY( font->glyphs,
font->glyphs_size,
font->glyphs_size + 64 ) )
goto Exit;
font->glyphs_size += 64;
}
glyph = font->glyphs + font->glyphs_used++;
glyph->name = p->glyph_name;
glyph->encoding = p->glyph_enc;
/* Reset the initial glyph info. */
p->glyph_name = 0;
}
else
{
/* Unencoded glyph. Check whether it should */
/* be added or not. */
if ( p->opts->keep_unencoded != 0 )
{
/* Allocate the next unencoded glyph. */
if ( font->unencoded_used == font->unencoded_size )
{
if ( FT_RENEW_ARRAY( font->unencoded ,
font->unencoded_size,
font->unencoded_size + 4 ) )
goto Exit;
font->unencoded_size += 4;
}
glyph = font->unencoded + font->unencoded_used;
glyph->name = p->glyph_name;
glyph->encoding = font->unencoded_used++;
}
else
/* Free up the glyph name if the unencoded shouldn't be */
/* kept. */
FT_FREE( p->glyph_name );
p->glyph_name = 0;
}
/* Clear the flags that might be added when width and height are */
/* checked for consistency. */
p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK );
p->flags |= _BDF_ENCODING;
goto Exit;
}
/* Point at the glyph being constructed. */
if ( p->glyph_enc == -1 )
glyph = font->unencoded + ( font->unencoded_used - 1 );
else
glyph = font->glyphs + ( font->glyphs_used - 1 );
/* Check whether a bitmap is being constructed. */
if ( p->flags & _BDF_BITMAP )
{
/* If there are more rows than are specified in the glyph metrics, */
/* ignore the remaining lines. */
if ( p->row >= (unsigned long)glyph->bbx.height )
{
if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding ));
p->flags |= _BDF_GLYPH_HEIGHT_CHECK;
font->modified = 1;
}
goto Exit;
}
/* Only collect the number of nibbles indicated by the glyph */
/* metrics. If there are more columns, they are simply ignored. */
nibbles = glyph->bpr << 1;
bp = glyph->bitmap + p->row * glyph->bpr;
for ( i = 0; i < nibbles; i++ )
{
c = line[i];
if ( !sbitset( hdigits, c ) )
break;
*bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] );
if ( i + 1 < nibbles && ( i & 1 ) )
*++bp = 0;
}
/* If any line has not enough columns, */
/* indicate they have been padded with zero bits. */
if ( i < nibbles &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
/* Remove possible garbage at the right. */
mask_index = ( glyph->bbx.width * p->font->bpp ) & 7;
if ( glyph->bbx.width )
*bp &= nibble_mask[mask_index];
/* If any line has extra columns, indicate they have been removed. */
if ( i == nibbles &&
sbitset( hdigits, line[nibbles] ) &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
p->row++;
goto Exit;
}
/* Expect the SWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
p->flags |= _BDF_SWIDTH;
goto Exit;
}
/* Expect the DWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
if ( !( p->flags & _BDF_SWIDTH ) )
{
/* Missing SWIDTH field. Emit an auto correction message and set */
/* the scalable width from the device width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno ));
glyph->swidth = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
}
p->flags |= _BDF_DWIDTH;
goto Exit;
}
/* Expect the BBX field next. */
if ( ft_memcmp( line, "BBX", 3 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 );
glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 );
glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 );
glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 );
/* Generate the ascent and descent of the character. */
glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset );
glyph->bbx.descent = (short)( -glyph->bbx.y_offset );
/* Determine the overall font bounding box as the characters are */
/* loaded so corrections can be done later if indicated. */
p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas );
p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds );
p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset );
p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb );
p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb );
p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb );
if ( !( p->flags & _BDF_DWIDTH ) )
{
/* Missing DWIDTH field. Emit an auto correction message and set */
/* the device width to the glyph width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno ));
glyph->dwidth = glyph->bbx.width;
}
/* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */
/* value if necessary. */
if ( p->opts->correct_metrics != 0 )
{
/* Determine the point size of the glyph. */
unsigned short sw = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
if ( sw != glyph->swidth )
{
glyph->swidth = sw;
if ( p->glyph_enc == -1 )
_bdf_set_glyph_modified( font->umod,
font->unencoded_used - 1 );
else
_bdf_set_glyph_modified( font->nmod, glyph->encoding );
p->flags |= _BDF_SWIDTH_ADJ;
font->modified = 1;
}
}
p->flags |= _BDF_BBX;
goto Exit;
}
/* And finally, gather up the bitmap. */
if ( ft_memcmp( line, "BITMAP", 6 ) == 0 )
{
unsigned long bitmap_size;
if ( !( p->flags & _BDF_BBX ) )
{
/* Missing BBX field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" ));
error = BDF_Err_Missing_Bbx_Field;
goto Exit;
}
/* Allocate enough space for the bitmap. */
glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3;
bitmap_size = glyph->bpr * glyph->bbx.height;
if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno ));
error = BDF_Err_Bbx_Too_Big;
goto Exit;
}
else
glyph->bytes = (unsigned short)bitmap_size;
if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) )
goto Exit;
p->row = 0;
p->flags |= _BDF_BITMAP;
goto Exit;
}
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
Missing_Encoding:
/* Missing ENCODING field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" ));
error = BDF_Err_Missing_Encoding_Field;
Exit:
if ( error && ( p->flags & _BDF_GLYPH ) )
FT_FREE( p->glyph_name );
return error;
}
Commit Message:
CWE ID: CWE-119 | _bdf_parse_glyphs( char* line,
unsigned long linelen,
unsigned long lineno,
void* call_data,
void* client_data )
{
int c, mask_index;
char* s;
unsigned char* bp;
unsigned long i, slen, nibbles;
_bdf_parse_t* p;
bdf_glyph_t* glyph;
bdf_font_t* font;
FT_Memory memory;
FT_Error error = BDF_Err_Ok;
FT_UNUSED( call_data );
FT_UNUSED( lineno ); /* only used in debug mode */
p = (_bdf_parse_t *)client_data;
font = p->font;
memory = font->memory;
/* Check for a comment. */
if ( ft_memcmp( line, "COMMENT", 7 ) == 0 )
{
linelen -= 7;
s = line + 7;
if ( *s != 0 )
{
s++;
linelen--;
}
error = _bdf_add_comment( p->font, s, linelen );
goto Exit;
}
/* The very first thing expected is the number of glyphs. */
if ( !( p->flags & _BDF_GLYPHS ) )
{
if ( ft_memcmp( line, "CHARS", 5 ) != 0 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" ));
error = BDF_Err_Missing_Chars_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 );
/* Make sure the number of glyphs is non-zero. */
if ( p->cnt == 0 )
font->glyphs_size = 64;
/* Limit ourselves to 1,114,112 glyphs in the font (this is the */
/* number of code points available in Unicode). */
if ( p->cnt >= 0x110000UL )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" ));
error = BDF_Err_Invalid_Argument;
goto Exit;
}
if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) )
goto Exit;
p->flags |= _BDF_GLYPHS;
goto Exit;
}
/* Check for the ENDFONT field. */
if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 )
{
/* Sort the glyphs by encoding. */
ft_qsort( (char *)font->glyphs,
font->glyphs_used,
sizeof ( bdf_glyph_t ),
by_encoding );
p->flags &= ~_BDF_START;
goto Exit;
}
/* Check for the ENDCHAR field. */
if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 )
{
p->glyph_enc = 0;
p->flags &= ~_BDF_GLYPH_BITS;
goto Exit;
}
/* Check whether a glyph is being scanned but should be */
/* ignored because it is an unencoded glyph. */
if ( ( p->flags & _BDF_GLYPH ) &&
p->glyph_enc == -1 &&
p->opts->keep_unencoded == 0 )
goto Exit;
/* Check for the STARTCHAR field. */
if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 )
{
/* Set the character name in the parse info first until the */
/* encoding can be checked for an unencoded character. */
FT_FREE( p->glyph_name );
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
_bdf_list_shift( &p->list, 1 );
s = _bdf_list_join( &p->list, ' ', &slen );
if ( !s )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) )
goto Exit;
FT_MEM_COPY( p->glyph_name, s, slen + 1 );
p->flags |= _BDF_GLYPH;
FT_TRACE4(( DBGMSG1, lineno, s ));
goto Exit;
}
/* Check for the ENCODING field. */
if ( ft_memcmp( line, "ENCODING", 8 ) == 0 )
{
if ( !( p->flags & _BDF_GLYPH ) )
{
/* Missing STARTCHAR field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" ));
error = BDF_Err_Missing_Startchar_Field;
goto Exit;
}
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 );
/* Normalize negative encoding values. The specification only */
/* allows -1, but we can be more generous here. */
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
/* Check for alternative encoding format. */
if ( p->glyph_enc == -1 && p->list.used > 2 )
p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 );
if ( p->glyph_enc < -1 )
p->glyph_enc = -1;
FT_TRACE4(( DBGMSG2, p->glyph_enc ));
/* Check that the encoding is in the Unicode range because */
sizeof ( unsigned long ) * 32 )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
}
/* Check whether this encoding has already been encountered. */
/* If it has then change it to unencoded so it gets added if */
/* indicated. */
if ( p->glyph_enc >= 0 )
{
if ( _bdf_glyph_modified( p->have, p->glyph_enc ) )
{
/* Emit a message saying a glyph has been moved to the */
/* unencoded area. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12,
p->glyph_enc, p->glyph_name ));
p->glyph_enc = -1;
font->modified = 1;
}
else
_bdf_set_glyph_modified( p->have, p->glyph_enc );
}
if ( p->glyph_enc >= 0 )
{
/* Make sure there are enough glyphs allocated in case the */
/* number of characters happen to be wrong. */
if ( font->glyphs_used == font->glyphs_size )
{
if ( FT_RENEW_ARRAY( font->glyphs,
font->glyphs_size,
font->glyphs_size + 64 ) )
goto Exit;
font->glyphs_size += 64;
}
glyph = font->glyphs + font->glyphs_used++;
glyph->name = p->glyph_name;
glyph->encoding = p->glyph_enc;
/* Reset the initial glyph info. */
p->glyph_name = 0;
}
else
{
/* Unencoded glyph. Check whether it should */
/* be added or not. */
if ( p->opts->keep_unencoded != 0 )
{
/* Allocate the next unencoded glyph. */
if ( font->unencoded_used == font->unencoded_size )
{
if ( FT_RENEW_ARRAY( font->unencoded ,
font->unencoded_size,
font->unencoded_size + 4 ) )
goto Exit;
font->unencoded_size += 4;
}
glyph = font->unencoded + font->unencoded_used;
glyph->name = p->glyph_name;
glyph->encoding = font->unencoded_used++;
}
else
/* Free up the glyph name if the unencoded shouldn't be */
/* kept. */
FT_FREE( p->glyph_name );
p->glyph_name = 0;
}
/* Clear the flags that might be added when width and height are */
/* checked for consistency. */
p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK );
p->flags |= _BDF_ENCODING;
goto Exit;
}
/* Point at the glyph being constructed. */
if ( p->glyph_enc == -1 )
glyph = font->unencoded + ( font->unencoded_used - 1 );
else
glyph = font->glyphs + ( font->glyphs_used - 1 );
/* Check whether a bitmap is being constructed. */
if ( p->flags & _BDF_BITMAP )
{
/* If there are more rows than are specified in the glyph metrics, */
/* ignore the remaining lines. */
if ( p->row >= (unsigned long)glyph->bbx.height )
{
if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding ));
p->flags |= _BDF_GLYPH_HEIGHT_CHECK;
font->modified = 1;
}
goto Exit;
}
/* Only collect the number of nibbles indicated by the glyph */
/* metrics. If there are more columns, they are simply ignored. */
nibbles = glyph->bpr << 1;
bp = glyph->bitmap + p->row * glyph->bpr;
for ( i = 0; i < nibbles; i++ )
{
c = line[i];
if ( !sbitset( hdigits, c ) )
break;
*bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] );
if ( i + 1 < nibbles && ( i & 1 ) )
*++bp = 0;
}
/* If any line has not enough columns, */
/* indicate they have been padded with zero bits. */
if ( i < nibbles &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
/* Remove possible garbage at the right. */
mask_index = ( glyph->bbx.width * p->font->bpp ) & 7;
if ( glyph->bbx.width )
*bp &= nibble_mask[mask_index];
/* If any line has extra columns, indicate they have been removed. */
if ( i == nibbles &&
sbitset( hdigits, line[nibbles] ) &&
!( p->flags & _BDF_GLYPH_WIDTH_CHECK ) )
{
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding ));
p->flags |= _BDF_GLYPH_WIDTH_CHECK;
font->modified = 1;
}
p->row++;
goto Exit;
}
/* Expect the SWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
p->flags |= _BDF_SWIDTH;
goto Exit;
}
/* Expect the DWIDTH (scalable width) field next. */
if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 );
if ( !( p->flags & _BDF_SWIDTH ) )
{
/* Missing SWIDTH field. Emit an auto correction message and set */
/* the scalable width from the device width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno ));
glyph->swidth = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
}
p->flags |= _BDF_DWIDTH;
goto Exit;
}
/* Expect the BBX field next. */
if ( ft_memcmp( line, "BBX", 3 ) == 0 )
{
if ( !( p->flags & _BDF_ENCODING ) )
goto Missing_Encoding;
error = _bdf_list_split( &p->list, (char *)" +", line, linelen );
if ( error )
goto Exit;
glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 );
glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 );
glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 );
glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 );
/* Generate the ascent and descent of the character. */
glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset );
glyph->bbx.descent = (short)( -glyph->bbx.y_offset );
/* Determine the overall font bounding box as the characters are */
/* loaded so corrections can be done later if indicated. */
p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas );
p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds );
p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset );
p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb );
p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb );
p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb );
if ( !( p->flags & _BDF_DWIDTH ) )
{
/* Missing DWIDTH field. Emit an auto correction message and set */
/* the device width to the glyph width. */
FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno ));
glyph->dwidth = glyph->bbx.width;
}
/* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */
/* value if necessary. */
if ( p->opts->correct_metrics != 0 )
{
/* Determine the point size of the glyph. */
unsigned short sw = (unsigned short)FT_MulDiv(
glyph->dwidth, 72000L,
(FT_Long)( font->point_size *
font->resolution_x ) );
if ( sw != glyph->swidth )
{
glyph->swidth = sw;
if ( p->glyph_enc == -1 )
_bdf_set_glyph_modified( font->umod,
font->unencoded_used - 1 );
else
_bdf_set_glyph_modified( font->nmod, glyph->encoding );
p->flags |= _BDF_SWIDTH_ADJ;
font->modified = 1;
}
}
p->flags |= _BDF_BBX;
goto Exit;
}
/* And finally, gather up the bitmap. */
if ( ft_memcmp( line, "BITMAP", 6 ) == 0 )
{
unsigned long bitmap_size;
if ( !( p->flags & _BDF_BBX ) )
{
/* Missing BBX field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" ));
error = BDF_Err_Missing_Bbx_Field;
goto Exit;
}
/* Allocate enough space for the bitmap. */
glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3;
bitmap_size = glyph->bpr * glyph->bbx.height;
if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU )
{
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno ));
error = BDF_Err_Bbx_Too_Big;
goto Exit;
}
else
glyph->bytes = (unsigned short)bitmap_size;
if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) )
goto Exit;
p->row = 0;
p->flags |= _BDF_BITMAP;
goto Exit;
}
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno ));
error = BDF_Err_Invalid_File_Format;
goto Exit;
Missing_Encoding:
/* Missing ENCODING field. */
FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" ));
error = BDF_Err_Missing_Encoding_Field;
Exit:
if ( error && ( p->flags & _BDF_GLYPH ) )
FT_FREE( p->glyph_name );
return error;
}
| 164,822 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Object> V8InjectedScriptHost::create(v8::Local<v8::Context> context, V8InspectorImpl* inspector)
{
v8::Isolate* isolate = inspector->isolate();
v8::Local<v8::Object> injectedScriptHost = v8::Object::New(isolate);
v8::Local<v8::External> debuggerExternal = v8::External::New(isolate, inspector);
setFunctionProperty(context, injectedScriptHost, "internalConstructorName", V8InjectedScriptHost::internalConstructorNameCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "formatAccessorsAsProperties", V8InjectedScriptHost::formatAccessorsAsProperties, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "subtype", V8InjectedScriptHost::subtypeCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "getInternalProperties", V8InjectedScriptHost::getInternalPropertiesCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "objectHasOwnProperty", V8InjectedScriptHost::objectHasOwnPropertyCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "bind", V8InjectedScriptHost::bindCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "proxyTargetValue", V8InjectedScriptHost::proxyTargetValueCallback, debuggerExternal);
return injectedScriptHost;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::Local<v8::Object> V8InjectedScriptHost::create(v8::Local<v8::Context> context, V8InspectorImpl* inspector)
{
v8::Isolate* isolate = inspector->isolate();
v8::Local<v8::Object> injectedScriptHost = v8::Object::New(isolate);
bool success = injectedScriptHost->SetPrototype(context, v8::Null(isolate)).FromMaybe(false);
DCHECK(success);
v8::Local<v8::External> debuggerExternal = v8::External::New(isolate, inspector);
setFunctionProperty(context, injectedScriptHost, "internalConstructorName", V8InjectedScriptHost::internalConstructorNameCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "formatAccessorsAsProperties", V8InjectedScriptHost::formatAccessorsAsProperties, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "subtype", V8InjectedScriptHost::subtypeCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "getInternalProperties", V8InjectedScriptHost::getInternalPropertiesCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "objectHasOwnProperty", V8InjectedScriptHost::objectHasOwnPropertyCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "bind", V8InjectedScriptHost::bindCallback, debuggerExternal);
setFunctionProperty(context, injectedScriptHost, "proxyTargetValue", V8InjectedScriptHost::proxyTargetValueCallback, debuggerExternal);
return injectedScriptHost;
}
| 172,069 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat)
{
ssize_t ret;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(type,
(struct compat_iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
else
#endif
ret = rw_copy_check_uvector(type,
(struct iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
if (ret < 0)
goto out;
kiocb->ki_nr_segs = kiocb->ki_nbytes;
kiocb->ki_cur_seg = 0;
/* ki_nbytes/left now reflect bytes instead of segs */
kiocb->ki_nbytes = ret;
kiocb->ki_left = ret;
ret = 0;
out:
return ret;
}
Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat)
{
ssize_t ret;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(type,
(struct compat_iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
else
#endif
ret = rw_copy_check_uvector(type,
(struct iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
if (ret < 0)
goto out;
ret = rw_verify_area(type, kiocb->ki_filp, &kiocb->ki_pos, ret);
if (ret < 0)
goto out;
kiocb->ki_nr_segs = kiocb->ki_nbytes;
kiocb->ki_cur_seg = 0;
/* ki_nbytes/left now reflect bytes instead of segs */
kiocb->ki_nbytes = ret;
kiocb->ki_left = ret;
ret = 0;
out:
return ret;
}
| 167,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err)
{
char *colon;
char *host = NULL;
#ifdef HAVE_IPV6
char *p;
if (*(str) == '[' && str_len > 1) {
/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */
p = memchr(str + 1, ']', str_len - 2);
if (!p || *(p + 1) != ':') {
if (get_err) {
*err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str);
}
return NULL;
}
*portno = atoi(p + 2);
return estrndup(str + 1, p - str - 1);
}
#endif
if (str_len) {
colon = memchr(str, ':', str_len - 1);
} else {
colon = NULL;
}
if (colon) {
*portno = atoi(colon + 1);
host = estrndup(str, colon - str);
} else {
if (get_err) {
*err = strpprintf(0, "Failed to parse address \"%s\"", str);
}
return NULL;
}
return host;
}
Commit Message: Detect invalid port in xp_socket parse ip address
For historical reasons, fsockopen() accepts the port and hostname
separately: fsockopen('127.0.0.1', 80)
However, with the introdcution of stream transports in PHP 4.3,
it became possible to include the port in the hostname specifier:
fsockopen('127.0.0.1:80')
Or more formally: fsockopen('tcp://127.0.0.1:80')
Confusing results when these two forms are combined, however.
fsockopen('127.0.0.1:80', 443) results in fsockopen() attempting
to connect to '127.0.0.1:80:443' which any reasonable stack would
consider invalid.
Unfortunately, PHP parses the address looking for the first colon
(with special handling for IPv6, don't worry) and calls atoi()
from there. atoi() in turn, simply stops parsing at the first
non-numeric character and returns the value so far.
The end result is that the explicitly supplied port is treated
as ignored garbage, rather than producing an error.
This diff replaces atoi() with strtol() and inspects the
stop character. If additional "garbage" of any kind is found,
it fails and returns an error.
CWE ID: CWE-918 | static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err)
{
char *colon;
char *host = NULL;
#ifdef HAVE_IPV6
if (*(str) == '[' && str_len > 1) {
/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */
char *p = memchr(str + 1, ']', str_len - 2), *e = NULL;
if (!p || *(p + 1) != ':') {
if (get_err) {
*err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str);
}
return NULL;
}
*portno = strtol(p + 2, &e, 10);
if (e && *e) {
if (get_err) {
*err = strpprintf(0, "Failed to parse address \"%s\"", str);
}
return NULL;
}
return estrndup(str + 1, p - str - 1);
}
#endif
if (str_len) {
colon = memchr(str, ':', str_len - 1);
} else {
colon = NULL;
}
if (colon) {
char *e = NULL;
*portno = strtol(colon + 1, &e, 10);
if (!e || !*e) {
return estrndup(str, colon - str);
}
}
if (get_err) {
*err = strpprintf(0, "Failed to parse address \"%s\"", str);
}
return NULL;
}
| 168,289 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadFITSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct _FITSInfo
{
MagickBooleanType
extend,
simple;
int
bits_per_pixel,
columns,
rows,
number_axes,
number_planes;
double
min_data,
max_data,
zero,
scale;
EndianType
endian;
} FITSInfo;
char
*comment,
keyword[9],
property[MaxTextExtent],
value[73];
double
pixel,
scale;
FITSInfo
fits_info;
Image
*image;
int
c;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
scene,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image header.
*/
(void) ResetMagickMemory(&fits_info,0,sizeof(fits_info));
fits_info.extend=MagickFalse;
fits_info.simple=MagickFalse;
fits_info.bits_per_pixel=8;
fits_info.columns=1;
fits_info.rows=1;
fits_info.rows=1;
fits_info.number_planes=1;
fits_info.min_data=0.0;
fits_info.max_data=0.0;
fits_info.zero=0.0;
fits_info.scale=1.0;
fits_info.endian=MSBEndian;
/*
Decode image header.
*/
for (comment=(char *) NULL; EOFBlob(image) == MagickFalse; )
{
for ( ; EOFBlob(image) == MagickFalse; )
{
register char
*p;
count=ReadBlob(image,8,(unsigned char *) keyword);
if (count != 8)
break;
for (i=0; i < 8; i++)
{
if (isspace((int) ((unsigned char) keyword[i])) != 0)
break;
keyword[i]=tolower((int) ((unsigned char) keyword[i]));
}
keyword[i]='\0';
count=ReadBlob(image,72,(unsigned char *) value);
value[72]='\0';
if (count != 72)
break;
p=value;
if (*p == '=')
{
p+=2;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
}
if (LocaleCompare(keyword,"end") == 0)
break;
if (LocaleCompare(keyword,"extend") == 0)
fits_info.extend=(*p == 'T') || (*p == 't') ? MagickTrue : MagickFalse;
if (LocaleCompare(keyword,"simple") == 0)
fits_info.simple=(*p == 'T') || (*p == 't') ? MagickTrue : MagickFalse;
if (LocaleCompare(keyword,"bitpix") == 0)
fits_info.bits_per_pixel=StringToLong(p);
if (LocaleCompare(keyword,"naxis") == 0)
fits_info.number_axes=StringToLong(p);
if (LocaleCompare(keyword,"naxis1") == 0)
fits_info.columns=StringToLong(p);
if (LocaleCompare(keyword,"naxis2") == 0)
fits_info.rows=StringToLong(p);
if (LocaleCompare(keyword,"naxis3") == 0)
fits_info.number_planes=StringToLong(p);
if (LocaleCompare(keyword,"datamax") == 0)
fits_info.max_data=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"datamin") == 0)
fits_info.min_data=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"bzero") == 0)
fits_info.zero=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"bscale") == 0)
fits_info.scale=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"comment") == 0)
{
if (comment == (char *) NULL)
comment=ConstantString(p);
else
(void) ConcatenateString(&comment,p);
}
if (LocaleCompare(keyword,"xendian") == 0)
{
if (LocaleNCompare(p,"big",3) == 0)
fits_info.endian=MSBEndian;
else
fits_info.endian=LSBEndian;
}
(void) FormatLocaleString(property,MaxTextExtent,"fits:%s",keyword);
(void) SetImageProperty(image,property,p);
}
c=0;
while (((TellBlob(image) % FITSBlocksize) != 0) && (c != EOF))
c=ReadBlobByte(image);
if (fits_info.extend == MagickFalse)
break;
number_pixels=(MagickSizeType) fits_info.columns*fits_info.rows;
if ((fits_info.simple != MagickFalse) && (fits_info.number_axes >= 1) &&
(fits_info.number_axes <= 4) && (number_pixels != 0))
break;
}
/*
Verify that required image information is defined.
*/
if (comment != (char *) NULL)
{
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
number_pixels=(MagickSizeType) fits_info.columns*fits_info.rows;
if ((fits_info.simple == MagickFalse) || (fits_info.number_axes < 1) ||
(fits_info.number_axes > 4) || (number_pixels == 0))
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
for (scene=0; scene < (ssize_t) fits_info.number_planes; scene++)
{
image->columns=(size_t) fits_info.columns;
image->rows=(size_t) fits_info.rows;
image->depth=(size_t) (fits_info.bits_per_pixel < 0 ? -1 : 1)*
fits_info.bits_per_pixel;
image->endian=fits_info.endian;
image->scene=(size_t) scene;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Initialize image structure.
*/
(void) SetImageColorspace(image,GRAYColorspace);
if ((fits_info.min_data == 0.0) && (fits_info.max_data == 0.0))
{
if (fits_info.zero == 0.0)
(void) GetFITSPixelExtrema(image,fits_info.bits_per_pixel,
&fits_info.min_data,&fits_info.max_data);
else
fits_info.max_data=GetFITSPixelRange((size_t)
fits_info.bits_per_pixel);
}
else
fits_info.max_data=GetFITSPixelRange((size_t) fits_info.bits_per_pixel);
/*
Convert FITS pixels to pixel packets.
*/
scale=QuantumRange/(fits_info.max_data-fits_info.min_data);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=GetFITSPixel(image,fits_info.bits_per_pixel);
if ((image->depth == 16) || (image->depth == 32) ||
(image->depth == 64))
SetFITSUnsignedPixels(1,image->depth,image->endian,(unsigned char *)
&pixel);
SetPixelRed(q,ClampToQuantum(scale*(fits_info.scale*(pixel-
fits_info.min_data)+fits_info.zero)));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (fits_info.number_planes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadFITSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct _FITSInfo
{
MagickBooleanType
extend,
simple;
int
bits_per_pixel,
columns,
rows,
number_axes,
number_planes;
double
min_data,
max_data,
zero,
scale;
EndianType
endian;
} FITSInfo;
char
*comment,
keyword[9],
property[MaxTextExtent],
value[73];
double
pixel,
scale;
FITSInfo
fits_info;
Image
*image;
int
c;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
scene,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image header.
*/
(void) ResetMagickMemory(&fits_info,0,sizeof(fits_info));
fits_info.extend=MagickFalse;
fits_info.simple=MagickFalse;
fits_info.bits_per_pixel=8;
fits_info.columns=1;
fits_info.rows=1;
fits_info.rows=1;
fits_info.number_planes=1;
fits_info.min_data=0.0;
fits_info.max_data=0.0;
fits_info.zero=0.0;
fits_info.scale=1.0;
fits_info.endian=MSBEndian;
/*
Decode image header.
*/
for (comment=(char *) NULL; EOFBlob(image) == MagickFalse; )
{
for ( ; EOFBlob(image) == MagickFalse; )
{
register char
*p;
count=ReadBlob(image,8,(unsigned char *) keyword);
if (count != 8)
break;
for (i=0; i < 8; i++)
{
if (isspace((int) ((unsigned char) keyword[i])) != 0)
break;
keyword[i]=tolower((int) ((unsigned char) keyword[i]));
}
keyword[i]='\0';
count=ReadBlob(image,72,(unsigned char *) value);
value[72]='\0';
if (count != 72)
break;
p=value;
if (*p == '=')
{
p+=2;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
}
if (LocaleCompare(keyword,"end") == 0)
break;
if (LocaleCompare(keyword,"extend") == 0)
fits_info.extend=(*p == 'T') || (*p == 't') ? MagickTrue : MagickFalse;
if (LocaleCompare(keyword,"simple") == 0)
fits_info.simple=(*p == 'T') || (*p == 't') ? MagickTrue : MagickFalse;
if (LocaleCompare(keyword,"bitpix") == 0)
fits_info.bits_per_pixel=StringToLong(p);
if (LocaleCompare(keyword,"naxis") == 0)
fits_info.number_axes=StringToLong(p);
if (LocaleCompare(keyword,"naxis1") == 0)
fits_info.columns=StringToLong(p);
if (LocaleCompare(keyword,"naxis2") == 0)
fits_info.rows=StringToLong(p);
if (LocaleCompare(keyword,"naxis3") == 0)
fits_info.number_planes=StringToLong(p);
if (LocaleCompare(keyword,"datamax") == 0)
fits_info.max_data=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"datamin") == 0)
fits_info.min_data=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"bzero") == 0)
fits_info.zero=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"bscale") == 0)
fits_info.scale=StringToDouble(p,(char **) NULL);
if (LocaleCompare(keyword,"comment") == 0)
{
if (comment == (char *) NULL)
comment=ConstantString(p);
else
(void) ConcatenateString(&comment,p);
}
if (LocaleCompare(keyword,"xendian") == 0)
{
if (LocaleNCompare(p,"big",3) == 0)
fits_info.endian=MSBEndian;
else
fits_info.endian=LSBEndian;
}
(void) FormatLocaleString(property,MaxTextExtent,"fits:%s",keyword);
(void) SetImageProperty(image,property,p);
}
c=0;
while (((TellBlob(image) % FITSBlocksize) != 0) && (c != EOF))
c=ReadBlobByte(image);
if (fits_info.extend == MagickFalse)
break;
number_pixels=(MagickSizeType) fits_info.columns*fits_info.rows;
if ((fits_info.simple != MagickFalse) && (fits_info.number_axes >= 1) &&
(fits_info.number_axes <= 4) && (number_pixels != 0))
break;
}
/*
Verify that required image information is defined.
*/
if (comment != (char *) NULL)
{
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
number_pixels=(MagickSizeType) fits_info.columns*fits_info.rows;
if ((fits_info.simple == MagickFalse) || (fits_info.number_axes < 1) ||
(fits_info.number_axes > 4) || (number_pixels == 0))
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
for (scene=0; scene < (ssize_t) fits_info.number_planes; scene++)
{
image->columns=(size_t) fits_info.columns;
image->rows=(size_t) fits_info.rows;
image->depth=(size_t) (fits_info.bits_per_pixel < 0 ? -1 : 1)*
fits_info.bits_per_pixel;
image->endian=fits_info.endian;
image->scene=(size_t) scene;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Initialize image structure.
*/
(void) SetImageColorspace(image,GRAYColorspace);
if ((fits_info.min_data == 0.0) && (fits_info.max_data == 0.0))
{
if (fits_info.zero == 0.0)
(void) GetFITSPixelExtrema(image,fits_info.bits_per_pixel,
&fits_info.min_data,&fits_info.max_data);
else
fits_info.max_data=GetFITSPixelRange((size_t)
fits_info.bits_per_pixel);
}
else
fits_info.max_data=GetFITSPixelRange((size_t) fits_info.bits_per_pixel);
/*
Convert FITS pixels to pixel packets.
*/
scale=QuantumRange/(fits_info.max_data-fits_info.min_data);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=GetFITSPixel(image,fits_info.bits_per_pixel);
if ((image->depth == 16) || (image->depth == 32) ||
(image->depth == 64))
SetFITSUnsignedPixels(1,image->depth,image->endian,(unsigned char *)
&pixel);
SetPixelRed(q,ClampToQuantum(scale*(fits_info.scale*(pixel-
fits_info.min_data)+fits_info.zero)));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (fits_info.number_planes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,565 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (memcmp(&name[2], &content_name[2], 31L) == 0) {
if (memcmp(&name[33], &content_name[33], 8L) == 0) {
chm->sec1.content = fi;
}
else if (memcmp(&name[33], &control_name[33], 11L) == 0) {
chm->sec1.control = fi;
}
else if (memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
chm->sec1.spaninfo = fi;
}
else if (memcmp(&name[33], &rtable_name[33], 72L) == 0) {
chm->sec1.rtable = fi;
}
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
}
Commit Message: length checks when looking for control files
CWE ID: CWE-119 | static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (name_len == 40 && memcmp(name, content_name, 40) == 0) {
chm->sec1.content = fi;
}
else if (name_len == 44 && memcmp(name, control_name, 44) == 0) {
chm->sec1.control = fi;
}
else if (name_len == 41 && memcmp(name, spaninfo_name, 41) == 0) {
chm->sec1.spaninfo = fi;
}
else if (name_len == 105 && memcmp(name, rtable_name, 105) == 0) {
chm->sec1.rtable = fi;
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
}
| 169,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MimeHandlerViewContainer::OnReady() {
if (!render_frame() || !is_embedded_)
return;
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
blink::WebAssociatedURLLoaderOptions options;
DCHECK(!loader_);
loader_.reset(frame->CreateAssociatedURLLoader(options));
blink::WebURLRequest request(original_url_);
request.SetRequestContext(blink::WebURLRequest::kRequestContextObject);
loader_->LoadAsynchronously(request, this);
}
Commit Message: Skip Service workers in requests for mime handler plugins
BUG=808838
TEST=./browser_tests --gtest_filter=*/ServiceWorkerTest.MimeHandlerView*
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: I82e75c200091babbab648a04232db47e2938d914
Reviewed-on: https://chromium-review.googlesource.com/914150
Commit-Queue: Rob Wu <[email protected]>
Reviewed-by: Istiaque Ahmed <[email protected]>
Reviewed-by: Matt Falkenhagen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#537386}
CWE ID: CWE-20 | void MimeHandlerViewContainer::OnReady() {
if (!render_frame() || !is_embedded_)
return;
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
blink::WebAssociatedURLLoaderOptions options;
DCHECK(!loader_);
loader_.reset(frame->CreateAssociatedURLLoader(options));
blink::WebURLRequest request(original_url_);
request.SetRequestContext(blink::WebURLRequest::kRequestContextObject);
// The plugin resource request should skip service workers since "plug-ins
// may get their security origins from their own urls".
// https://w3c.github.io/ServiceWorker/#implementer-concerns
request.SetServiceWorkerMode(blink::WebURLRequest::ServiceWorkerMode::kNone);
loader_->LoadAsynchronously(request, this);
}
| 172,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnGetTransferBuffer(
int32 id,
IPC::Message* reply_message) {
if (!channel_->renderer_process())
return;
if (command_buffer_.get()) {
base::SharedMemoryHandle transfer_buffer = base::SharedMemoryHandle();
uint32 size = 0;
gpu::Buffer buffer = command_buffer_->GetTransferBuffer(id);
if (buffer.shared_memory) {
buffer.shared_memory->ShareToProcess(channel_->renderer_process(),
&transfer_buffer);
size = buffer.size;
}
GpuCommandBufferMsg_GetTransferBuffer::WriteReplyParams(reply_message,
transfer_buffer,
size);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnGetTransferBuffer(
int32 id,
IPC::Message* reply_message) {
if (command_buffer_.get()) {
base::SharedMemoryHandle transfer_buffer = base::SharedMemoryHandle();
uint32 size = 0;
gpu::Buffer buffer = command_buffer_->GetTransferBuffer(id);
if (buffer.shared_memory) {
#if defined(OS_WIN)
transfer_buffer = NULL;
sandbox::BrokerDuplicateHandle(buffer.shared_memory->handle(),
channel_->renderer_pid(), &transfer_buffer, FILE_MAP_READ |
FILE_MAP_WRITE, 0);
CHECK(transfer_buffer != NULL);
#else
buffer.shared_memory->ShareToProcess(channel_->renderer_pid(),
&transfer_buffer);
#endif
size = buffer.size;
}
GpuCommandBufferMsg_GetTransferBuffer::WriteReplyParams(reply_message,
transfer_buffer,
size);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 170,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int noblock = flags&MSG_DONTWAIT;
size_t copied;
struct sk_buff *skb, *data_skb;
int err, ret;
if (flags&MSG_OOB)
return -EOPNOTSUPP;
copied = 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (skb == NULL)
goto out;
data_skb = skb;
#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
if (unlikely(skb_shinfo(skb)->frag_list)) {
/*
* If this skb has a frag_list, then here that means that we
* will have to use the frag_list skb's data for compat tasks
* and the regular skb's data for normal (non-compat) tasks.
*
* If we need to send the compat skb, assign it to the
* 'data_skb' variable so that it will be used below for data
* copying. We keep 'skb' for everything else, including
* freeing both later.
*/
if (flags & MSG_CMSG_COMPAT)
data_skb = skb_shinfo(skb)->frag_list;
}
#endif
msg->msg_namelen = 0;
copied = data_skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(data_skb);
err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
if (msg->msg_name) {
struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
addr->nl_family = AF_NETLINK;
addr->nl_pad = 0;
addr->nl_pid = NETLINK_CB(skb).portid;
addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
msg->msg_namelen = sizeof(*addr);
}
if (nlk->flags & NETLINK_RECV_PKTINFO)
netlink_cmsg_recv_pktinfo(msg, skb);
if (NULL == siocb->scm) {
memset(&scm, 0, sizeof(scm));
siocb->scm = &scm;
}
siocb->scm->creds = *NETLINK_CREDS(skb);
if (flags & MSG_TRUNC)
copied = data_skb->len;
skb_free_datagram(sk, skb);
if (nlk->cb_running &&
atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
ret = netlink_dump(sk);
if (ret) {
sk->sk_err = ret;
sk->sk_error_report(sk);
}
}
scm_recv(sock, msg, siocb->scm, flags);
out:
netlink_rcv_wake(sk);
return err ? : copied;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int noblock = flags&MSG_DONTWAIT;
size_t copied;
struct sk_buff *skb, *data_skb;
int err, ret;
if (flags&MSG_OOB)
return -EOPNOTSUPP;
copied = 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (skb == NULL)
goto out;
data_skb = skb;
#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
if (unlikely(skb_shinfo(skb)->frag_list)) {
/*
* If this skb has a frag_list, then here that means that we
* will have to use the frag_list skb's data for compat tasks
* and the regular skb's data for normal (non-compat) tasks.
*
* If we need to send the compat skb, assign it to the
* 'data_skb' variable so that it will be used below for data
* copying. We keep 'skb' for everything else, including
* freeing both later.
*/
if (flags & MSG_CMSG_COMPAT)
data_skb = skb_shinfo(skb)->frag_list;
}
#endif
copied = data_skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(data_skb);
err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
if (msg->msg_name) {
struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
addr->nl_family = AF_NETLINK;
addr->nl_pad = 0;
addr->nl_pid = NETLINK_CB(skb).portid;
addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
msg->msg_namelen = sizeof(*addr);
}
if (nlk->flags & NETLINK_RECV_PKTINFO)
netlink_cmsg_recv_pktinfo(msg, skb);
if (NULL == siocb->scm) {
memset(&scm, 0, sizeof(scm));
siocb->scm = &scm;
}
siocb->scm->creds = *NETLINK_CREDS(skb);
if (flags & MSG_TRUNC)
copied = data_skb->len;
skb_free_datagram(sk, skb);
if (nlk->cb_running &&
atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
ret = netlink_dump(sk);
if (ret) {
sk->sk_err = ret;
sk->sk_error_report(sk);
}
}
scm_recv(sock, msg, siocb->scm, flags);
out:
netlink_rcv_wake(sk);
return err ? : copied;
}
| 166,507 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: poppler_page_prepare_output_dev (PopplerPage *page,
double scale,
int rotation,
gboolean transparent,
OutputDevData *output_dev_data)
{
CairoOutputDev *output_dev;
cairo_surface_t *surface;
double width, height;
int cairo_width, cairo_height, cairo_rowstride, rotate;
unsigned char *cairo_data;
rotate = rotation + page->page->getRotate ();
if (rotate == 90 || rotate == 270) {
height = page->page->getCropWidth ();
width = page->page->getCropHeight ();
} else {
width = page->page->getCropWidth ();
height = page->page->getCropHeight ();
}
cairo_width = (int) ceil(width * scale);
cairo_height = (int) ceil(height * scale);
output_dev = page->document->output_dev;
cairo_rowstride = cairo_width * 4;
cairo_data = (guchar *) gmalloc (cairo_height * cairo_rowstride);
if (transparent)
memset (cairo_data, 0x00, cairo_height * cairo_rowstride);
else
memset (cairo_data, 0xff, cairo_height * cairo_rowstride);
surface = cairo_image_surface_create_for_data(cairo_data,
CAIRO_FORMAT_ARGB32,
cairo_width, cairo_height,
cairo_rowstride);
output_dev_data->cairo_data = cairo_data;
output_dev_data->surface = surface;
output_dev_data->cairo = cairo_create (surface);
output_dev->setCairo (output_dev_data->cairo);
}
Commit Message:
CWE ID: CWE-189 | poppler_page_prepare_output_dev (PopplerPage *page,
double scale,
int rotation,
gboolean transparent,
OutputDevData *output_dev_data)
{
CairoOutputDev *output_dev;
cairo_surface_t *surface;
double width, height;
int cairo_width, cairo_height, cairo_rowstride, rotate;
unsigned char *cairo_data;
rotate = rotation + page->page->getRotate ();
if (rotate == 90 || rotate == 270) {
height = page->page->getCropWidth ();
width = page->page->getCropHeight ();
} else {
width = page->page->getCropWidth ();
height = page->page->getCropHeight ();
}
cairo_width = (int) ceil(width * scale);
cairo_height = (int) ceil(height * scale);
output_dev = page->document->output_dev;
cairo_rowstride = cairo_width * 4;
cairo_data = (guchar *) gmallocn (cairo_height, cairo_rowstride);
if (transparent)
memset (cairo_data, 0x00, cairo_height * cairo_rowstride);
else
memset (cairo_data, 0xff, cairo_height * cairo_rowstride);
surface = cairo_image_surface_create_for_data(cairo_data,
CAIRO_FORMAT_ARGB32,
cairo_width, cairo_height,
cairo_rowstride);
output_dev_data->cairo_data = cairo_data;
output_dev_data->surface = surface;
output_dev_data->cairo = cairo_create (surface);
output_dev->setCairo (output_dev_data->cairo);
}
| 164,617 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool freelist_state_initialize(union freelist_init_state *state,
struct kmem_cache *cachep,
unsigned int count)
{
bool ret;
unsigned int rand;
/* Use best entropy available to define a random shift */
rand = get_random_int();
/* Use a random state if the pre-computed list is not available */
if (!cachep->random_seq) {
prandom_seed_state(&state->rnd_state, rand);
ret = false;
} else {
state->list = cachep->random_seq;
state->count = count;
state->pos = 0;
state->rand = rand;
ret = true;
}
return ret;
}
Commit Message: mm/slab.c: fix SLAB freelist randomization duplicate entries
This patch fixes a bug in the freelist randomization code. When a high
random number is used, the freelist will contain duplicate entries. It
will result in different allocations sharing the same chunk.
It will result in odd behaviours and crashes. It should be uncommon but
it depends on the machines. We saw it happening more often on some
machines (every few hours of running tests).
Fixes: c7ce4f60ac19 ("mm: SLAB freelist randomization")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: John Sperbeck <[email protected]>
Signed-off-by: Thomas Garnier <[email protected]>
Cc: Christoph Lameter <[email protected]>
Cc: Pekka Enberg <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Joonsoo Kim <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static bool freelist_state_initialize(union freelist_init_state *state,
struct kmem_cache *cachep,
unsigned int count)
{
bool ret;
unsigned int rand;
/* Use best entropy available to define a random shift */
rand = get_random_int();
/* Use a random state if the pre-computed list is not available */
if (!cachep->random_seq) {
prandom_seed_state(&state->rnd_state, rand);
ret = false;
} else {
state->list = cachep->random_seq;
state->count = count;
state->pos = rand % count;
ret = true;
}
return ret;
}
| 168,396 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btm_sec_pin_code_request (UINT8 *p_bda)
{
tBTM_SEC_DEV_REC *p_dev_rec;
tBTM_CB *p_cb = &btm_cb;
#ifdef PORCHE_PAIRING_CONFLICT
UINT8 default_pin_code_len = 4;
PIN_CODE default_pin_code = {0x30, 0x30, 0x30, 0x30};
#endif
BTM_TRACE_EVENT ("btm_sec_pin_code_request() State: %s, BDA:%04x%08x",
btm_pair_state_descr(btm_cb.pairing_state),
(p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] );
if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
{
if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) &&
(btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) )
{
/* fake this out - porshe carkit issue - */
if(! btm_cb.pin_code_len_saved)
{
btsnd_hcic_pin_code_neg_reply (p_bda);
return;
}
else
{
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code);
return;
}
}
else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ)
|| memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
{
BTM_TRACE_WARNING ("btm_sec_pin_code_request() rejected - state: %s",
btm_pair_state_descr(btm_cb.pairing_state));
#ifdef PORCHE_PAIRING_CONFLICT
/* reply pin code again due to counter in_rand when local initiates pairing */
BTM_TRACE_EVENT ("btm_sec_pin_code_request from remote dev. for local initiated pairing");
if(! btm_cb.pin_code_len_saved)
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, default_pin_code_len, default_pin_code);
}
else
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code);
}
#else
btsnd_hcic_pin_code_neg_reply (p_bda);
#endif
return;
}
}
p_dev_rec = btm_find_or_alloc_dev (p_bda);
/* received PIN code request. must be non-sm4 */
p_dev_rec->sm4 = BTM_SM4_KNOWN;
if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
{
memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN);
btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
/* Make sure we reset the trusted mask to help against attacks */
BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
}
if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED))
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request fixed pin replying");
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code);
return;
}
/* Use the connecting device's CoD for the connection */
if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN))
&& (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) )
memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN);
/* We could have started connection after asking user for the PIN code */
if (btm_cb.pin_code_len != 0)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request bonding sending reply");
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code);
#ifdef PORCHE_PAIRING_CONFLICT
btm_cb.pin_code_len_saved = btm_cb.pin_code_len;
#endif
/* Mark that we forwarded received from the user PIN code */
btm_cb.pin_code_len = 0;
/* We can change mode back right away, that other connection being established */
/* is not forced to be secure - found a FW issue, so we can not do this
btm_restore_mode(); */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
}
/* If pairing disabled OR (no PIN callback and not bonding) */
/* OR we could not allocate entry in the database reject pairing request */
else if (p_cb->pairing_disabled
|| (p_cb->api.p_pin_callback == NULL)
/* OR Microsoft keyboard can for some reason try to establish connection */
/* the only thing we can do here is to shut it up. Normally we will be originator */
/* for keyboard bonding */
|| (!p_dev_rec->is_originator
&& ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL)
&& (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) )
{
BTM_TRACE_WARNING("btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!",
p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
btsnd_hcic_pin_code_neg_reply (p_bda);
}
/* Notify upper layer of PIN request and start expiration timer */
else
{
btm_cb.pin_code_len_saved = 0;
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
/* Pin code request can not come at the same time as connection request */
memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN);
memcpy (p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
/* Check if the name is known */
/* Even if name is not known we might not be able to get one */
/* this is the case when we are already getting something from the */
/* device, so HCI level is flow controlled */
/* Also cannot send remote name request while paging, i.e. connection is not completed */
if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
else
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for remote name");
/* We received PIN code request for the device with unknown name */
/* it is not user friendly just to ask for the PIN without name */
/* try to get name at first */
if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr,
HCI_PAGE_SCAN_REP_MODE_R1,
HCI_MANDATARY_PAGE_SCAN_MODE, 0))
{
p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
p_dev_rec->sec_bd_name[0] = 'f';
p_dev_rec->sec_bd_name[1] = '0';
BTM_TRACE_ERROR ("can not send rmt_name_req?? fake a name and call callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
}
}
return;
}
Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround
Bug: 26551752
Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1
CWE ID: CWE-264 | void btm_sec_pin_code_request (UINT8 *p_bda)
{
tBTM_SEC_DEV_REC *p_dev_rec;
tBTM_CB *p_cb = &btm_cb;
BTM_TRACE_EVENT ("btm_sec_pin_code_request() State: %s, BDA:%04x%08x",
btm_pair_state_descr(btm_cb.pairing_state),
(p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] );
if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
{
if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) &&
(btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) )
{
btsnd_hcic_pin_code_neg_reply (p_bda);
return;
}
else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ)
|| memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
{
BTM_TRACE_WARNING ("btm_sec_pin_code_request() rejected - state: %s",
btm_pair_state_descr(btm_cb.pairing_state));
btsnd_hcic_pin_code_neg_reply (p_bda);
return;
}
}
p_dev_rec = btm_find_or_alloc_dev (p_bda);
/* received PIN code request. must be non-sm4 */
p_dev_rec->sm4 = BTM_SM4_KNOWN;
if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
{
memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN);
btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
/* Make sure we reset the trusted mask to help against attacks */
BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
}
if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED))
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request fixed pin replying");
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code);
return;
}
/* Use the connecting device's CoD for the connection */
if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN))
&& (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) )
memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN);
/* We could have started connection after asking user for the PIN code */
if (btm_cb.pin_code_len != 0)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request bonding sending reply");
btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code);
/* Mark that we forwarded received from the user PIN code */
btm_cb.pin_code_len = 0;
/* We can change mode back right away, that other connection being established */
/* is not forced to be secure - found a FW issue, so we can not do this
btm_restore_mode(); */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
}
/* If pairing disabled OR (no PIN callback and not bonding) */
/* OR we could not allocate entry in the database reject pairing request */
else if (p_cb->pairing_disabled
|| (p_cb->api.p_pin_callback == NULL)
/* OR Microsoft keyboard can for some reason try to establish connection */
/* the only thing we can do here is to shut it up. Normally we will be originator */
/* for keyboard bonding */
|| (!p_dev_rec->is_originator
&& ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL)
&& (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) )
{
BTM_TRACE_WARNING("btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!",
p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
btsnd_hcic_pin_code_neg_reply (p_bda);
}
/* Notify upper layer of PIN request and start expiration timer */
else
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
/* Pin code request can not come at the same time as connection request */
memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN);
memcpy (p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
/* Check if the name is known */
/* Even if name is not known we might not be able to get one */
/* this is the case when we are already getting something from the */
/* device, so HCI level is flow controlled */
/* Also cannot send remote name request while paging, i.e. connection is not completed */
if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
else
{
BTM_TRACE_EVENT ("btm_sec_pin_code_request going for remote name");
/* We received PIN code request for the device with unknown name */
/* it is not user friendly just to ask for the PIN without name */
/* try to get name at first */
if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr,
HCI_PAGE_SCAN_REP_MODE_R1,
HCI_MANDATARY_PAGE_SCAN_MODE, 0))
{
p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
p_dev_rec->sec_bd_name[0] = 'f';
p_dev_rec->sec_bd_name[1] = '0';
BTM_TRACE_ERROR ("can not send rmt_name_req?? fake a name and call callback");
btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback)
(*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
}
}
}
return;
}
| 173,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CursorImpl::IDBThreadHelper::~IDBThreadHelper() {
cursor_->RemoveCursorFromTransaction();
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: [email protected]
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416 | CursorImpl::IDBThreadHelper::~IDBThreadHelper() {
| 172,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->SetRenderer(frame_host_ ? frame_host_->GetProcess() : nullptr,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler()));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
if (frame_tree_node_ && !frame_tree_node_->parent()) {
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
}
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler()));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
if (frame_tree_node_ && !frame_tree_node_->parent()) {
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
}
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
}
| 172,781 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = (mWidth * mHeight * 3) / 2;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20 | void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
OMX_U32 frameSize = (mWidth * mHeight * 3) / 2;
if (outHeader->nAllocLen < frameSize) {
android_errorWriteLog(0x534e4554, "27833616");
ALOGE("Insufficient output buffer size");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = frameSize;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
| 174,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ptrace_link(struct task_struct *child, struct task_struct *new_parent)
{
rcu_read_lock();
__ptrace_link(child, new_parent, __task_cred(new_parent));
rcu_read_unlock();
}
Commit Message: ptrace: Fix ->ptracer_cred handling for PTRACE_TRACEME
Fix two issues:
When called for PTRACE_TRACEME, ptrace_link() would obtain an RCU
reference to the parent's objective credentials, then give that pointer
to get_cred(). However, the object lifetime rules for things like
struct cred do not permit unconditionally turning an RCU reference into
a stable reference.
PTRACE_TRACEME records the parent's credentials as if the parent was
acting as the subject, but that's not the case. If a malicious
unprivileged child uses PTRACE_TRACEME and the parent is privileged, and
at a later point, the parent process becomes attacker-controlled
(because it drops privileges and calls execve()), the attacker ends up
with control over two processes with a privileged ptrace relationship,
which can be abused to ptrace a suid binary and obtain root privileges.
Fix both of these by always recording the credentials of the process
that is requesting the creation of the ptrace relationship:
current_cred() can't change under us, and current is the proper subject
for access control.
This change is theoretically userspace-visible, but I am not aware of
any code that it will actually break.
Fixes: 64b875f7ac8a ("ptrace: Capture the ptracer's creds not PT_PTRACE_CAP")
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static void ptrace_link(struct task_struct *child, struct task_struct *new_parent)
{
__ptrace_link(child, new_parent, current_cred());
}
| 169,606 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (IsFullscreenForCurrentTab())
ExitFullscreen(true);
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
| 172,315 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int jpg_validate(jas_stream_t *in)
{
uchar buf[JPG_MAGICLEN];
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < JPG_MAGICLEN) {
return -1;
}
/* Does this look like JPEG? */
if (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {
return -1;
}
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 | int jpg_validate(jas_stream_t *in)
{
jas_uchar buf[JPG_MAGICLEN];
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < JPG_MAGICLEN) {
return -1;
}
/* Does this look like JPEG? */
if (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {
return -1;
}
return 0;
}
| 168,723 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
Commit Message:
CWE ID: CWE-119 | gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
if (psession.size > *session_data_size)
{
*session_data_size = psession.size;
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
| 164,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
{
ASSERT(!m_isDestroyingShadowSubtree);
m_isDestroyingShadowSubtree = true;
if (SpinButtonElement* element = spinButtonElement())
element->removeSpinButtonOwner();
if (ClearButtonElement* element = clearButtonElement())
element->removeClearButtonOwner();
if (DateTimeEditElement* element = dateTimeEditElement())
element->removeEditControlOwner();
if (PickerIndicatorElement* element = pickerIndicatorElement())
element->removePickerIndicatorOwner();
if (element()->focused())
element()->focus();
BaseDateAndTimeInputType::destroyShadowSubtree();
m_isDestroyingShadowSubtree = false;
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
{
ASSERT(!m_isDestroyingShadowSubtree);
m_isDestroyingShadowSubtree = true;
if (SpinButtonElement* element = spinButtonElement())
element->removeSpinButtonOwner();
if (ClearButtonElement* element = clearButtonElement())
element->removeClearButtonOwner();
if (DateTimeEditElement* element = dateTimeEditElement())
element->removeEditControlOwner();
if (PickerIndicatorElement* element = pickerIndicatorElement())
element->removePickerIndicatorOwner();
if (containsFocusedShadowElement())
element()->focus();
BaseDateAndTimeInputType::destroyShadowSubtree();
m_isDestroyingShadowSubtree = false;
}
| 171,210 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
Quantum
blue,
green,
red;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
size_t
bits_per_pixel,
height,
length,
width;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PIX image.
*/
width=ReadBlobMSBShort(image);
height=ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image); /* x-offset */
(void) ReadBlobMSBShort(image); /* y-offset */
bits_per_pixel=ReadBlobMSBShort(image);
if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) &&
(bits_per_pixel != 24)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Initialize image structure.
*/
image->columns=width;
image->rows=height;
if (bits_per_pixel == 8)
if (AcquireImageColormap(image,256) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Convert PIX raster image to pixel packets.
*/
red=(Quantum) 0;
green=(Quantum) 0;
blue=(Quantum) 0;
index=(IndexPacket) 0;
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (length == 0)
{
length=(size_t) ReadBlobByte(image);
if (bits_per_pixel == 8)
index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
else
{
blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
}
}
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,index);
SetPixelBlue(q,blue);
SetPixelGreen(q,green);
SetPixelRed(q,red);
length--;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
bits_per_pixel=ReadBlobMSBShort(image);
status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) ||
(bits_per_pixel == 24)) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
Quantum
blue,
green,
red;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
size_t
bits_per_pixel,
height,
length,
width;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PIX image.
*/
width=ReadBlobMSBShort(image);
height=ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image); /* x-offset */
(void) ReadBlobMSBShort(image); /* y-offset */
bits_per_pixel=ReadBlobMSBShort(image);
if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) &&
(bits_per_pixel != 24)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Initialize image structure.
*/
image->columns=width;
image->rows=height;
if (bits_per_pixel == 8)
if (AcquireImageColormap(image,256) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert PIX raster image to pixel packets.
*/
red=(Quantum) 0;
green=(Quantum) 0;
blue=(Quantum) 0;
index=(IndexPacket) 0;
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (length == 0)
{
length=(size_t) ReadBlobByte(image);
if (bits_per_pixel == 8)
index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
else
{
blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
}
}
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,index);
SetPixelBlue(q,blue);
SetPixelGreen(q,green);
SetPixelRed(q,red);
length--;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
bits_per_pixel=ReadBlobMSBShort(image);
status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) ||
(bits_per_pixel == 24)) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,594 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct tcp_sock_t *tcp_open(uint16_t port)
{
struct tcp_sock_t *this = calloc(1, sizeof *this);
if (this == NULL) {
ERR("callocing this failed");
goto error;
}
this->sd = -1;
this->sd = socket(AF_INET6, SOCK_STREAM, 0);
if (this->sd < 0) {
ERR("sockect open failed");
goto error;
}
struct sockaddr_in6 addr;
memset(&addr, 0, sizeof addr);
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_any;
if (bind(this->sd,
(struct sockaddr *)&addr,
sizeof addr) < 0) {
if (g_options.only_desired_port == 1)
ERR("Bind on port failed. "
"Requested port may be taken or require root permissions.");
goto error;
}
if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) {
ERR("listen failed on socket");
goto error;
}
return this;
error:
if (this != NULL) {
if (this->sd != -1) {
close(this->sd);
}
free(this);
}
return NULL;
}
Commit Message: SECURITY FIX: Actually restrict the access to the printer to localhost
Before, any machine in any network connected by any of the interfaces (as
listed by "ifconfig") could access to an IPP-over-USB printer on the assigned
port, allowing users on remote machines to print and to access the web
configuration interface of a IPP-over-USB printer in contrary to conventional
USB printers which are only accessible locally.
CWE ID: CWE-264 | struct tcp_sock_t *tcp_open(uint16_t port)
{
struct tcp_sock_t *this = calloc(1, sizeof *this);
if (this == NULL) {
ERR("IPv4: callocing this failed");
goto error;
}
// Open [S]ocket [D]escriptor
this->sd = -1;
this->sd = socket(AF_INET, SOCK_STREAM, 0);
if (this->sd < 0) {
ERR("IPv4 socket open failed");
goto error;
}
// Configure socket params
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(0x7F000001);
// Bind to localhost
if (bind(this->sd,
(struct sockaddr *)&addr,
sizeof addr) < 0) {
if (g_options.only_desired_port == 1)
ERR("IPv4 bind on port failed. "
"Requested port may be taken or require root permissions.");
goto error;
}
// Let kernel over-accept max number of connections
if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) {
ERR("IPv4 listen failed on socket");
goto error;
}
return this;
error:
if (this != NULL) {
if (this->sd != -1) {
close(this->sd);
}
free(this);
}
return NULL;
}
struct tcp_sock_t *tcp6_open(uint16_t port)
{
struct tcp_sock_t *this = calloc(1, sizeof *this);
if (this == NULL) {
ERR("IPv6: callocing this failed");
goto error;
}
this->sd = -1;
this->sd = socket(AF_INET6, SOCK_STREAM, 0);
if (this->sd < 0) {
ERR("Ipv6 socket open failed");
goto error;
}
struct sockaddr_in6 addr;
memset(&addr, 0, sizeof addr);
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_loopback;
if (bind(this->sd,
(struct sockaddr *)&addr,
sizeof addr) < 0) {
if (g_options.only_desired_port == 1)
ERR("IPv6 bind on port failed. "
"Requested port may be taken or require root permissions.");
goto error;
}
if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) {
ERR("IPv6 listen failed on socket");
goto error;
}
return this;
error:
if (this != NULL) {
if (this->sd != -1) {
close(this->sd);
}
free(this);
}
return NULL;
}
| 166,590 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType WriteIPLImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
IPLInfo
ipl_info;
MagickBooleanType
status;
MagickOffsetType
scene;
register const PixelPacket
*p;
QuantumInfo
*quantum_info;
ssize_t
y;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
quantum_info=AcquireQuantumInfo(image_info, image);
if ((quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
switch(quantum_info->depth){
case 8:
ipl_info.byteType = 0;
break;
case 16:
if(quantum_info->format == SignedQuantumFormat){
ipl_info.byteType = 2;
}
else{
ipl_info.byteType = 1;
}
break;
case 32:
if(quantum_info->format == FloatingPointQuantumFormat){
ipl_info.byteType = 3;
}
else{
ipl_info.byteType = 4;
}
break;
case 64:
ipl_info.byteType = 10;
break;
default:
ipl_info.byteType = 2;
break;
}
ipl_info.z = (unsigned int) GetImageListLength(image);
/* There is no current method for detecting whether we have T or Z stacks */
ipl_info.time = 1;
ipl_info.width = (unsigned int) image->columns;
ipl_info.height = (unsigned int) image->rows;
(void) TransformImageColorspace(image,sRGBColorspace);
if(IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { ipl_info.colors = 3; }
else{ ipl_info.colors = 1; }
ipl_info.size = (unsigned int) (28 +
((image->depth)/8)*ipl_info.height*ipl_info.width*ipl_info.colors*ipl_info.z);
/* Ok! Calculations are done. Lets write this puppy down! */
/*
Write IPL header.
*/
/* Shockingly (maybe not if you have used IPLab), IPLab itself CANNOT read MSBEndian
files! The reader above can, but they cannot. For compatability reasons, I will leave
the code in here, but it is all but useless if you want to use IPLab. */
if(image_info->endian == MSBEndian)
(void) WriteBlob(image, 4, (const unsigned char *) "mmmm");
else{
image->endian = LSBEndian;
(void) WriteBlob(image, 4, (const unsigned char *) "iiii");
}
(void) WriteBlobLong(image, 4);
(void) WriteBlob(image, 4, (const unsigned char *) "100f");
(void) WriteBlob(image, 4, (const unsigned char *) "data");
(void) WriteBlobLong(image, ipl_info.size);
(void) WriteBlobLong(image, ipl_info.width);
(void) WriteBlobLong(image, ipl_info.height);
(void) WriteBlobLong(image, ipl_info.colors);
if(image_info->adjoin == MagickFalse)
(void) WriteBlobLong(image, 1);
else
(void) WriteBlobLong(image, ipl_info.z);
(void) WriteBlobLong(image, ipl_info.time);
(void) WriteBlobLong(image, ipl_info.byteType);
exception=(&image->exception);
do
{
/*
Convert MIFF to IPL raster pixels.
*/
pixels=GetQuantumPixels(quantum_info);
if(ipl_info.colors == 1){
/* Red frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
GrayQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
}
}
if(ipl_info.colors == 3){
/* Red frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
RedQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
}
/* Green frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
GreenQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
}
/* Blue frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
BlueQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
}while (image_info->adjoin != MagickFalse);
(void) WriteBlob(image, 4, (const unsigned char *) "fini");
(void) WriteBlobLong(image, 0);
CloseBlob(image);
return(MagickTrue);
}
Commit Message: ...
CWE ID: CWE-284 | static MagickBooleanType WriteIPLImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
IPLInfo
ipl_info;
MagickBooleanType
status;
MagickOffsetType
scene;
register const PixelPacket
*p;
QuantumInfo
*quantum_info;
ssize_t
y;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
quantum_info=AcquireQuantumInfo(image_info, image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
switch(quantum_info->depth){
case 8:
ipl_info.byteType = 0;
break;
case 16:
if(quantum_info->format == SignedQuantumFormat){
ipl_info.byteType = 2;
}
else{
ipl_info.byteType = 1;
}
break;
case 32:
if(quantum_info->format == FloatingPointQuantumFormat){
ipl_info.byteType = 3;
}
else{
ipl_info.byteType = 4;
}
break;
case 64:
ipl_info.byteType = 10;
break;
default:
ipl_info.byteType = 2;
break;
}
ipl_info.z = (unsigned int) GetImageListLength(image);
/* There is no current method for detecting whether we have T or Z stacks */
ipl_info.time = 1;
ipl_info.width = (unsigned int) image->columns;
ipl_info.height = (unsigned int) image->rows;
(void) TransformImageColorspace(image,sRGBColorspace);
if(IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { ipl_info.colors = 3; }
else{ ipl_info.colors = 1; }
ipl_info.size = (unsigned int) (28 +
((image->depth)/8)*ipl_info.height*ipl_info.width*ipl_info.colors*ipl_info.z);
/* Ok! Calculations are done. Lets write this puppy down! */
/*
Write IPL header.
*/
/* Shockingly (maybe not if you have used IPLab), IPLab itself CANNOT read MSBEndian
files! The reader above can, but they cannot. For compatability reasons, I will leave
the code in here, but it is all but useless if you want to use IPLab. */
if(image_info->endian == MSBEndian)
(void) WriteBlob(image, 4, (const unsigned char *) "mmmm");
else{
image->endian = LSBEndian;
(void) WriteBlob(image, 4, (const unsigned char *) "iiii");
}
(void) WriteBlobLong(image, 4);
(void) WriteBlob(image, 4, (const unsigned char *) "100f");
(void) WriteBlob(image, 4, (const unsigned char *) "data");
(void) WriteBlobLong(image, ipl_info.size);
(void) WriteBlobLong(image, ipl_info.width);
(void) WriteBlobLong(image, ipl_info.height);
(void) WriteBlobLong(image, ipl_info.colors);
if(image_info->adjoin == MagickFalse)
(void) WriteBlobLong(image, 1);
else
(void) WriteBlobLong(image, ipl_info.z);
(void) WriteBlobLong(image, ipl_info.time);
(void) WriteBlobLong(image, ipl_info.byteType);
exception=(&image->exception);
do
{
/*
Convert MIFF to IPL raster pixels.
*/
pixels=GetQuantumPixels(quantum_info);
if(ipl_info.colors == 1){
/* Red frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
GrayQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
}
}
if(ipl_info.colors == 3){
/* Red frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
RedQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
}
/* Green frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
GreenQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
}
/* Blue frame */
for(y = 0; y < (ssize_t) ipl_info.height; y++){
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,
BlueQuantum, pixels,&image->exception);
(void) WriteBlob(image, image->columns*image->depth/8, pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
}while (image_info->adjoin != MagickFalse);
(void) WriteBlob(image, 4, (const unsigned char *) "fini");
(void) WriteBlobLong(image, 0);
CloseBlob(image);
return(MagickTrue);
}
| 168,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Chapters::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
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 == 0x05B9) { // EditionEntry ID
status = ParseEdition(pos, size);
if (status < 0) // error
return status;
}
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::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
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 == 0x05B9) { // EditionEntry ID
status = ParseEdition(pos, size);
if (status < 0) // error
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,838 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DECLAREcpFunc(cpSeparate2ContigByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
for (row = 0; row < imagelength; row++) {
/* merge channels */
for (s = 0; s < spp; s++) {
if (TIFFReadScanline(in, inbuf, row, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = (uint8*)inbuf;
outp = ((uint8*)outbuf) + s;
for (n = imagewidth; n-- > 0;) {
*outp = *inp++;
outp += spp;
}
}
if (TIFFWriteScanline(out, outbuf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and
cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and
http://bugzilla.maptools.org/show_bug.cgi?id=2657
CWE ID: CWE-119 | DECLAREcpFunc(cpSeparate2ContigByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
uint16 bps = 0;
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps != 8 )
{
TIFFError(TIFFFileName(in),
"Error, can only handle BitsPerSample=8 in %s",
"cpSeparate2ContigByRow");
return 0;
}
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
for (row = 0; row < imagelength; row++) {
/* merge channels */
for (s = 0; s < spp; s++) {
if (TIFFReadScanline(in, inbuf, row, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = (uint8*)inbuf;
outp = ((uint8*)outbuf) + s;
for (n = imagewidth; n-- > 0;) {
*outp = *inp++;
outp += spp;
}
}
if (TIFFWriteScanline(out, outbuf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
| 168,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color)
{
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color)
{
notImplemented();
}
| 170,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_tRNS_to_alpha_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_tRNS_to_alpha(pp);
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_tRNS_to_alpha_set(PNG_CONST image_transform *this,
image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_tRNS_to_alpha(pp);
/* If there was a tRNS chunk that would get expanded and add an alpha
* channel is_transparent must be updated:
*/
if (that->this.has_tRNS)
that->this.is_transparent = 1;
this->next->set(this->next, that, pp, pi);
}
| 173,656 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: t42_parse_font_matrix( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
(void)T1_ToFixedArray( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
Commit Message:
CWE ID: CWE-20 | t42_parse_font_matrix( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
| 165,343 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return true;
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
Commit Message: xkbcomp: Don't falsely promise from ExprResolveLhs
Every user of ExprReturnLhs goes on to unconditionally dereference the
field return, which can be NULL if xkb_intern_atom fails. Return false
if this is the case, so we fail safely.
testcase: splice geometry data into interp
Signed-off-by: Daniel Stone <[email protected]>
CWE ID: CWE-476 | ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
| 169,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void _modinit(module_t *m)
{
service_named_bind_command("chanserv", &cs_flags);
}
Commit Message: chanserv/flags: make Anope FLAGS compatibility an option
Previously, ChanServ FLAGS behavior could be modified by registering or
dropping the keyword nicks "LIST", "CLEAR", and "MODIFY".
Now, a configuration option is available that when turned on (default),
disables registration of these keyword nicks and enables this
compatibility feature. When turned off, registration of these keyword
nicks is possible, and compatibility to Anope's FLAGS command is
disabled.
Fixes atheme/atheme#397
CWE ID: CWE-284 | void _modinit(module_t *m)
{
service_named_bind_command("chanserv", &cs_flags);
add_bool_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table, 0, &anope_flags_compat, true);
hook_add_event("nick_can_register");
hook_add_nick_can_register(check_registration_keywords);
hook_add_event("user_can_register");
hook_add_user_can_register(check_registration_keywords);
}
| 167,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyStereo16(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i];
*dst++ = src[1][i];
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyStereo16(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i];
*dst++ = src[1][i];
}
}
| 174,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionScriptAndCaptureVisibleTest()
: http_url("http://www.google.com"),
http_url_with_path("http://www.google.com/index.html"),
https_url("https://www.google.com"),
example_com("https://example.com"),
test_example_com("https://test.example.com"),
sample_example_com("https://sample.example.com"),
file_url("file:///foo/bar"),
favicon_url("chrome://favicon/http://www.google.com"),
extension_url("chrome-extension://" +
crx_file::id_util::GenerateIdForPath(
base::FilePath(FILE_PATH_LITERAL("foo")))),
settings_url("chrome://settings"),
about_url("about:flags") {
urls_.insert(http_url);
urls_.insert(http_url_with_path);
urls_.insert(https_url);
urls_.insert(example_com);
urls_.insert(test_example_com);
urls_.insert(sample_example_com);
urls_.insert(file_url);
urls_.insert(favicon_url);
urls_.insert(extension_url);
urls_.insert(settings_url);
urls_.insert(about_url);
PermissionsData::SetPolicyDelegate(NULL);
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20 | ExtensionScriptAndCaptureVisibleTest()
: http_url("http://www.google.com"),
http_url_with_path("http://www.google.com/index.html"),
https_url("https://www.google.com"),
example_com("https://example.com"),
test_example_com("https://test.example.com"),
sample_example_com("https://sample.example.com"),
file_url("file:///foo/bar"),
favicon_url("chrome://favicon/http://www.google.com"),
extension_url("chrome-extension://" +
crx_file::id_util::GenerateIdForPath(
base::FilePath(FILE_PATH_LITERAL("foo")))),
settings_url("chrome://settings"),
about_flags_url("about:flags") {
urls_.insert(http_url);
urls_.insert(http_url_with_path);
urls_.insert(https_url);
urls_.insert(example_com);
urls_.insert(test_example_com);
urls_.insert(sample_example_com);
urls_.insert(file_url);
urls_.insert(favicon_url);
urls_.insert(extension_url);
urls_.insert(settings_url);
urls_.insert(about_flags_url);
PermissionsData::SetPolicyDelegate(NULL);
}
| 173,231 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IsIDNComponentSafe(base::StringPiece16 label, bool is_tld_ascii) {
return g_idn_spoof_checker.Get().SafeToDisplayAsUnicode(label, is_tld_ascii);
}
Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains
This character (þ) can be confused with both b and p when used in a domain
name. IDN spoof checker doesn't have a good way of flagging a character as
confusable with multiple characters, so it can't catch spoofs containing
this character. As a practical fix, this CL restricts this character to
domains under Iceland's ccTLD (.is). With this change, a domain name containing
"þ" with a non-.is TLD will be displayed in punycode in the UI.
This change affects less than 10 real world domains with limited popularity.
Bug: 798892, 843352, 904327, 1017707
Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Christopher Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#709309}
CWE ID: | bool IsIDNComponentSafe(base::StringPiece16 label, bool is_tld_ascii) {
bool IsIDNComponentSafe(base::StringPiece16 label,
base::StringPiece top_level_domain) {
return g_idn_spoof_checker.Get().SafeToDisplayAsUnicode(label,
top_level_domain);
}
| 172,730 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void f2fs_put_super(struct super_block *sb)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
int i;
f2fs_quota_off_umount(sb);
/* prevent remaining shrinker jobs */
mutex_lock(&sbi->umount_mutex);
/*
* We don't need to do checkpoint when superblock is clean.
* But, the previous checkpoint was not done by umount, it needs to do
* clean checkpoint again.
*/
if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
struct cp_control cpc = {
.reason = CP_UMOUNT,
};
write_checkpoint(sbi, &cpc);
}
/* be sure to wait for any on-going discard commands */
f2fs_wait_discard_bios(sbi);
if (f2fs_discard_en(sbi) && !sbi->discard_blks) {
struct cp_control cpc = {
.reason = CP_UMOUNT | CP_TRIMMED,
};
write_checkpoint(sbi, &cpc);
}
/* write_checkpoint can update stat informaion */
f2fs_destroy_stats(sbi);
/*
* normally superblock is clean, so we need to release this.
* In addition, EIO will skip do checkpoint, we need this as well.
*/
release_ino_entry(sbi, true);
f2fs_leave_shrinker(sbi);
mutex_unlock(&sbi->umount_mutex);
/* our cp_error case, we can wait for any writeback page */
f2fs_flush_merged_writes(sbi);
iput(sbi->node_inode);
iput(sbi->meta_inode);
/* destroy f2fs internal modules */
destroy_node_manager(sbi);
destroy_segment_manager(sbi);
kfree(sbi->ckpt);
f2fs_unregister_sysfs(sbi);
sb->s_fs_info = NULL;
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->raw_super);
destroy_device_list(sbi);
mempool_destroy(sbi->write_io_dummy);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
destroy_percpu_info(sbi);
for (i = 0; i < NR_PAGE_TYPE; i++)
kfree(sbi->write_io[i]);
kfree(sbi);
}
Commit Message: f2fs: fix potential panic during fstrim
As Ju Hyung Park reported:
"When 'fstrim' is called for manual trim, a BUG() can be triggered
randomly with this patch.
I'm seeing this issue on both x86 Desktop and arm64 Android phone.
On x86 Desktop, this was caused during Ubuntu boot-up. I have a
cronjob installed which calls 'fstrim -v /' during boot. On arm64
Android, this was caused during GC looping with 1ms gc_min_sleep_time
& gc_max_sleep_time."
Root cause of this issue is that f2fs_wait_discard_bios can only be
used by f2fs_put_super, because during put_super there must be no
other referrers, so it can ignore discard entry's reference count
when removing the entry, otherwise in other caller we will hit bug_on
in __remove_discard_cmd as there may be other issuer added reference
count in discard entry.
Thread A Thread B
- issue_discard_thread
- f2fs_ioc_fitrim
- f2fs_trim_fs
- f2fs_wait_discard_bios
- __issue_discard_cmd
- __submit_discard_cmd
- __wait_discard_cmd
- dc->ref++
- __wait_one_discard_bio
- __wait_discard_cmd
- __remove_discard_cmd
- f2fs_bug_on(sbi, dc->ref)
Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de
Reported-by: Ju Hyung Park <[email protected]>
Signed-off-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-20 | static void f2fs_put_super(struct super_block *sb)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
int i;
f2fs_quota_off_umount(sb);
/* prevent remaining shrinker jobs */
mutex_lock(&sbi->umount_mutex);
/*
* We don't need to do checkpoint when superblock is clean.
* But, the previous checkpoint was not done by umount, it needs to do
* clean checkpoint again.
*/
if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
struct cp_control cpc = {
.reason = CP_UMOUNT,
};
write_checkpoint(sbi, &cpc);
}
/* be sure to wait for any on-going discard commands */
f2fs_wait_discard_bios(sbi, true);
if (f2fs_discard_en(sbi) && !sbi->discard_blks) {
struct cp_control cpc = {
.reason = CP_UMOUNT | CP_TRIMMED,
};
write_checkpoint(sbi, &cpc);
}
/* write_checkpoint can update stat informaion */
f2fs_destroy_stats(sbi);
/*
* normally superblock is clean, so we need to release this.
* In addition, EIO will skip do checkpoint, we need this as well.
*/
release_ino_entry(sbi, true);
f2fs_leave_shrinker(sbi);
mutex_unlock(&sbi->umount_mutex);
/* our cp_error case, we can wait for any writeback page */
f2fs_flush_merged_writes(sbi);
iput(sbi->node_inode);
iput(sbi->meta_inode);
/* destroy f2fs internal modules */
destroy_node_manager(sbi);
destroy_segment_manager(sbi);
kfree(sbi->ckpt);
f2fs_unregister_sysfs(sbi);
sb->s_fs_info = NULL;
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->raw_super);
destroy_device_list(sbi);
mempool_destroy(sbi->write_io_dummy);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
destroy_percpu_info(sbi);
for (i = 0; i < NR_PAGE_TYPE; i++)
kfree(sbi->write_io[i]);
kfree(sbi);
}
| 169,415 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DWORD WtsSessionProcessDelegate::Core::GetExitCode() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
DWORD exit_code = CONTROL_C_EXIT;
if (worker_process_.IsValid()) {
if (!::GetExitCodeProcess(worker_process_, &exit_code)) {
LOG_GETLASTERROR(INFO)
<< "Failed to query the exit code of the worker process";
exit_code = CONTROL_C_EXIT;
}
}
return exit_code;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | DWORD WtsSessionProcessDelegate::Core::GetExitCode() {
DWORD WtsSessionProcessDelegate::Core::GetProcessId() const {
DWORD pid = 0;
if (pipe_.IsValid() && get_named_pipe_client_pid_(pipe_, &pid)) {
return pid;
} else {
return 0;
}
}
bool WtsSessionProcessDelegate::Core::IsPermanentError(
int failure_count) const {
// Get exit code of the worker process if it is available.
DWORD exit_code = CONTROL_C_EXIT;
if (worker_process_.IsValid()) {
if (!::GetExitCodeProcess(worker_process_, &exit_code)) {
LOG_GETLASTERROR(INFO)
<< "Failed to query the exit code of the worker process";
exit_code = CONTROL_C_EXIT;
}
}
// Stop trying to restart the worker process if it exited due to
// misconfiguration.
return (kMinPermanentErrorExitCode <= exit_code &&
exit_code <= kMaxPermanentErrorExitCode);
}
| 171,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result==1) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
Commit Message: fix bug #64660 - yyparse can return 2, not only 1
CWE ID: CWE-20 | ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result != 0) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
| 166,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,
struct vsock_sock *vsk,
struct msghdr *msg, size_t len,
int flags)
{
int err;
int noblock;
struct vmci_datagram *dg;
size_t payload_len;
struct sk_buff *skb;
noblock = flags & MSG_DONTWAIT;
if (flags & MSG_OOB || flags & MSG_ERRQUEUE)
return -EOPNOTSUPP;
msg->msg_namelen = 0;
/* Retrieve the head sk_buff from the socket's receive queue. */
err = 0;
skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);
if (err)
return err;
if (!skb)
return -EAGAIN;
dg = (struct vmci_datagram *)skb->data;
if (!dg)
/* err is 0, meaning we read zero bytes. */
goto out;
payload_len = dg->payload_size;
/* Ensure the sk_buff matches the payload size claimed in the packet. */
if (payload_len != skb->len - sizeof(*dg)) {
err = -EINVAL;
goto out;
}
if (payload_len > len) {
payload_len = len;
msg->msg_flags |= MSG_TRUNC;
}
/* Place the datagram payload in the user's iovec. */
err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,
payload_len);
if (err)
goto out;
if (msg->msg_name) {
struct sockaddr_vm *vm_addr;
/* Provide the address of the sender. */
vm_addr = (struct sockaddr_vm *)msg->msg_name;
vsock_addr_init(vm_addr, dg->src.context, dg->src.resource);
msg->msg_namelen = sizeof(*vm_addr);
}
err = payload_len;
out:
skb_free_datagram(&vsk->sk, skb);
return err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,
struct vsock_sock *vsk,
struct msghdr *msg, size_t len,
int flags)
{
int err;
int noblock;
struct vmci_datagram *dg;
size_t payload_len;
struct sk_buff *skb;
noblock = flags & MSG_DONTWAIT;
if (flags & MSG_OOB || flags & MSG_ERRQUEUE)
return -EOPNOTSUPP;
/* Retrieve the head sk_buff from the socket's receive queue. */
err = 0;
skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);
if (err)
return err;
if (!skb)
return -EAGAIN;
dg = (struct vmci_datagram *)skb->data;
if (!dg)
/* err is 0, meaning we read zero bytes. */
goto out;
payload_len = dg->payload_size;
/* Ensure the sk_buff matches the payload size claimed in the packet. */
if (payload_len != skb->len - sizeof(*dg)) {
err = -EINVAL;
goto out;
}
if (payload_len > len) {
payload_len = len;
msg->msg_flags |= MSG_TRUNC;
}
/* Place the datagram payload in the user's iovec. */
err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,
payload_len);
if (err)
goto out;
if (msg->msg_name) {
struct sockaddr_vm *vm_addr;
/* Provide the address of the sender. */
vm_addr = (struct sockaddr_vm *)msg->msg_name;
vsock_addr_init(vm_addr, dg->src.context, dg->src.resource);
msg->msg_namelen = sizeof(*vm_addr);
}
err = payload_len;
out:
skb_free_datagram(&vsk->sk, skb);
return err;
}
| 166,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,
struct nfs4_state_owner *sp, int flags,
const struct iattr *attrs)
{
struct dentry *parent = dget_parent(path->dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);
if (p->o_arg.seqid == NULL)
goto err_free;
p->path.mnt = mntget(path->mnt);
p->path.dentry = dget(path->dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags,
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id = sp->so_owner_id.id;
p->o_arg.name = &p->path.dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (flags & O_EXCL) {
u32 *s = (u32 *) p->o_arg.u.verifier.data;
s[0] = jiffies;
s[1] = current->pid;
} else if (flags & O_CREAT) {
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,
struct nfs4_state_owner *sp, fmode_t fmode, int flags,
const struct iattr *attrs)
{
struct dentry *parent = dget_parent(path->dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);
if (p->o_arg.seqid == NULL)
goto err_free;
p->path.mnt = mntget(path->mnt);
p->path.dentry = dget(path->dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags;
p->o_arg.fmode = fmode & (FMODE_READ|FMODE_WRITE);
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id = sp->so_owner_id.id;
p->o_arg.name = &p->path.dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (flags & O_EXCL) {
u32 *s = (u32 *) p->o_arg.u.verifier.data;
s[0] = jiffies;
s[1] = current->pid;
} else if (flags & O_CREAT) {
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
}
| 165,700 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.