instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.x = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.y = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
rect.width = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
rect.height = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189 | PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.x = Z_LVAL(lval);
} else {
rect.x = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.y = Z_LVAL(lval);
} else {
rect.y = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.width = Z_LVAL(lval);
} else {
rect.width = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.height = Z_LVAL(lval);
} else {
rect.height = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
| 166,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_principal_2_svc(gprinc_arg *arg, struct svc_req *rqstp)
{
static gprinc_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gprinc_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_get_principal";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE,
arg->princ,
NULL))) {
ret.code = KADM5_AUTH_GET;
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principal(handle, arg->princ, &ret.rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | get_principal_2_svc(gprinc_arg *arg, struct svc_req *rqstp)
{
static gprinc_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gprinc_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_get_principal";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE,
arg->princ,
NULL))) {
ret.code = KADM5_AUTH_GET;
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principal(handle, arg->princ, &ret.rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,515 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NetworkHandler::NetworkHandler(const std::string& host_id)
: DevToolsDomainHandler(Network::Metainfo::domainName),
process_(nullptr),
host_(nullptr),
enabled_(false),
host_id_(host_id),
bypass_service_worker_(false),
cache_disabled_(false),
weak_factory_(this) {
static bool have_configured_service_worker_context = false;
if (have_configured_service_worker_context)
return;
have_configured_service_worker_context = true;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&ConfigureServiceWorkerContextOnIO));
}
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 | NetworkHandler::NetworkHandler(const std::string& host_id)
: DevToolsDomainHandler(Network::Metainfo::domainName),
browser_context_(nullptr),
storage_partition_(nullptr),
host_(nullptr),
enabled_(false),
host_id_(host_id),
bypass_service_worker_(false),
cache_disabled_(false),
weak_factory_(this) {
static bool have_configured_service_worker_context = false;
if (have_configured_service_worker_context)
return;
have_configured_service_worker_context = true;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&ConfigureServiceWorkerContextOnIO));
}
| 172,759 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416 | PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
| 164,970 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
OnQueryKnownToValidate)
IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
OnSetKnownToValidate)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler,
OnAttachDebugExceptionHandler)
#endif
IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelCreated,
OnPpapiChannelCreated)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
OnQueryKnownToValidate)
IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
OnSetKnownToValidate)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler,
OnAttachDebugExceptionHandler)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
| 170,725 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int spl_load_fit_image(struct spl_load_info *info, ulong sector,
void *fit, ulong base_offset, int node,
struct spl_image_info *image_info)
{
int offset;
size_t length;
int len;
ulong size;
ulong load_addr, load_ptr;
void *src;
ulong overhead;
int nr_sectors;
int align_len = ARCH_DMA_MINALIGN - 1;
uint8_t image_comp = -1, type = -1;
const void *data;
bool external_data = false;
if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
(IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
if (fit_image_get_type(fit, node, &type))
puts("Cannot get image type.\n");
else
debug("%s ", genimg_get_type_name(type));
}
if (IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP)) {
if (fit_image_get_comp(fit, node, &image_comp))
puts("Cannot get image compression format.\n");
else
debug("%s ", genimg_get_comp_name(image_comp));
}
if (fit_image_get_load(fit, node, &load_addr))
load_addr = image_info->load_addr;
if (!fit_image_get_data_position(fit, node, &offset)) {
external_data = true;
} else if (!fit_image_get_data_offset(fit, node, &offset)) {
offset += base_offset;
external_data = true;
}
if (external_data) {
/* External data */
if (fit_image_get_data_size(fit, node, &len))
return -ENOENT;
load_ptr = (load_addr + align_len) & ~align_len;
length = len;
overhead = get_aligned_image_overhead(info, offset);
nr_sectors = get_aligned_image_size(info, length, offset);
if (info->read(info,
sector + get_aligned_image_offset(info, offset),
nr_sectors, (void *)load_ptr) != nr_sectors)
return -EIO;
debug("External data: dst=%lx, offset=%x, size=%lx\n",
load_ptr, offset, (unsigned long)length);
src = (void *)load_ptr + overhead;
} else {
/* Embedded data */
if (fit_image_get_data(fit, node, &data, &length)) {
puts("Cannot get image data/size\n");
return -ENOENT;
}
debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
(unsigned long)length);
src = (void *)data;
}
#ifdef CONFIG_SPL_FIT_SIGNATURE
printf("## Checking hash(es) for Image %s ... ",
fit_get_name(fit, node, NULL));
if (!fit_image_verify_with_data(fit, node,
src, length))
return -EPERM;
puts("OK\n");
#endif
#ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
board_fit_image_post_process(&src, &length);
#endif
if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
size = length;
if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
src, &size)) {
puts("Uncompressing error\n");
return -EIO;
}
length = size;
} else {
memcpy((void *)load_addr, src, length);
}
if (image_info) {
image_info->load_addr = load_addr;
image_info->size = length;
image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
}
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | static int spl_load_fit_image(struct spl_load_info *info, ulong sector,
void *fit, ulong base_offset, int node,
struct spl_image_info *image_info)
{
int offset;
size_t length;
int len;
ulong size;
ulong load_addr, load_ptr;
void *src;
ulong overhead;
int nr_sectors;
int align_len = ARCH_DMA_MINALIGN - 1;
uint8_t image_comp = -1, type = -1;
const void *data;
bool external_data = false;
if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
(IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
if (fit_image_get_type(fit, node, &type))
puts("Cannot get image type.\n");
else
debug("%s ", genimg_get_type_name(type));
}
if (IS_ENABLED(CONFIG_SPL_GZIP)) {
fit_image_get_comp(fit, node, &image_comp);
debug("%s ", genimg_get_comp_name(image_comp));
}
if (fit_image_get_load(fit, node, &load_addr))
load_addr = image_info->load_addr;
if (!fit_image_get_data_position(fit, node, &offset)) {
external_data = true;
} else if (!fit_image_get_data_offset(fit, node, &offset)) {
offset += base_offset;
external_data = true;
}
if (external_data) {
/* External data */
if (fit_image_get_data_size(fit, node, &len))
return -ENOENT;
load_ptr = (load_addr + align_len) & ~align_len;
length = len;
overhead = get_aligned_image_overhead(info, offset);
nr_sectors = get_aligned_image_size(info, length, offset);
if (info->read(info,
sector + get_aligned_image_offset(info, offset),
nr_sectors, (void *)load_ptr) != nr_sectors)
return -EIO;
debug("External data: dst=%lx, offset=%x, size=%lx\n",
load_ptr, offset, (unsigned long)length);
src = (void *)load_ptr + overhead;
} else {
/* Embedded data */
if (fit_image_get_data(fit, node, &data, &length)) {
puts("Cannot get image data/size\n");
return -ENOENT;
}
debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
(unsigned long)length);
src = (void *)data;
}
#ifdef CONFIG_SPL_FIT_SIGNATURE
printf("## Checking hash(es) for Image %s ... ",
fit_get_name(fit, node, NULL));
if (!fit_image_verify_with_data(fit, node,
src, length))
return -EPERM;
puts("OK\n");
#endif
#ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
board_fit_image_post_process(&src, &length);
#endif
if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
size = length;
if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
src, &size)) {
puts("Uncompressing error\n");
return -EIO;
}
length = size;
} else {
memcpy((void *)load_addr, src, length);
}
if (image_info) {
image_info->load_addr = load_addr;
image_info->size = length;
image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
}
return 0;
}
| 169,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fillWidgetStates(AXObject& axObject,
protocol::Array<AXProperty>& properties) {
AccessibilityRole role = axObject.roleValue();
if (roleAllowsChecked(role)) {
AccessibilityButtonState checked = axObject.checkboxOrRadioValue();
switch (checked) {
case ButtonStateOff:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("false", AXValueTypeEnum::Tristate)));
break;
case ButtonStateOn:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("true", AXValueTypeEnum::Tristate)));
break;
case ButtonStateMixed:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("mixed", AXValueTypeEnum::Tristate)));
break;
}
}
AccessibilityExpanded expanded = axObject.isExpanded();
switch (expanded) {
case ExpandedUndefined:
break;
case ExpandedCollapsed:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined)));
break;
case ExpandedExpanded:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
break;
}
if (role == ToggleButtonRole) {
if (!axObject.isPressed()) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("false", AXValueTypeEnum::Tristate)));
} else {
const AtomicString& pressedAttr =
axObject.getAttribute(HTMLNames::aria_pressedAttr);
if (equalIgnoringCase(pressedAttr, "mixed"))
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("mixed", AXValueTypeEnum::Tristate)));
else
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("true", AXValueTypeEnum::Tristate)));
}
}
if (roleAllowsSelected(role)) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Selected,
createBooleanValue(axObject.isSelected())));
}
if (roleAllowsModal(role)) {
properties.addItem(createProperty(AXWidgetStatesEnum::Modal,
createBooleanValue(axObject.isModal())));
}
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | void fillWidgetStates(AXObject& axObject,
protocol::Array<AXProperty>& properties) {
AccessibilityRole role = axObject.roleValue();
if (roleAllowsChecked(role)) {
AccessibilityButtonState checked = axObject.checkboxOrRadioValue();
switch (checked) {
case ButtonStateOff:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("false", AXValueTypeEnum::Tristate)));
break;
case ButtonStateOn:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("true", AXValueTypeEnum::Tristate)));
break;
case ButtonStateMixed:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("mixed", AXValueTypeEnum::Tristate)));
break;
}
}
AccessibilityExpanded expanded = axObject.isExpanded();
switch (expanded) {
case ExpandedUndefined:
break;
case ExpandedCollapsed:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined)));
break;
case ExpandedExpanded:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
break;
}
if (role == ToggleButtonRole) {
if (!axObject.isPressed()) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("false", AXValueTypeEnum::Tristate)));
} else {
const AtomicString& pressedAttr =
axObject.getAttribute(HTMLNames::aria_pressedAttr);
if (equalIgnoringASCIICase(pressedAttr, "mixed"))
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("mixed", AXValueTypeEnum::Tristate)));
else
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("true", AXValueTypeEnum::Tristate)));
}
}
if (roleAllowsSelected(role)) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Selected,
createBooleanValue(axObject.isSelected())));
}
if (roleAllowsModal(role)) {
properties.addItem(createProperty(AXWidgetStatesEnum::Modal,
createBooleanValue(axObject.isModal())));
}
}
| 171,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderMessageFilter::OnCreateWindow(
const ViewHostMsg_CreateWindow_Params& params,
int* route_id,
int* surface_id,
int64* cloned_session_storage_namespace_id) {
bool no_javascript_access;
bool can_create_window =
GetContentClient()->browser()->CanCreateWindow(
GURL(params.opener_url),
GURL(params.opener_security_origin),
params.window_container_type,
resource_context_,
render_process_id_,
&no_javascript_access);
if (!can_create_window) {
*route_id = MSG_ROUTING_NONE;
*surface_id = 0;
return;
}
scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace =
new SessionStorageNamespaceImpl(dom_storage_context_,
params.session_storage_namespace_id);
*cloned_session_storage_namespace_id = cloned_namespace->id();
render_widget_helper_->CreateNewWindow(params,
no_javascript_access,
peer_handle(),
route_id,
surface_id,
cloned_namespace);
}
Commit Message: Filter more incoming URLs in the CreateWindow path.
BUG=170532
Review URL: https://chromiumcodereview.appspot.com/12036002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderMessageFilter::OnCreateWindow(
const ViewHostMsg_CreateWindow_Params& params,
int* route_id,
int* surface_id,
int64* cloned_session_storage_namespace_id) {
bool no_javascript_access;
bool can_create_window =
GetContentClient()->browser()->CanCreateWindow(
params.opener_url,
params.opener_security_origin,
params.window_container_type,
resource_context_,
render_process_id_,
&no_javascript_access);
if (!can_create_window) {
*route_id = MSG_ROUTING_NONE;
*surface_id = 0;
return;
}
scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace =
new SessionStorageNamespaceImpl(dom_storage_context_,
params.session_storage_namespace_id);
*cloned_session_storage_namespace_id = cloned_namespace->id();
render_widget_helper_->CreateNewWindow(params,
no_javascript_access,
peer_handle(),
route_id,
surface_id,
cloned_namespace);
}
| 171,497 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
size_t n_size = ( grp->nbits + 7 ) / 8;
#if defined(ECP_MONTGOMERY)
if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last three bits are unset */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
else
#endif /* ECP_MONTGOMERY */
#if defined(ECP_SHORTWEIERSTRASS)
if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
}
else
#endif /* ECP_SHORTWEIERSTRASS */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
cleanup:
if( ret != 0 )
return( ret );
return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200 | int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t n_size = ( grp->nbits + 7 ) / 8;
#if defined(ECP_MONTGOMERY)
if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last three bits are unset */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
#endif /* ECP_MONTGOMERY */
#if defined(ECP_SHORTWEIERSTRASS)
if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
}
#endif /* ECP_SHORTWEIERSTRASS */
cleanup:
return( ret );
}
/*
* Generate a keypair with configurable base point
*/
int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
cleanup:
return( ret );
}
| 170,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize)
{
unsigned char *buf;
assert(m->buf_);
assert(bufsize >= 0);
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char)))) {
return -1;
}
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
Commit Message: The memory stream interface allows for a buffer size of zero.
The case of a zero-sized buffer was not handled correctly, as it could
lead to a double free.
This problem has now been fixed (hopefully).
One might ask whether a zero-sized buffer should be allowed at all,
but this is a question for another day.
CWE ID: CWE-415 | static int mem_resize(jas_stream_memobj_t *m, int bufsize)
{
unsigned char *buf;
//assert(m->buf_);
assert(bufsize >= 0);
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
bufsize) {
return -1;
}
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
| 168,759 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (!mp)
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
umount_tree(mnt, 0);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
Commit Message: mnt: Honor MNT_LOCKED when detaching mounts
Modify umount(MNT_DETACH) to keep mounts in the hash table that are
locked to their parent mounts, when the parent is lazily unmounted.
In mntput_no_expire detach the children from the hash table, depending
on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children.
In __detach_mounts if there are any mounts that have been unmounted
but still are on the list of mounts of a mountpoint, remove their
children from the mount hash table and those children to the unmounted
list so they won't linger potentially indefinitely waiting for their
final mntput, now that the mounts serve no purpose.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-284 | void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (!mp)
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
hlist_add_head(&p->mnt_umount.s_list, &unmounted);
umount_mnt(p);
}
}
else umount_tree(mnt, 0);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
| 167,588 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothOptionsHandler::RequestConfirmation(
chromeos::BluetoothDevice* device,
int passkey) {
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void BluetoothOptionsHandler::RequestConfirmation(
chromeos::BluetoothDevice* device,
int passkey) {
DictionaryValue params;
params.SetString("pairing", "bluetoothConfirmPasskey");
params.SetInteger("passkey", passkey);
SendDeviceNotification(device, ¶ms);
}
| 170,971 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsingState(InDOMContentLoaded);
if (!m_documentTiming.domContentLoadedEventStart())
m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime());
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd())
m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime());
setParsingState(FinishedParsing);
RefPtrWillBeRawPtr<Document> protect(this);
Microtask::performCheckpoint();
if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
if (mainResourceWasAlreadyRequested)
updateLayoutTreeIfNeeded();
frame->loader().finishedParsing();
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get()));
InspectorInstrumentation::domContentLoadedEventFired(frame.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254 | void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsingState(InDOMContentLoaded);
if (!m_documentTiming.domContentLoadedEventStart())
m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime());
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd())
m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime());
setParsingState(FinishedParsing);
RefPtrWillBeRawPtr<Document> protect(this);
Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate());
if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
if (mainResourceWasAlreadyRequested)
updateLayoutTreeIfNeeded();
frame->loader().finishedParsing();
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get()));
InspectorInstrumentation::domContentLoadedEventFired(frame.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
}
| 171,944 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + nbytes;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + nbytes;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
Commit Message: * Enforce limit of 8K on regex searches that have no limits
* Allow the l modifier for regex to mean line count. Default
to byte count. If line count is specified, assume a max
of 80 characters per line to limit the byte count.
* Don't allow conversions to be used for dates, allowing
the mask field to be used as an offset.
* Bump the version of the magic format so that regex changes
are visible.
CWE ID: CWE-399 | mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines, linecnt, bytecnt;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
if (m->str_flags & REGEX_LINE_COUNT) {
linecnt = m->str_range;
bytecnt = linecnt * 80;
} else {
linecnt = 0;
bytecnt = m->str_range;
}
if (bytecnt == 0)
bytecnt = 8192;
if (bytecnt > nbytes)
bytecnt = nbytes;
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + bytecnt;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + bytecnt;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
| 166,359 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
Commit Message: Avoid integer overflows in parsing fonts
A malformed TTF can cause size calculations to overflow. This patch
checks the maximum reasonable value so that the total size fits in 32
bits. It also adds some explicit casting to avoid possible technical
undefined behavior when parsing sized unsigned values.
Bug: 25645298
Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616
(cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274)
CWE ID: CWE-19 | static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow
// For all values < kMaxNGroups, kFirstGroupOffset + nGroups * kGroupSize fits in 32 bits.
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
| 173,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ObjectBackedNativeHandler::Router(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> handler_function_value;
v8::Local<v8::Value> feature_name_value;
if (!GetPrivate(context, data, kHandlerFunction, &handler_function_value) ||
handler_function_value->IsUndefined() ||
!GetPrivate(context, data, kFeatureName, &feature_name_value) ||
!feature_name_value->IsString()) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
console::Error(script_context ? script_context->GetRenderFrame() : nullptr,
"Extension view no longer exists");
return;
}
if (content::WorkerThread::GetCurrentId() == 0) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
v8::Local<v8::String> feature_name_string =
feature_name_value->ToString(context).ToLocalChecked();
std::string feature_name = *v8::String::Utf8Value(feature_name_string);
if (script_context &&
!feature_name.empty() &&
!script_context->GetAvailability(feature_name).is_available()) {
return;
}
}
CHECK(handler_function_value->IsExternal());
static_cast<HandlerFunction*>(
handler_function_value.As<v8::External>()->Value())->Run(args);
v8::ReturnValue<v8::Value> ret = args.GetReturnValue();
v8::Local<v8::Value> ret_value = ret.Get();
if (ret_value->IsObject() && !ret_value->IsNull() &&
!ContextCanAccessObject(context, v8::Local<v8::Object>::Cast(ret_value),
true)) {
NOTREACHED() << "Insecure return value";
ret.SetUndefined();
}
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | void ObjectBackedNativeHandler::Router(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> handler_function_value;
v8::Local<v8::Value> feature_name_value;
if (!GetPrivate(context, data, kHandlerFunction, &handler_function_value) ||
handler_function_value->IsUndefined() ||
!GetPrivate(context, data, kFeatureName, &feature_name_value) ||
!feature_name_value->IsString()) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
console::Error(script_context ? script_context->GetRenderFrame() : nullptr,
"Extension view no longer exists");
return;
}
if (content::WorkerThread::GetCurrentId() == 0) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
v8::Local<v8::String> feature_name_string =
feature_name_value->ToString(context).ToLocalChecked();
std::string feature_name = *v8::String::Utf8Value(feature_name_string);
if (script_context && !feature_name.empty()) {
Feature::Availability availability =
script_context->GetAvailability(feature_name);
if (!availability.is_available()) {
DVLOG(1) << feature_name
<< " is not available: " << availability.message();
return;
}
}
}
CHECK(handler_function_value->IsExternal());
static_cast<HandlerFunction*>(
handler_function_value.As<v8::External>()->Value())->Run(args);
v8::ReturnValue<v8::Value> ret = args.GetReturnValue();
v8::Local<v8::Value> ret_value = ret.Get();
if (ret_value->IsObject() && !ret_value->IsNull() &&
!ContextCanAccessObject(context, v8::Local<v8::Object>::Cast(ret_value),
true)) {
NOTREACHED() << "Insecure return value";
ret.SetUndefined();
}
}
| 172,251 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_put_be_3byte (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3)
{ psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_3byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_put_be_3byte (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = (x >> 16) ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = x ;
} /* header_put_be_3byte */
| 170,048 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399 | static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
| 166,599 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CrosLibrary::TestApi::SetSpeechSynthesisLibrary(
SpeechSynthesisLibrary* library, bool own) {
library_->speech_synthesis_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void CrosLibrary::TestApi::SetSpeechSynthesisLibrary(
| 170,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125 | static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps;
++pi->compno, ++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
pi->lyrno < JAS_CAST(int, pchg->lyrnoend);
++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
| 169,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
Commit Message:
CWE ID: CWE-119 | static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
if (size > (R_MAX - R_RX_BUF0 - rxbase) * 4) {
D(qemu_log("ethlite packet is too big, size=%x\n", size));
return -1;
}
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
| 164,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int svc_rdma_xdr_encode_error(struct svcxprt_rdma *xprt,
struct rpcrdma_msg *rmsgp,
enum rpcrdma_errcode err, __be32 *va)
{
__be32 *startp = va;
*va++ = rmsgp->rm_xid;
*va++ = rmsgp->rm_vers;
*va++ = xprt->sc_fc_credits;
*va++ = rdma_error;
*va++ = cpu_to_be32(err);
if (err == ERR_VERS) {
*va++ = rpcrdma_version;
*va++ = rpcrdma_version;
}
return (int)((unsigned long)va - (unsigned long)startp);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | int svc_rdma_xdr_encode_error(struct svcxprt_rdma *xprt,
| 168,160 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
CommandLine* command_line, int child_process_id) {
#if defined(USE_LINUX_BREAKPAD)
if (IsCrashReporterEnabled()) {
command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
child_process_logging::GetClientId() + "," + base::GetLinuxDistro());
}
#elif defined(OS_MACOSX)
if (IsCrashReporterEnabled()) {
command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
child_process_logging::GetClientId());
}
#endif // OS_MACOSX
if (logging::DialogsAreSuppressed())
command_line->AppendSwitch(switches::kNoErrorDialogs);
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
if (process_type == switches::kExtensionProcess ||
process_type == switches::kRendererProcess) {
FilePath user_data_dir =
browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
if (!user_data_dir.empty())
command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
#if defined(OS_CHROMEOS)
const std::string& login_profile =
browser_command_line.GetSwitchValueASCII(switches::kLoginProfile);
if (!login_profile.empty())
command_line->AppendSwitchASCII(switches::kLoginProfile, login_profile);
#endif
RenderProcessHost* process = RenderProcessHost::FromID(child_process_id);
PrefService* prefs = process->profile()->GetPrefs();
if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
prefs->GetBoolean(prefs::kDisable3DAPIs)) {
command_line->AppendSwitch(switches::kDisable3DAPIs);
}
if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
!g_browser_process->safe_browsing_detection_service()) {
command_line->AppendSwitch(switches::kDisableClientSidePhishingDetection);
}
static const char* const kSwitchNames[] = {
switches::kAllowHTTPBackgroundPage,
switches::kAllowScriptingGallery,
switches::kAppsCheckoutURL,
switches::kAppsGalleryURL,
switches::kCloudPrintServiceURL,
switches::kDebugPrint,
#if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) && !defined(OS_MACOSX)
switches::kDisablePrintPreview,
#else
switches::kEnablePrintPreview,
#endif
switches::kDomAutomationController,
switches::kDumpHistogramsOnExit,
switches::kEnableClickToPlay,
switches::kEnableCrxlessWebApps,
switches::kEnableExperimentalExtensionApis,
switches::kEnableInBrowserThumbnailing,
switches::kEnableIPCFuzzing,
switches::kEnableNaCl,
switches::kEnableRemoting,
switches::kEnableResourceContentSettings,
switches::kEnableSearchProviderApiV2,
switches::kEnableWatchdog,
switches::kExperimentalSpellcheckerFeatures,
switches::kMemoryProfiling,
switches::kMessageLoopHistogrammer,
switches::kPpapiFlashArgs,
switches::kPpapiFlashInProcess,
switches::kPpapiFlashPath,
switches::kPpapiFlashVersion,
switches::kProfilingAtStart,
switches::kProfilingFile,
switches::kProfilingFlush,
switches::kRemoteShellPort,
switches::kSilentDumpOnDCHECK,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
} else if (process_type == switches::kUtilityProcess) {
if (browser_command_line.HasSwitch(
switches::kEnableExperimentalExtensionApis)) {
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
} else if (process_type == switches::kPluginProcess) {
static const char* const kSwitchNames[] = {
#if defined(OS_CHROMEOS)
switches::kLoginProfile,
#endif
switches::kMemoryProfiling,
switches::kSilentDumpOnDCHECK,
switches::kUserDataDir,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
} else if (process_type == switches::kZygoteProcess) {
static const char* const kSwitchNames[] = {
switches::kEnableRemoting,
switches::kUserDataDir, // Make logs go to the right file.
switches::kPpapiFlashInProcess,
switches::kPpapiFlashPath,
switches::kPpapiFlashVersion,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
}
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
CommandLine* command_line, int child_process_id) {
#if defined(USE_LINUX_BREAKPAD)
if (IsCrashReporterEnabled()) {
command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
child_process_logging::GetClientId() + "," + base::GetLinuxDistro());
}
#elif defined(OS_MACOSX)
if (IsCrashReporterEnabled()) {
command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
child_process_logging::GetClientId());
}
#endif // OS_MACOSX
if (logging::DialogsAreSuppressed())
command_line->AppendSwitch(switches::kNoErrorDialogs);
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
if (process_type == switches::kExtensionProcess ||
process_type == switches::kRendererProcess) {
FilePath user_data_dir =
browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
if (!user_data_dir.empty())
command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
#if defined(OS_CHROMEOS)
const std::string& login_profile =
browser_command_line.GetSwitchValueASCII(switches::kLoginProfile);
if (!login_profile.empty())
command_line->AppendSwitchASCII(switches::kLoginProfile, login_profile);
#endif
RenderProcessHost* process = RenderProcessHost::FromID(child_process_id);
PrefService* prefs = process->profile()->GetPrefs();
if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
prefs->GetBoolean(prefs::kDisable3DAPIs)) {
command_line->AppendSwitch(switches::kDisable3DAPIs);
}
if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
!g_browser_process->safe_browsing_detection_service()) {
command_line->AppendSwitch(switches::kDisableClientSidePhishingDetection);
}
static const char* const kSwitchNames[] = {
switches::kAllowHTTPBackgroundPage,
switches::kAllowScriptingGallery,
switches::kAppsCheckoutURL,
switches::kAppsGalleryURL,
switches::kCloudPrintServiceURL,
switches::kDebugPrint,
#if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) && !defined(OS_MACOSX)
switches::kDisablePrintPreview,
#else
switches::kEnablePrintPreview,
#endif
switches::kDomAutomationController,
switches::kDumpHistogramsOnExit,
switches::kEnableClickToPlay,
switches::kEnableCrxlessWebApps,
switches::kEnableExperimentalExtensionApis,
switches::kEnableInBrowserThumbnailing,
switches::kEnableIPCFuzzing,
switches::kEnableNaCl,
switches::kEnableRemoting,
switches::kEnableResourceContentSettings,
switches::kEnableSearchProviderApiV2,
switches::kEnableWatchdog,
switches::kExperimentalSpellcheckerFeatures,
switches::kMemoryProfiling,
switches::kMessageLoopHistogrammer,
switches::kPpapiFlashArgs,
switches::kPpapiFlashInProcess,
switches::kPpapiFlashPath,
switches::kPpapiFlashVersion,
switches::kProfilingAtStart,
switches::kProfilingFile,
switches::kProfilingFlush,
switches::kSilentDumpOnDCHECK,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
} else if (process_type == switches::kUtilityProcess) {
if (browser_command_line.HasSwitch(
switches::kEnableExperimentalExtensionApis)) {
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
} else if (process_type == switches::kPluginProcess) {
static const char* const kSwitchNames[] = {
#if defined(OS_CHROMEOS)
switches::kLoginProfile,
#endif
switches::kMemoryProfiling,
switches::kSilentDumpOnDCHECK,
switches::kUserDataDir,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
} else if (process_type == switches::kZygoteProcess) {
static const char* const kSwitchNames[] = {
switches::kEnableRemoting,
switches::kUserDataDir, // Make logs go to the right file.
switches::kPpapiFlashInProcess,
switches::kPpapiFlashPath,
switches::kPpapiFlashVersion,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
}
}
| 170,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
Commit Message: Clear out some minor TODOs.
BUG=none
Review URL: https://codereview.chromium.org/1047063002
Cr-Commit-Position: refs/heads/master@{#322959}
CWE ID: CWE-20 | views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kLightShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
| 171,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB);
std::vector<RTCRtpReceiver*> removed_receivers;
for (auto it = handler_->rtp_receivers_.begin();
it != handler_->rtp_receivers_.end(); ++it) {
if (ReceiverWasRemoved(*(*it), states.transceiver_states))
removed_receivers.push_back(it->get());
}
for (auto& transceiver_state : states.transceiver_states) {
if (ReceiverWasAdded(transceiver_state)) {
handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState());
}
}
for (auto* removed_receiver : removed_receivers) {
handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId(
removed_receiver->state().webrtc_receiver().get()));
}
}
Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl
Bug: 912074
Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8
Reviewed-on: https://chromium-review.googlesource.com/c/1411916
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#622945}
CWE ID: CWE-416 | void ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB);
if (!handler_)
return;
std::vector<RTCRtpReceiver*> removed_receivers;
for (auto it = handler_->rtp_receivers_.begin();
it != handler_->rtp_receivers_.end(); ++it) {
if (ReceiverWasRemoved(*(*it), states.transceiver_states))
removed_receivers.push_back(it->get());
}
for (auto& transceiver_state : states.transceiver_states) {
if (handler_ && ReceiverWasAdded(transceiver_state)) {
// |handler_| can become null after this call.
handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState());
}
}
for (auto* removed_receiver : removed_receivers) {
if (handler_) {
// |handler_| can become null after this call.
handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId(
removed_receiver->state().webrtc_receiver().get()));
}
}
}
| 173,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gplotCreate(const char *rootname,
l_int32 outformat,
const char *title,
const char *xlabel,
const char *ylabel)
{
char *newroot;
char buf[L_BUF_SIZE];
l_int32 badchar;
GPLOT *gplot;
PROCNAME("gplotCreate");
if (!rootname)
return (GPLOT *)ERROR_PTR("rootname not defined", procName, NULL);
if (outformat != GPLOT_PNG && outformat != GPLOT_PS &&
outformat != GPLOT_EPS && outformat != GPLOT_LATEX)
return (GPLOT *)ERROR_PTR("outformat invalid", procName, NULL);
stringCheckForChars(rootname, "`;&|><\"?*", &badchar);
if (badchar) /* danger of command injection */
return (GPLOT *)ERROR_PTR("invalid rootname", procName, NULL);
if ((gplot = (GPLOT *)LEPT_CALLOC(1, sizeof(GPLOT))) == NULL)
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
gplot->cmddata = sarrayCreate(0);
gplot->datanames = sarrayCreate(0);
gplot->plotdata = sarrayCreate(0);
gplot->plottitles = sarrayCreate(0);
gplot->plotstyles = numaCreate(0);
/* Save title, labels, rootname, outformat, cmdname, outname */
newroot = genPathname(rootname, NULL);
gplot->rootname = newroot;
gplot->outformat = outformat;
snprintf(buf, L_BUF_SIZE, "%s.cmd", rootname);
gplot->cmdname = stringNew(buf);
if (outformat == GPLOT_PNG)
snprintf(buf, L_BUF_SIZE, "%s.png", newroot);
else if (outformat == GPLOT_PS)
snprintf(buf, L_BUF_SIZE, "%s.ps", newroot);
else if (outformat == GPLOT_EPS)
snprintf(buf, L_BUF_SIZE, "%s.eps", newroot);
else if (outformat == GPLOT_LATEX)
snprintf(buf, L_BUF_SIZE, "%s.tex", newroot);
gplot->outname = stringNew(buf);
if (title) gplot->title = stringNew(title);
if (xlabel) gplot->xlabel = stringNew(xlabel);
if (ylabel) gplot->ylabel = stringNew(ylabel);
return gplot;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119 | gplotCreate(const char *rootname,
l_int32 outformat,
const char *title,
const char *xlabel,
const char *ylabel)
{
char *newroot;
char buf[L_BUFSIZE];
l_int32 badchar;
GPLOT *gplot;
PROCNAME("gplotCreate");
if (!rootname)
return (GPLOT *)ERROR_PTR("rootname not defined", procName, NULL);
if (outformat != GPLOT_PNG && outformat != GPLOT_PS &&
outformat != GPLOT_EPS && outformat != GPLOT_LATEX)
return (GPLOT *)ERROR_PTR("outformat invalid", procName, NULL);
stringCheckForChars(rootname, "`;&|><\"?*", &badchar);
if (badchar) /* danger of command injection */
return (GPLOT *)ERROR_PTR("invalid rootname", procName, NULL);
if ((gplot = (GPLOT *)LEPT_CALLOC(1, sizeof(GPLOT))) == NULL)
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
gplot->cmddata = sarrayCreate(0);
gplot->datanames = sarrayCreate(0);
gplot->plotdata = sarrayCreate(0);
gplot->plottitles = sarrayCreate(0);
gplot->plotstyles = numaCreate(0);
/* Save title, labels, rootname, outformat, cmdname, outname */
newroot = genPathname(rootname, NULL);
gplot->rootname = newroot;
gplot->outformat = outformat;
snprintf(buf, L_BUFSIZE, "%s.cmd", rootname);
gplot->cmdname = stringNew(buf);
if (outformat == GPLOT_PNG)
snprintf(buf, L_BUFSIZE, "%s.png", newroot);
else if (outformat == GPLOT_PS)
snprintf(buf, L_BUFSIZE, "%s.ps", newroot);
else if (outformat == GPLOT_EPS)
snprintf(buf, L_BUFSIZE, "%s.eps", newroot);
else if (outformat == GPLOT_LATEX)
snprintf(buf, L_BUFSIZE, "%s.tex", newroot);
gplot->outname = stringNew(buf);
if (title) gplot->title = stringNew(title);
if (xlabel) gplot->xlabel = stringNew(xlabel);
if (ylabel) gplot->ylabel = stringNew(ylabel);
return gplot;
}
| 169,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
Commit Message: Add bounds check before length read
CWE ID: CWE-125 | static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
| 169,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_hunkmax (void)
{
if (!p_line)
p_line = (char **) malloc (hunkmax * sizeof *p_line);
if (!p_len)
p_len = (size_t *) malloc (hunkmax * sizeof *p_len);
if (!p_Char)
p_Char = malloc (hunkmax * sizeof *p_Char);
}
Commit Message:
CWE ID: CWE-399 | set_hunkmax (void)
{
if (!p_line)
p_line = (char **) xmalloc (hunkmax * sizeof *p_line);
if (!p_len)
p_len = (size_t *) xmalloc (hunkmax * sizeof *p_len);
if (!p_Char)
p_Char = xmalloc (hunkmax * sizeof *p_Char);
}
| 165,401 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InProcessBrowserTest::InProcessBrowserTest()
: browser_(NULL),
exit_when_last_browser_closes_(true),
multi_desktop_test_(false)
#if defined(OS_MACOSX)
, autorelease_pool_(NULL)
#endif // OS_MACOSX
{
#if defined(OS_MACOSX)
base::FilePath chrome_path;
CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
chrome_path = chrome_path.DirName();
chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
CHECK(PathService::Override(base::FILE_EXE, chrome_path));
#endif // defined(OS_MACOSX)
CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
base::FilePath src_dir;
CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir));
base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data");
embedded_test_server()->ServeFilesFromDirectory(test_data_dir);
CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir));
}
Commit Message: Make the policy fetch for first time login blocking
The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users.
BUG=334584
Review URL: https://codereview.chromium.org/330843002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | InProcessBrowserTest::InProcessBrowserTest()
: browser_(NULL),
exit_when_last_browser_closes_(true),
open_about_blank_on_browser_launch_(true),
multi_desktop_test_(false)
#if defined(OS_MACOSX)
, autorelease_pool_(NULL)
#endif // OS_MACOSX
{
#if defined(OS_MACOSX)
base::FilePath chrome_path;
CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
chrome_path = chrome_path.DirName();
chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
CHECK(PathService::Override(base::FILE_EXE, chrome_path));
#endif // defined(OS_MACOSX)
CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
base::FilePath src_dir;
CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir));
base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data");
embedded_test_server()->ServeFilesFromDirectory(test_data_dir);
CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir));
}
| 171,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vp8_remove_decoder_instances(struct frame_buffers *fb)
{
if(!fb->use_frame_threads)
{
VP8D_COMP *pbi = fb->pbi[0];
if (!pbi)
return VPX_CODEC_ERROR;
#if CONFIG_MULTITHREAD
if (pbi->b_multithreaded_rd)
vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows);
vp8_decoder_remove_threads(pbi);
#endif
/* decoder instance for single thread mode */
remove_decompressor(pbi);
}
else
{
/* TODO : remove frame threads and decoder instances for each
* thread here */
}
return VPX_CODEC_OK;
}
Commit Message: vp8:fix threading issues
1 - stops de allocating before threads are closed.
2 - limits threads to mb_rows when mb_rows < partitions
BUG=webm:851
Bug: 30436808
Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b
(cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e)
CWE ID: | int vp8_remove_decoder_instances(struct frame_buffers *fb)
{
if(!fb->use_frame_threads)
{
VP8D_COMP *pbi = fb->pbi[0];
if (!pbi)
return VPX_CODEC_ERROR;
#if CONFIG_MULTITHREAD
vp8_decoder_remove_threads(pbi);
#endif
/* decoder instance for single thread mode */
remove_decompressor(pbi);
}
else
{
/* TODO : remove frame threads and decoder instances for each
* thread here */
}
return VPX_CODEC_OK;
}
| 174,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(openssl_random_pseudo_bytes)
{
long buffer_length;
unsigned char *buffer = NULL;
zval *zstrong_result_returned = NULL;
int strong_result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) {
return;
return;
}
if (buffer_length <= 0) {
RETURN_FALSE;
}
if (zstrong_result_returned) {
zval_dtor(zstrong_result_returned);
ZVAL_BOOL(zstrong_result_returned, 0);
}
buffer = emalloc(buffer_length + 1);
#ifdef PHP_WIN32
strong_result = 1;
/* random/urandom equivalent on Windows */
if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {
efree(buffer);
if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {
efree(buffer);
if (zstrong_result_returned) {
RETURN_FALSE;
}
#else
if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) {
efree(buffer);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 0);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 0);
}
RETURN_FALSE;
}
#endif
RETVAL_STRINGL((char *)buffer, buffer_length, 0);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, strong_result);
}
}
/* }}} */
Commit Message:
CWE ID: CWE-310 | PHP_FUNCTION(openssl_random_pseudo_bytes)
{
long buffer_length;
unsigned char *buffer = NULL;
zval *zstrong_result_returned = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) {
return;
return;
}
if (buffer_length <= 0) {
RETURN_FALSE;
}
if (zstrong_result_returned) {
zval_dtor(zstrong_result_returned);
ZVAL_BOOL(zstrong_result_returned, 0);
}
buffer = emalloc(buffer_length + 1);
#ifdef PHP_WIN32
/* random/urandom equivalent on Windows */
if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {
efree(buffer);
if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {
efree(buffer);
if (zstrong_result_returned) {
RETURN_FALSE;
}
#else
if (RAND_bytes(buffer, buffer_length) <= 0) {
efree(buffer);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 0);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 0);
}
RETURN_FALSE;
}
#endif
RETVAL_STRINGL((char *)buffer, buffer_length, 0);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 1);
}
}
/* }}} */
| 165,272 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const AXObject* AXObject::ariaHiddenRoot() const {
for (const AXObject* object = this; object; object = object->parentObject()) {
if (equalIgnoringCase(object->getAttribute(aria_hiddenAttr), "true"))
return object;
}
return 0;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | const AXObject* AXObject::ariaHiddenRoot() const {
for (const AXObject* object = this; object; object = object->parentObject()) {
if (equalIgnoringASCIICase(object->getAttribute(aria_hiddenAttr), "true"))
return object;
}
return 0;
}
| 171,923 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: load_fake(png_charp param, png_bytepp profile)
{
char *endptr = NULL;
unsigned long long int size = strtoull(param, &endptr, 0/*base*/);
/* The 'fake' format is <number>*[string] */
if (endptr != NULL && *endptr == '*')
{
size_t len = strlen(++endptr);
size_t result = (size_t)size;
if (len == 0) len = 1; /* capture the terminating '\0' */
/* Now repeat that string to fill 'size' bytes. */
if (result == size && (*profile = malloc(result)) != NULL)
{
png_bytep out = *profile;
if (len == 1)
memset(out, *endptr, result);
else
{
while (size >= len)
{
memcpy(out, endptr, len);
out += len;
size -= len;
}
memcpy(out, endptr, size);
}
return result;
}
else
{
fprintf(stderr, "%s: size exceeds system limits\n", param);
exit(1);
}
}
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | load_fake(png_charp param, png_bytepp profile)
{
char *endptr = NULL;
uint64_t size = strtoull(param, &endptr, 0/*base*/);
/* The 'fake' format is <number>*[string] */
if (endptr != NULL && *endptr == '*')
{
size_t len = strlen(++endptr);
size_t result = (size_t)size;
if (len == 0) len = 1; /* capture the terminating '\0' */
/* Now repeat that string to fill 'size' bytes. */
if (result == size && (*profile = malloc(result)) != NULL)
{
png_bytep out = *profile;
if (len == 1)
memset(out, *endptr, result);
else
{
while (size >= len)
{
memcpy(out, endptr, len);
out += len;
size -= len;
}
memcpy(out, endptr, size);
}
return result;
}
else
{
fprintf(stderr, "%s: size exceeds system limits\n", param);
exit(1);
}
}
return 0;
}
| 173,583 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int GetFreeFrameBuffer(size_t min_size, vpx_codec_frame_buffer_t *fb) {
EXPECT_TRUE(fb != NULL);
const int idx = FindFreeBufferIndex();
if (idx == num_buffers_)
return -1;
if (ext_fb_list_[idx].size < min_size) {
delete [] ext_fb_list_[idx].data;
ext_fb_list_[idx].data = new uint8_t[min_size];
ext_fb_list_[idx].size = min_size;
}
SetFrameBuffer(idx, fb);
return 0;
}
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 | int GetFreeFrameBuffer(size_t min_size, vpx_codec_frame_buffer_t *fb) {
EXPECT_TRUE(fb != NULL);
const int idx = FindFreeBufferIndex();
if (idx == num_buffers_)
return -1;
if (ext_fb_list_[idx].size < min_size) {
delete [] ext_fb_list_[idx].data;
ext_fb_list_[idx].data = new uint8_t[min_size];
memset(ext_fb_list_[idx].data, 0, min_size);
ext_fb_list_[idx].size = min_size;
}
SetFrameBuffer(idx, fb);
return 0;
}
| 174,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xps_select_font_encoding(xps_font_t *font, int idx)
{
byte *cmapdata, *entry;
int pid, eid;
if (idx < 0 || idx >= font->cmapsubcount)
return;
cmapdata = font->data + font->cmaptable;
entry = cmapdata + 4 + idx * 8;
pid = u16(entry + 0);
eid = u16(entry + 2);
font->cmapsubtable = font->cmaptable + u32(entry + 4);
font->usepua = (pid == 3 && eid == 0);
}
Commit Message:
CWE ID: CWE-125 | xps_select_font_encoding(xps_font_t *font, int idx)
{
byte *cmapdata, *entry;
int pid, eid;
if (idx < 0 || idx >= font->cmapsubcount)
return 0;
cmapdata = font->data + font->cmaptable;
entry = cmapdata + 4 + idx * 8;
pid = u16(entry + 0);
eid = u16(entry + 2);
font->cmapsubtable = font->cmaptable + u32(entry + 4);
if (font->cmapsubtable >= font->length) {
font->cmapsubtable = 0;
return 0;
}
font->usepua = (pid == 3 && eid == 0);
return 1;
}
| 164,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
}
| 170,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PreconnectedRequestStats::PreconnectedRequestStats(const GURL& origin,
bool was_preconnected)
: origin(origin),
was_preconnected(was_preconnected) {}
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 | PreconnectedRequestStats::PreconnectedRequestStats(const GURL& origin,
PreconnectedRequestStats::PreconnectedRequestStats(const url::Origin& origin,
bool was_preconnected)
| 172,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DoCheckFakeData(uint8* audio_data, size_t length) {
Type* output = reinterpret_cast<Type*>(audio_data);
for (size_t i = 0; i < length; i++) {
EXPECT_TRUE(algorithm_.is_muted() || output[i] != 0);
}
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void DoCheckFakeData(uint8* audio_data, size_t length) {
if (algorithm_.is_muted())
ASSERT_EQ(sum, 0);
else
ASSERT_NE(sum, 0);
}
| 171,531 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
m_exceptionCode = AbortError;
abortError();
return;
}
if (error.isTimeout()) {
didTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
m_exceptionCode = NetworkError;
networkError();
}
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
handleDidCancel();
return;
}
if (error.isTimeout()) {
handleDidTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
handleNetworkError();
}
| 171,165 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataRootDirectory::GDataRootDirectory()
: ALLOW_THIS_IN_INITIALIZER_LIST(GDataDirectory(NULL, this)),
fake_search_directory_(new GDataDirectory(NULL, NULL)),
largest_changestamp_(0), serialized_size_(0) {
title_ = kGDataRootDirectory;
SetFileNameFromTitle();
}
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: | GDataRootDirectory::GDataRootDirectory()
: ALLOW_THIS_IN_INITIALIZER_LIST(GDataDirectory(NULL, this)),
fake_search_directory_(new GDataDirectory(NULL, NULL)),
largest_changestamp_(0), serialized_size_(0) {
title_ = kGDataRootDirectory;
SetFileNameFromTitle();
resource_id_ = kGDataRootDirectoryResourceId;
// Add self to the map so the root directory can be looked up by the
// resource ID.
AddEntryToResourceMap(this);
}
| 170,777 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
return htonl(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
id = __ipv6_select_ident(net, &addrs[1], &addrs[0]);
return htonl(id);
}
| 169,718 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Initialize() {
Initialize(kDefaultChannelLayout, kDefaultSampleBits);
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void Initialize() {
Initialize(kDefaultChannelLayout, kDefaultSampleBits, kSamplesPerSecond);
}
| 171,533 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap)
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
else
cp = ikev1_attr_print(ndo, cp, ep2);
if (cp == NULL)
goto trunc;
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
| 167,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ext4_get_block_write(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
handle_t *handle = NULL;
int ret = 0;
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
int dio_credits;
ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
inode->i_ino, create);
/*
* ext4_get_block in prepare for a DIO write or buffer write.
* We allocate an uinitialized extent if blocks haven't been allocated.
* The extent will be converted to initialized after IO complete.
*/
create = EXT4_GET_BLOCKS_IO_CREATE_EXT;
if (max_blocks > DIO_MAX_BLOCKS)
max_blocks = DIO_MAX_BLOCKS;
dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
handle = ext4_journal_start(inode, dio_credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
create);
if (ret > 0) {
bh_result->b_size = (ret << inode->i_blkbits);
ret = 0;
}
ext4_journal_stop(handle);
out:
return ret;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static int ext4_get_block_write(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
handle_t *handle = ext4_journal_current_handle();
int ret = 0;
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
int dio_credits;
int started = 0;
ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
inode->i_ino, create);
/*
* ext4_get_block in prepare for a DIO write or buffer write.
* We allocate an uinitialized extent if blocks haven't been allocated.
* The extent will be converted to initialized after IO complete.
*/
create = EXT4_GET_BLOCKS_IO_CREATE_EXT;
if (!handle) {
if (max_blocks > DIO_MAX_BLOCKS)
max_blocks = DIO_MAX_BLOCKS;
dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
handle = ext4_journal_start(inode, dio_credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
started = 1;
}
ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
create);
if (ret > 0) {
bh_result->b_size = (ret << inode->i_blkbits);
ret = 0;
}
if (started)
ext4_journal_stop(handle);
out:
return ret;
}
| 167,545 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
renderer_process_(base::kNullProcessHandle),
renderer_pid_(base::kNullProcessId),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
| 170,931 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GaiaOAuthClient::Core::OnUserInfoFetchComplete(
const net::URLRequestStatus& status,
int response_code,
const std::string& response) {
std::string email;
if (response_code == net::HTTP_OK) {
scoped_ptr<Value> message_value(base::JSONReader::Read(response));
if (message_value.get() &&
message_value->IsType(Value::TYPE_DICTIONARY)) {
scoped_ptr<DictionaryValue> response_dict(
static_cast<DictionaryValue*>(message_value.release()));
response_dict->GetString(kEmailValue, &email);
}
}
if (email.empty()) {
delegate_->OnNetworkError(response_code);
} else {
delegate_->OnRefreshTokenResponse(
email, access_token_, expires_in_seconds_);
}
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GaiaOAuthClient::Core::OnUserInfoFetchComplete(
const net::URLRequestStatus& status,
int response_code,
const std::string& response) {
request_.reset();
url_fetcher_type_ = URL_FETCHER_NONE;
std::string email;
if (response_code == net::HTTP_OK) {
scoped_ptr<Value> message_value(base::JSONReader::Read(response));
if (message_value.get() &&
message_value->IsType(Value::TYPE_DICTIONARY)) {
scoped_ptr<DictionaryValue> response_dict(
static_cast<DictionaryValue*>(message_value.release()));
response_dict->GetString(kEmailValue, &email);
}
}
if (email.empty()) {
delegate_->OnNetworkError(response_code);
} else {
delegate_->OnRefreshTokenResponse(
email, access_token_, expires_in_seconds_);
}
}
| 170,808 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SoftAACEncoder2::~SoftAACEncoder2() {
aacEncClose(&mAACEncoder);
delete[] mInputFrame;
mInputFrame = NULL;
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID: | SoftAACEncoder2::~SoftAACEncoder2() {
aacEncClose(&mAACEncoder);
onReset();
}
| 174,009 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: l2tp_accm_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
ptr++; /* skip "Reserved" */
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "send=%08x ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "recv=%08x ", (val_h<<16) + val_l));
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l2tp_accm_print(netdissect_options *ndo, const u_char *dat)
l2tp_accm_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
if (length < 2) {
ND_PRINT((ndo, "AVP too short"));
return;
}
ptr++; /* skip "Reserved" */
length -= 2;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2;
val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2;
ND_PRINT((ndo, "send=%08x ", (val_h<<16) + val_l));
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "recv=%08x ", (val_h<<16) + val_l));
}
| 167,889 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init ipip_init(void)
{
int err;
printk(banner);
if (xfrm4_tunnel_register(&ipip_handler, AF_INET)) {
printk(KERN_INFO "ipip init: can't register tunnel\n");
return -EAGAIN;
}
err = register_pernet_device(&ipip_net_ops);
if (err)
xfrm4_tunnel_deregister(&ipip_handler, AF_INET);
return err;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int __init ipip_init(void)
{
int err;
printk(banner);
err = register_pernet_device(&ipip_net_ops);
if (err < 0)
return err;
err = xfrm4_tunnel_register(&ipip_handler, AF_INET);
if (err < 0) {
unregister_pernet_device(&ipip_net_ops);
printk(KERN_INFO "ipip init: can't register tunnel\n");
}
return err;
}
| 165,876 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
re_yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
re_yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476 | int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
re_yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
re_yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
| 168,485 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mct_u232_port_probe(struct usb_serial_port *port)
{
struct mct_u232_private *priv;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* Use second interrupt-in endpoint for reading. */
priv->read_urb = port->serial->port[1]->interrupt_in_urb;
priv->read_urb->context = port;
spin_lock_init(&priv->lock);
usb_set_serial_port_data(port, priv);
return 0;
}
Commit Message: USB: mct_u232: add sanity checking in probe
An attack using the lack of sanity checking in probe is known. This
patch checks for the existence of a second port.
CVE-2016-3136
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
[johan: add error message ]
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int mct_u232_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct mct_u232_private *priv;
/* check first to simplify error handling */
if (!serial->port[1] || !serial->port[1]->interrupt_in_urb) {
dev_err(&port->dev, "expected endpoint missing\n");
return -ENODEV;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* Use second interrupt-in endpoint for reading. */
priv->read_urb = serial->port[1]->interrupt_in_urb;
priv->read_urb->context = port;
spin_lock_init(&priv->lock);
usb_set_serial_port_data(port, priv);
return 0;
}
| 167,361 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c ) {
newitem->string = cJSON_strdup( string );
cJSON_ReplaceItemInArray( object, i, newitem );
}
}
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 | void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem )
| 167,296 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
GError *error = NULL;
Buffer *buffer;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (!side->closed)
{
if (!side->got_first_byte)
buffer = buffer_new (1, NULL);
else if (!client->authenticated)
buffer = buffer_new (64, NULL);
else
buffer = side->current_read_buffer;
if (!buffer_read (side, buffer, socket))
{
if (buffer != side->current_read_buffer)
buffer_unref (buffer);
break;
}
if (!client->authenticated)
{
if (buffer->pos > 0)
{
gboolean found_auth_end = FALSE;
gsize extra_data;
buffer->size = buffer->pos;
if (!side->got_first_byte)
{
buffer->send_credentials = TRUE;
side->got_first_byte = TRUE;
}
/* Look for end of authentication mechanism */
else if (side == &client->client_side)
{
gssize auth_end = find_auth_end (client, buffer);
if (auth_end >= 0)
{
found_auth_end = TRUE;
buffer->size = auth_end;
extra_data = buffer->pos - buffer->size;
/* We may have gotten some extra data which is not part of
the auth handshake, keep it for the next iteration. */
if (extra_data > 0)
side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
}
}
got_buffer_from_side (side, buffer);
if (found_auth_end)
client->authenticated = TRUE;
}
else
{
buffer_unref (buffer);
}
}
else if (buffer->pos == buffer->size)
{
if (buffer == &side->header_buffer)
{
gssize required;
required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
if (required < 0)
{
g_warning ("Invalid message header read");
side_closed (side);
}
else
{
side->current_read_buffer = buffer_new (required, buffer);
}
}
else
{
got_buffer_from_side (side, buffer);
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
}
}
}
if (side->closed)
{
side->in_source = NULL;
retval = G_SOURCE_REMOVE;
}
g_object_unref (client);
return retval;
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436 | side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
GError *error = NULL;
Buffer *buffer;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (!side->closed)
{
if (!side->got_first_byte)
buffer = buffer_new (1, NULL);
else if (!client->authenticated)
buffer = buffer_new (64, NULL);
else
buffer = side->current_read_buffer;
if (!buffer_read (side, buffer, socket))
{
if (buffer != side->current_read_buffer)
buffer_unref (buffer);
break;
}
if (!client->authenticated)
{
if (buffer->pos > 0)
{
gboolean found_auth_end = FALSE;
gsize extra_data;
buffer->size = buffer->pos;
if (!side->got_first_byte)
{
buffer->send_credentials = TRUE;
side->got_first_byte = TRUE;
}
/* Look for end of authentication mechanism */
else if (side == &client->client_side)
{
gssize auth_end = find_auth_end (client, buffer);
if (auth_end >= 0)
{
found_auth_end = TRUE;
buffer->size = auth_end;
extra_data = buffer->pos - buffer->size;
/* We may have gotten some extra data which is not part of
the auth handshake, keep it for the next iteration. */
if (extra_data > 0)
side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
}
else if (auth_end == FIND_AUTH_END_ABORT)
{
buffer_unref (buffer);
if (client->proxy->log_messages)
g_print ("Invalid AUTH line, aborting\n");
side_closed (side);
break;
}
}
got_buffer_from_side (side, buffer);
if (found_auth_end)
client->authenticated = TRUE;
}
else
{
buffer_unref (buffer);
}
}
else if (buffer->pos == buffer->size)
{
if (buffer == &side->header_buffer)
{
gssize required;
required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
if (required < 0)
{
g_warning ("Invalid message header read");
side_closed (side);
}
else
{
side->current_read_buffer = buffer_new (required, buffer);
}
}
else
{
got_buffer_from_side (side, buffer);
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
}
}
}
if (side->closed)
{
side->in_source = NULL;
retval = G_SOURCE_REMOVE;
}
g_object_unref (client);
return retval;
}
| 169,343 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_image_compose_unopt(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
int i, j;
int sw = src->width;
int sh = src->height;
int sx = 0;
int sy = 0;
/* clip to the dst image boundaries */
if (x < 0) {
sx += -x;
sw -= -x;
x = 0;
}
if (y < 0) {
sy += -y;
sh -= -y;
y = 0;
}
if (x + sw >= dst->width)
sw = dst->width - x;
if (y + sh >= dst->height)
sh = dst->height - y;
switch (op) {
case JBIG2_COMPOSE_OR:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) | jbig2_image_get_pixel(dst, i + x, j + y));
}
}
break;
case JBIG2_COMPOSE_AND:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) & jbig2_image_get_pixel(dst, i + x, j + y));
}
}
break;
case JBIG2_COMPOSE_XOR:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) ^ jbig2_image_get_pixel(dst, i + x, j + y));
}
}
break;
case JBIG2_COMPOSE_XNOR:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, (jbig2_image_get_pixel(src, i + sx, j + sy) == jbig2_image_get_pixel(dst, i + x, j + y)));
}
}
break;
case JBIG2_COMPOSE_REPLACE:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy));
}
}
break;
}
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_image_compose_unopt(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
uint32_t i, j;
uint32_t sw = src->width;
uint32_t sh = src->height;
uint32_t sx = 0;
uint32_t sy = 0;
/* clip to the dst image boundaries */
if (x < 0) {
sx += -x;
sw -= -x;
x = 0;
}
if (y < 0) {
sy += -y;
sh -= -y;
y = 0;
}
if (x + sw >= dst->width)
sw = dst->width - x;
if (y + sh >= dst->height)
sh = dst->height - y;
switch (op) {
case JBIG2_COMPOSE_OR:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) | jbig2_image_get_pixel(dst, i + x, j + y));
}
}
break;
case JBIG2_COMPOSE_AND:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) & jbig2_image_get_pixel(dst, i + x, j + y));
}
}
break;
case JBIG2_COMPOSE_XOR:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) ^ jbig2_image_get_pixel(dst, i + x, j + y));
}
}
break;
case JBIG2_COMPOSE_XNOR:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, (jbig2_image_get_pixel(src, i + sx, j + sy) == jbig2_image_get_pixel(dst, i + x, j + y)));
}
}
break;
case JBIG2_COMPOSE_REPLACE:
for (j = 0; j < sh; j++) {
for (i = 0; i < sw; i++) {
jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy));
}
}
break;
}
return 0;
}
| 165,490 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AcceleratedStaticBitmapImage::Transfer() {
CheckThread();
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
detach_thread_at_next_check_ = true;
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void AcceleratedStaticBitmapImage::Transfer() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
DETACH_FROM_THREAD(thread_checker_);
}
| 172,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline ogg_uint32_t decode_packed_entry_number(codebook *book,
oggpack_buffer *b){
ogg_uint32_t chase=0;
int read=book->dec_maxlength;
long lok = oggpack_look(b,read),i;
while(lok<0 && read>1)
lok = oggpack_look(b, --read);
if(lok<0){
oggpack_adv(b,1); /* force eop */
return -1;
}
/* chase the tree with the bits we got */
switch (book->dec_method)
{
case 0:
{
/* book->dec_nodeb==1, book->dec_leafw==1 */
/* 8/8 - Used */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
chase=t[chase*2+((lok>>i)&1)];
if(chase&0x80UL)break;
}
chase&=0x7fUL;
break;
}
case 1:
{
/* book->dec_nodeb==1, book->dec_leafw!=1 */
/* 8/16 - Used by infile2 */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x80){
chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)];
break;
}
chase=next;
}
chase&=~0x8000UL;
break;
}
case 2:
{
/* book->dec_nodeb==2, book->dec_leafw==1 */
/* 16/16 - Used */
for(i=0;i<read;i++){
chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x8000UL)break;
}
chase&=~0x8000UL;
break;
}
case 3:
{
/* book->dec_nodeb==2, book->dec_leafw!=1 */
/* 16/32 - Used by infile2 */
ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x8000){
chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)];
break;
}
chase=next;
}
chase&=~0x80000000UL;
break;
}
case 4:
{
for(i=0;i<read;i++){
chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x80000000UL)break;
}
chase&=~0x80000000UL;
break;
}
}
if(i<read){
oggpack_adv(b,i+1);
return chase;
}
oggpack_adv(b,read+1);
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 | static inline ogg_uint32_t decode_packed_entry_number(codebook *book,
oggpack_buffer *b){
ogg_uint32_t chase=0;
int read=book->dec_maxlength;
long lok = oggpack_look(b,read),i;
while(lok<0 && read>1)
lok = oggpack_look(b, --read);
if(lok<0){
oggpack_adv(b,1); /* force eop */
return -1;
}
/* chase the tree with the bits we got */
switch (book->dec_method)
{
case 0:
{
/* book->dec_nodeb==1, book->dec_leafw==1 */
/* 8/8 - Used */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
chase=t[chase*2+((lok>>i)&1)];
if(chase&0x80UL)break;
}
chase&=0x7fUL;
break;
}
case 1:
{
/* book->dec_nodeb==1, book->dec_leafw!=1 */
/* 8/16 - Used by infile2 */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x80){
chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)];
break;
}
chase=next;
}
chase&=~0x8000UL;
break;
}
case 2:
{
/* book->dec_nodeb==2, book->dec_leafw==1 */
/* 16/16 - Used */
for(i=0;i<read;i++){
chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x8000UL)break;
}
chase&=~0x8000UL;
break;
}
case 3:
{
/* book->dec_nodeb==2, book->dec_leafw!=1 */
/* 16/32 - Used by infile2 */
ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x8000){
chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)];
break;
}
chase=next;
}
chase&=~0x80000000UL;
break;
}
case 4:
{
for(i=0;i<read;i++){
chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x80000000UL)break;
}
chase&=~0x80000000UL;
break;
}
}
if(i<read){
oggpack_adv(b,i+1);
return chase;
}
oggpack_adv(b,read+1);
return(-1);
}
| 173,984 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppControllerImpl::SetClient(mojom::AppControllerClientPtr client) {
client_ = std::move(client);
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void AppControllerImpl::SetClient(mojom::AppControllerClientPtr client) {
void AppControllerService::SetClient(mojom::AppControllerClientPtr client) {
client_ = std::move(client);
}
| 172,088 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ContentSecurityPolicy::postViolationReport(
const SecurityPolicyViolationEventInit& violationData,
LocalFrame* contextFrame,
const Vector<String>& reportEndpoints) {
Document* document =
contextFrame ? contextFrame->document() : this->document();
if (!document)
return;
std::unique_ptr<JSONObject> cspReport = JSONObject::create();
cspReport->setString("document-uri", violationData.documentURI());
cspReport->setString("referrer", violationData.referrer());
cspReport->setString("violated-directive", violationData.violatedDirective());
cspReport->setString("effective-directive",
violationData.effectiveDirective());
cspReport->setString("original-policy", violationData.originalPolicy());
cspReport->setString("disposition", violationData.disposition());
cspReport->setString("blocked-uri", violationData.blockedURI());
if (violationData.lineNumber())
cspReport->setInteger("line-number", violationData.lineNumber());
if (violationData.columnNumber())
cspReport->setInteger("column-number", violationData.columnNumber());
if (!violationData.sourceFile().isEmpty())
cspReport->setString("source-file", violationData.sourceFile());
cspReport->setInteger("status-code", violationData.statusCode());
if (experimentalFeaturesEnabled())
cspReport->setString("sample", violationData.sample());
std::unique_ptr<JSONObject> reportObject = JSONObject::create();
reportObject->setObject("csp-report", std::move(cspReport));
String stringifiedReport = reportObject->toJSONString();
if (shouldSendViolationReport(stringifiedReport)) {
didSendViolationReport(stringifiedReport);
RefPtr<EncodedFormData> report =
EncodedFormData::create(stringifiedReport.utf8());
LocalFrame* frame = document->frame();
if (!frame)
return;
for (const String& endpoint : reportEndpoints) {
DCHECK(!contextFrame || !m_executionContext);
DCHECK(!contextFrame ||
getDirectiveType(violationData.effectiveDirective()) ==
DirectiveType::FrameAncestors);
KURL url =
contextFrame
? frame->document()->completeURLWithOverride(
endpoint, KURL(ParsedURLString, violationData.blockedURI()))
: completeURL(endpoint);
PingLoader::sendViolationReport(
frame, url, report, PingLoader::ContentSecurityPolicyViolationReport);
}
}
}
Commit Message: CSP: Strip the fragment from reported URLs.
We should have been stripping the fragment from the URL we report for
CSP violations, but we weren't. Now we are, by running the URLs through
`stripURLForUseInReport()`, which implements the stripping algorithm
from CSP2: https://www.w3.org/TR/CSP2/#strip-uri-for-reporting
Eventually, we will migrate more completely to the CSP3 world that
doesn't require such detailed stripping, as it exposes less data to the
reports, but we're not there yet.
BUG=678776
Review-Url: https://codereview.chromium.org/2619783002
Cr-Commit-Position: refs/heads/master@{#458045}
CWE ID: CWE-200 | void ContentSecurityPolicy::postViolationReport(
const SecurityPolicyViolationEventInit& violationData,
LocalFrame* contextFrame,
const Vector<String>& reportEndpoints) {
Document* document =
contextFrame ? contextFrame->document() : this->document();
if (!document)
return;
//
// TODO(mkwst): This justification is BS. Insecure reports are mixed content,
// let's kill them. https://crbug.com/695363
std::unique_ptr<JSONObject> cspReport = JSONObject::create();
cspReport->setString("document-uri", violationData.documentURI());
cspReport->setString("referrer", violationData.referrer());
cspReport->setString("violated-directive", violationData.violatedDirective());
cspReport->setString("effective-directive",
violationData.effectiveDirective());
cspReport->setString("original-policy", violationData.originalPolicy());
cspReport->setString("disposition", violationData.disposition());
cspReport->setString("blocked-uri", violationData.blockedURI());
if (violationData.lineNumber())
cspReport->setInteger("line-number", violationData.lineNumber());
if (violationData.columnNumber())
cspReport->setInteger("column-number", violationData.columnNumber());
if (!violationData.sourceFile().isEmpty())
cspReport->setString("source-file", violationData.sourceFile());
cspReport->setInteger("status-code", violationData.statusCode());
if (experimentalFeaturesEnabled())
cspReport->setString("sample", violationData.sample());
std::unique_ptr<JSONObject> reportObject = JSONObject::create();
reportObject->setObject("csp-report", std::move(cspReport));
String stringifiedReport = reportObject->toJSONString();
if (shouldSendViolationReport(stringifiedReport)) {
didSendViolationReport(stringifiedReport);
RefPtr<EncodedFormData> report =
EncodedFormData::create(stringifiedReport.utf8());
LocalFrame* frame = document->frame();
if (!frame)
return;
for (const String& endpoint : reportEndpoints) {
DCHECK(!contextFrame || !m_executionContext);
DCHECK(!contextFrame ||
getDirectiveType(violationData.effectiveDirective()) ==
DirectiveType::FrameAncestors);
KURL url =
contextFrame
? frame->document()->completeURLWithOverride(
endpoint, KURL(ParsedURLString, violationData.blockedURI()))
: completeURL(endpoint);
PingLoader::sendViolationReport(
frame, url, report, PingLoader::ContentSecurityPolicyViolationReport);
}
}
}
| 172,362 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void cliRefreshPrompt(void) {
int len;
if (config.eval_ldb) return;
if (config.hostsocket != NULL)
len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
config.hostsocket);
else
len = anetFormatAddr(config.prompt, sizeof(config.prompt),
config.hostip, config.hostport);
/* Add [dbnum] if needed */
if (config.dbnum != 0)
len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
config.dbnum);
snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
}
Commit Message: Security: fix redis-cli buffer overflow.
Thanks to Fakhri Zulkifli for reporting it.
The fix switched to dynamic allocation, copying the final prompt in the
static buffer only at the end.
CWE ID: CWE-119 | static void cliRefreshPrompt(void) {
if (config.eval_ldb) return;
sds prompt = sdsempty();
if (config.hostsocket != NULL) {
prompt = sdscatfmt(prompt,"redis %s",config.hostsocket);
} else {
char addr[256];
anetFormatAddr(addr, sizeof(addr), config.hostip, config.hostport);
prompt = sdscatlen(prompt,addr,strlen(addr));
}
/* Add [dbnum] if needed */
if (config.dbnum != 0)
prompt = sdscatfmt(prompt,"[%i]",config.dbnum);
/* Copy the prompt in the static buffer. */
prompt = sdscatlen(prompt,"> ",2);
snprintf(config.prompt,sizeof(config.prompt),"%s",prompt);
sdsfree(prompt);
}
| 169,196 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_krb5int_export_lucid_sec_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_error_code kret = 0;
OM_uint32 retval;
krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle;
void *lctx = NULL;
int version = 0;
gss_buffer_desc rep;
/* Assume failure */
retval = GSS_S_FAILURE;
*minor_status = 0;
*data_set = GSS_C_NO_BUFFER_SET;
retval = generic_gss_oid_decompose(minor_status,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH,
desired_object,
&version);
if (GSS_ERROR(retval))
return retval;
/* Externalize a structure of the right version */
switch (version) {
case 1:
kret = make_external_lucid_ctx_v1((krb5_pointer)ctx,
version, &lctx);
break;
default:
kret = (OM_uint32) KG_LUCID_VERSION;
break;
}
if (kret)
goto error_out;
rep.value = &lctx;
rep.length = sizeof(lctx);
retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set);
if (GSS_ERROR(retval))
goto error_out;
error_out:
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | gss_krb5int_export_lucid_sec_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_error_code kret = 0;
OM_uint32 retval;
krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle;
void *lctx = NULL;
int version = 0;
gss_buffer_desc rep;
/* Assume failure */
retval = GSS_S_FAILURE;
*minor_status = 0;
*data_set = GSS_C_NO_BUFFER_SET;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
retval = generic_gss_oid_decompose(minor_status,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH,
desired_object,
&version);
if (GSS_ERROR(retval))
return retval;
/* Externalize a structure of the right version */
switch (version) {
case 1:
kret = make_external_lucid_ctx_v1((krb5_pointer)ctx,
version, &lctx);
break;
default:
kret = (OM_uint32) KG_LUCID_VERSION;
break;
}
if (kret)
goto error_out;
rep.value = &lctx;
rep.length = sizeof(lctx);
retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set);
if (GSS_ERROR(retval))
goto error_out;
error_out:
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
| 166,821 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ForeignSessionHelper::TriggerSessionSync(
JNIEnv* env,
const JavaParamRef<jobject>& obj) {
browser_sync::ProfileSyncService* service =
ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_);
if (!service)
return;
const syncer::ModelTypeSet types(syncer::SESSIONS);
service->TriggerRefresh(types);
}
Commit Message: Prefer SyncService over ProfileSyncService in foreign_session_helper
SyncService is the interface, ProfileSyncService is the concrete
implementation. Generally no clients should need to use the conrete
implementation - for one, testing will be much easier once everyone
uses the interface only.
Bug: 924508
Change-Id: Ia210665f8f02512053d1a60d627dea0f22758387
Reviewed-on: https://chromium-review.googlesource.com/c/1461119
Auto-Submit: Marc Treib <[email protected]>
Commit-Queue: Yaron Friedman <[email protected]>
Reviewed-by: Yaron Friedman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#630662}
CWE ID: CWE-254 | void ForeignSessionHelper::TriggerSessionSync(
JNIEnv* env,
const JavaParamRef<jobject>& obj) {
syncer::SyncService* service =
ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_);
if (!service)
return;
service->TriggerRefresh({syncer::SESSIONS});
}
| 172,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
size_t
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(size_t) (buffer[0] << 24);
value|=buffer[1] << 16;
value|=buffer[2] << 8;
value|=buffer[3];
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
unsigned int
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool omx_vdec::release_output_done(void)
{
bool bRet = false;
unsigned i=0,j=0;
DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_inp_mem_ptr);
if (m_out_mem_ptr) {
for (; j < drv_ctx.op_buf.actualcount ; j++) {
if (BITMASK_PRESENT(&m_out_bm_count,j)) {
break;
}
}
if (j == drv_ctx.op_buf.actualcount) {
m_out_bm_count = 0;
bRet = true;
}
} else {
m_out_bm_count = 0;
bRet = true;
}
return bRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers
Allow only up to 64 buffers on input/output port (since the
allocation bitmap is only 64-wide).
Do not allow changing theactual buffer count while still
holding allocation (Client can technically negotiate
buffer count on a free/disabled port)
Add safety checks to free only as many buffers were allocated.
Fixes: Security Vulnerability - Heap Overflow and Possible Local
Privilege Escalation in MediaServer (libOmxVdec problem #3)
Bug: 27532282 27661749
Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523
CWE ID: CWE-119 | bool omx_vdec::release_output_done(void)
{
bool bRet = false;
unsigned i=0,j=0;
DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_out_mem_ptr);
if (m_out_mem_ptr) {
for (; j < drv_ctx.op_buf.actualcount ; j++) {
if (BITMASK_PRESENT(&m_out_bm_count,j)) {
break;
}
}
if (j == drv_ctx.op_buf.actualcount) {
m_out_bm_count = 0;
bRet = true;
}
} else {
m_out_bm_count = 0;
bRet = true;
}
return bRet;
}
| 173,786 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void IGDstartelt(void * d, const char * name, int l)
{
struct IGDdatas * datas = (struct IGDdatas *)d;
memcpy( datas->cureltname, name, l);
datas->cureltname[l] = '\0';
datas->level++;
if( (l==7) && !memcmp(name, "service", l) ) {
datas->tmp.controlurl[0] = '\0';
datas->tmp.eventsuburl[0] = '\0';
datas->tmp.scpdurl[0] = '\0';
datas->tmp.servicetype[0] = '\0';
}
}
Commit Message: igd_desc_parse.c: fix buffer overflow
CWE ID: CWE-119 | void IGDstartelt(void * d, const char * name, int l)
{
struct IGDdatas * datas = (struct IGDdatas *)d;
if(l >= MINIUPNPC_URL_MAXSIZE)
l = MINIUPNPC_URL_MAXSIZE-1;
memcpy(datas->cureltname, name, l);
datas->cureltname[l] = '\0';
datas->level++;
if( (l==7) && !memcmp(name, "service", l) ) {
datas->tmp.controlurl[0] = '\0';
datas->tmp.eventsuburl[0] = '\0';
datas->tmp.scpdurl[0] = '\0';
datas->tmp.servicetype[0] = '\0';
}
}
| 166,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init xfrm6_tunnel_init(void)
{
int rv;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto err;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto unreg;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto dereg6;
rv = xfrm6_tunnel_spi_init();
if (rv < 0)
goto dereg46;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto deregspi;
return 0;
deregspi:
xfrm6_tunnel_spi_fini();
dereg46:
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
dereg6:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
unreg:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
err:
return rv;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int __init xfrm6_tunnel_init(void)
{
int rv;
xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi",
sizeof(struct xfrm6_tunnel_spi),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!xfrm6_tunnel_spi_kmem)
return -ENOMEM;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto out_pernet;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto out_type;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto out_xfrm6;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto out_xfrm46;
return 0;
out_xfrm46:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
out_xfrm6:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
out_type:
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
out_pernet:
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
return rv;
}
| 165,880 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CatalogueRescan (FontPathElementPtr fpe)
{
CataloguePtr cat = fpe->private;
char link[MAXFONTFILENAMELEN];
char dest[MAXFONTFILENAMELEN];
char *attrib;
FontPathElementPtr subfpe;
struct stat statbuf;
const char *path;
DIR *dir;
struct dirent *entry;
int len;
int pathlen;
path = fpe->name + strlen(CataloguePrefix);
if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode))
return BadFontPath;
if (statbuf.st_mtime <= cat->mtime)
return Successful;
dir = opendir(path);
if (dir == NULL)
{
xfree(cat);
return BadFontPath;
}
CatalogueUnrefFPEs (fpe);
while (entry = readdir(dir), entry != NULL)
{
snprintf(link, sizeof link, "%s/%s", path, entry->d_name);
len = readlink(link, dest, sizeof dest);
if (len < 0)
continue;
dest[len] = '\0';
if (dest[0] != '/')
{
pathlen = strlen(path);
memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1);
memcpy(dest, path, pathlen);
memcpy(dest + pathlen, "/", 1);
len += pathlen + 1;
}
attrib = strchr(link, ':');
if (attrib && len + strlen(attrib) < sizeof dest)
{
memcpy(dest + len, attrib, strlen(attrib));
len += strlen(attrib);
}
subfpe = xalloc(sizeof *subfpe);
if (subfpe == NULL)
continue;
/* The fonts returned by OpenFont will point back to the
* subfpe they come from. So set the type of the subfpe to
* what the catalogue fpe was assigned, so calls to CloseFont
* (which uses font->fpe->type) goes to CatalogueCloseFont. */
subfpe->type = fpe->type;
subfpe->name_length = len;
subfpe->name = xalloc (len + 1);
if (subfpe == NULL)
{
xfree(subfpe);
continue;
}
memcpy(subfpe->name, dest, len);
subfpe->name[len] = '\0';
/* The X server will manipulate the subfpe ref counts
* associated with the font in OpenFont and CloseFont, so we
* have to make sure it's valid. */
subfpe->refcount = 1;
if (FontFileInitFPE (subfpe) != Successful)
{
xfree(subfpe->name);
xfree(subfpe);
continue;
}
if (CatalogueAddFPE(cat, subfpe) != Successful)
{
FontFileFreeFPE (subfpe);
xfree(subfpe);
continue;
}
}
closedir(dir);
qsort(cat->fpeList,
cat->fpeCount, sizeof cat->fpeList[0], ComparePriority);
cat->mtime = statbuf.st_mtime;
return Successful;
}
Commit Message:
CWE ID: CWE-119 | CatalogueRescan (FontPathElementPtr fpe)
{
CataloguePtr cat = fpe->private;
char link[MAXFONTFILENAMELEN];
char dest[MAXFONTFILENAMELEN];
char *attrib;
FontPathElementPtr subfpe;
struct stat statbuf;
const char *path;
DIR *dir;
struct dirent *entry;
int len;
int pathlen;
path = fpe->name + strlen(CataloguePrefix);
if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode))
return BadFontPath;
if (statbuf.st_mtime <= cat->mtime)
return Successful;
dir = opendir(path);
if (dir == NULL)
{
xfree(cat);
return BadFontPath;
}
CatalogueUnrefFPEs (fpe);
while (entry = readdir(dir), entry != NULL)
{
snprintf(link, sizeof link, "%s/%s", path, entry->d_name);
len = readlink(link, dest, sizeof dest - 1);
if (len < 0)
continue;
dest[len] = '\0';
if (dest[0] != '/')
{
pathlen = strlen(path);
memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1);
memcpy(dest, path, pathlen);
memcpy(dest + pathlen, "/", 1);
len += pathlen + 1;
}
attrib = strchr(link, ':');
if (attrib && len + strlen(attrib) < sizeof dest)
{
memcpy(dest + len, attrib, strlen(attrib));
len += strlen(attrib);
}
subfpe = xalloc(sizeof *subfpe);
if (subfpe == NULL)
continue;
/* The fonts returned by OpenFont will point back to the
* subfpe they come from. So set the type of the subfpe to
* what the catalogue fpe was assigned, so calls to CloseFont
* (which uses font->fpe->type) goes to CatalogueCloseFont. */
subfpe->type = fpe->type;
subfpe->name_length = len;
subfpe->name = xalloc (len + 1);
if (subfpe == NULL)
{
xfree(subfpe);
continue;
}
memcpy(subfpe->name, dest, len);
subfpe->name[len] = '\0';
/* The X server will manipulate the subfpe ref counts
* associated with the font in OpenFont and CloseFont, so we
* have to make sure it's valid. */
subfpe->refcount = 1;
if (FontFileInitFPE (subfpe) != Successful)
{
xfree(subfpe->name);
xfree(subfpe);
continue;
}
if (CatalogueAddFPE(cat, subfpe) != Successful)
{
FontFileFreeFPE (subfpe);
xfree(subfpe);
continue;
}
}
closedir(dir);
qsort(cat->fpeList,
cat->fpeCount, sizeof cat->fpeList[0], ComparePriority);
cat->mtime = statbuf.st_mtime;
return Successful;
}
| 165,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decodetile != NULL);
if ((*sp->decodetile)(tif, op0, occ0, s)) {
tmsize_t rowsize = sp->rowsize;
assert(rowsize > 0);
assert((occ0%rowsize)==0);
assert(sp->decodepfunc != NULL);
while (occ0 > 0) {
(*sp->decodepfunc)(tif, op0, rowsize);
occ0 -= rowsize;
op0 += rowsize;
}
return 1;
} else
return 0;
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decodetile != NULL);
if ((*sp->decodetile)(tif, op0, occ0, s)) {
tmsize_t rowsize = sp->rowsize;
assert(rowsize > 0);
if((occ0%rowsize) !=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorDecodeTile",
"%s", "occ0%rowsize != 0");
return 0;
}
assert(sp->decodepfunc != NULL);
while (occ0 > 0) {
if( !(*sp->decodepfunc)(tif, op0, rowsize) )
return 0;
occ0 -= rowsize;
op0 += rowsize;
}
return 1;
} else
return 0;
}
| 166,877 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct super_block *alloc_super(struct file_system_type *type, int flags)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
int i;
if (!s)
return NULL;
if (security_sb_alloc(s))
goto fail;
#ifdef CONFIG_SMP
s->s_files = alloc_percpu(struct list_head);
if (!s->s_files)
goto fail;
for_each_possible_cpu(i)
INIT_LIST_HEAD(per_cpu_ptr(s->s_files, i));
#else
INIT_LIST_HEAD(&s->s_files);
#endif
for (i = 0; i < SB_FREEZE_LEVELS; i++) {
if (percpu_counter_init(&s->s_writers.counter[i], 0) < 0)
goto fail;
lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i],
&type->s_writers_key[i], 0);
}
init_waitqueue_head(&s->s_writers.wait);
init_waitqueue_head(&s->s_writers.wait_unfrozen);
s->s_flags = flags;
s->s_bdi = &default_backing_dev_info;
INIT_HLIST_NODE(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
if (list_lru_init(&s->s_dentry_lru))
goto fail;
if (list_lru_init(&s->s_inode_lru))
goto fail;
INIT_LIST_HEAD(&s->s_mounts);
init_rwsem(&s->s_umount);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
init_rwsem(&s->s_dquot.dqptr_sem);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = -1;
s->s_shrink.seeks = DEFAULT_SEEKS;
s->s_shrink.scan_objects = super_cache_scan;
s->s_shrink.count_objects = super_cache_count;
s->s_shrink.batch = 1024;
s->s_shrink.flags = SHRINKER_NUMA_AWARE;
return s;
fail:
destroy_super(s);
return NULL;
}
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 struct super_block *alloc_super(struct file_system_type *type, int flags)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
int i;
if (!s)
return NULL;
if (security_sb_alloc(s))
goto fail;
for (i = 0; i < SB_FREEZE_LEVELS; i++) {
if (percpu_counter_init(&s->s_writers.counter[i], 0) < 0)
goto fail;
lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i],
&type->s_writers_key[i], 0);
}
init_waitqueue_head(&s->s_writers.wait);
init_waitqueue_head(&s->s_writers.wait_unfrozen);
s->s_flags = flags;
s->s_bdi = &default_backing_dev_info;
INIT_HLIST_NODE(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
if (list_lru_init(&s->s_dentry_lru))
goto fail;
if (list_lru_init(&s->s_inode_lru))
goto fail;
INIT_LIST_HEAD(&s->s_mounts);
init_rwsem(&s->s_umount);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
init_rwsem(&s->s_dquot.dqptr_sem);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = -1;
s->s_shrink.seeks = DEFAULT_SEEKS;
s->s_shrink.scan_objects = super_cache_scan;
s->s_shrink.count_objects = super_cache_count;
s->s_shrink.batch = 1024;
s->s_shrink.flags = SHRINKER_NUMA_AWARE;
return s;
fail:
destroy_super(s);
return NULL;
}
| 166,806 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob)
{
ASSERT(&blob->registry() == this);
ThreadableBlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob)
{
ASSERT(&blob->registry() == this);
BlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
}
| 170,677 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType CheckMemoryOverflow(const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return(MagickTrue);
}
return(MagickFalse);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119 | static MagickBooleanType CheckMemoryOverflow(const size_t count,
| 168,539 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int hashtable_set(hashtable_t *hashtable,
const char *key, size_t serial,
json_t *value)
{
pair_t *pair;
bucket_t *bucket;
size_t hash, index;
/* rehash if the load ratio exceeds 1 */
if(hashtable->size >= num_buckets(hashtable))
if(hashtable_do_rehash(hashtable))
return -1;
hash = hash_str(key);
index = hash % num_buckets(hashtable);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(pair)
{
json_decref(pair->value);
pair->value = value;
}
else
{
/* offsetof(...) returns the size of pair_t without the last,
flexible member. This way, the correct amount is
allocated. */
pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1);
if(!pair)
return -1;
pair->hash = hash;
pair->serial = serial;
strcpy(pair->key, key);
pair->value = value;
list_init(&pair->list);
insert_to_bucket(hashtable, bucket, &pair->list);
hashtable->size++;
}
return 0;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | int hashtable_set(hashtable_t *hashtable,
const char *key, size_t serial,
json_t *value)
{
pair_t *pair;
bucket_t *bucket;
size_t hash, index;
/* rehash if the load ratio exceeds 1 */
if(hashtable->size >= hashsize(hashtable->order))
if(hashtable_do_rehash(hashtable))
return -1;
hash = hash_str(key);
index = hash & hashmask(hashtable->order);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(pair)
{
json_decref(pair->value);
pair->value = value;
}
else
{
/* offsetof(...) returns the size of pair_t without the last,
flexible member. This way, the correct amount is
allocated. */
pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1);
if(!pair)
return -1;
pair->hash = hash;
pair->serial = serial;
strcpy(pair->key, key);
pair->value = value;
list_init(&pair->list);
insert_to_bucket(hashtable, bucket, &pair->list);
hashtable->size++;
}
return 0;
}
| 166,533 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hcom_client_init
(
OUT p_hsm_com_client_hdl_t *p_hdl,
IN char *server_path,
IN char *client_path,
IN int max_data_len
)
{
hsm_com_client_hdl_t *hdl = NULL;
hsm_com_errno_t res = HSM_COM_OK;
if((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) ||
(strlen(server_path) == 0)){
res = HSM_COM_PATH_ERR;
goto cleanup;
}
if((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) ||
(strlen(client_path) == 0)){
res = HSM_COM_PATH_ERR;
goto cleanup;
}
if((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
if((hdl->scr.scratch = malloc(max_data_len)) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
if((hdl->recv_buf = malloc(max_data_len)) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
if((hdl->send_buf = malloc(max_data_len)) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
hdl->scr.scratch_fill = 0;
hdl->scr.scratch_len = max_data_len;
hdl->buf_len = max_data_len;
hdl->trans_id = 1;
strcpy(hdl->s_path,server_path);
strcpy(hdl->c_path,client_path);
hdl->client_state = HSM_COM_C_STATE_IN;
*p_hdl = hdl;
return res;
cleanup:
if(hdl)
{
if (hdl->scr.scratch) {
free(hdl->scr.scratch);
}
if (hdl->recv_buf) {
free(hdl->recv_buf);
}
free(hdl);
}
return res;
}
Commit Message: Fix scripts and code that use well-known tmp files.
CWE ID: CWE-362 | hcom_client_init
(
OUT p_hsm_com_client_hdl_t *p_hdl,
IN char *server_path,
IN char *client_path,
IN int max_data_len
)
{
hsm_com_client_hdl_t *hdl = NULL;
hsm_com_errno_t res = HSM_COM_OK;
if((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) ||
(strlen(server_path) == 0)){
res = HSM_COM_PATH_ERR;
goto cleanup;
}
if((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) ||
(strlen(client_path) == 0)){
res = HSM_COM_PATH_ERR;
goto cleanup;
}
if((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
if((hdl->scr.scratch = malloc(max_data_len)) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
if((hdl->recv_buf = malloc(max_data_len)) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
if((hdl->send_buf = malloc(max_data_len)) == NULL)
{
res = HSM_COM_NO_MEM;
goto cleanup;
}
hdl->scr.scratch_fill = 0;
hdl->scr.scratch_len = max_data_len;
hdl->buf_len = max_data_len;
hdl->trans_id = 1;
strcpy(hdl->s_path,server_path);
strcpy(hdl->c_path,client_path);
if (mkstemp(hdl->c_path) == -1)
{
res = HSM_COM_PATH_ERR;
goto cleanup;
}
hdl->client_state = HSM_COM_C_STATE_IN;
*p_hdl = hdl;
return res;
cleanup:
if(hdl)
{
if (hdl->scr.scratch) {
free(hdl->scr.scratch);
}
if (hdl->recv_buf) {
free(hdl->recv_buf);
}
free(hdl);
}
return res;
}
| 170,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void svc_rdma_put_req_map(struct svcxprt_rdma *xprt,
struct svc_rdma_req_map *map)
{
spin_lock(&xprt->sc_map_lock);
list_add(&map->free, &xprt->sc_maps);
spin_unlock(&xprt->sc_map_lock);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | void svc_rdma_put_req_map(struct svcxprt_rdma *xprt,
| 168,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hash_foreach_mangle_dict_of_strings (gpointer key, gpointer val, gpointer user_data)
{
GHashTable *out = (GHashTable*) user_data;
GHashTable *in_dict = (GHashTable *) val;
HashAndString *data = g_new0 (HashAndString, 1);
data->string = (gchar*) key;
data->hash = g_hash_table_new_full (g_str_hash, g_str_equal,
g_free, g_free);
g_hash_table_foreach (in_dict, hash_foreach_prepend_string, data);
g_hash_table_insert(out, g_strdup ((gchar*) key), data->hash);
}
Commit Message:
CWE ID: CWE-264 | hash_foreach_mangle_dict_of_strings (gpointer key, gpointer val, gpointer user_data)
| 165,085 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: asn1_get_octet_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *str_len)
{
int len_len;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
/* if(str==NULL) return ASN1_SUCCESS; */
*str_len = asn1_get_length_der (der, der_len, &len_len);
if (*str_len < 0)
return ASN1_DER_ERROR;
*ret_len = *str_len + len_len;
if (str_size >= *str_len)
memcpy (str, der + len_len, *str_len);
else
{
return ASN1_MEM_ERROR;
}
return ASN1_SUCCESS;
}
Commit Message:
CWE ID: CWE-189 | asn1_get_octet_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *str_len)
{
int len_len = 0;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
/* if(str==NULL) return ASN1_SUCCESS; */
*str_len = asn1_get_length_der (der, der_len, &len_len);
if (*str_len < 0)
return ASN1_DER_ERROR;
*ret_len = *str_len + len_len;
if (str_size >= *str_len)
memcpy (str, der + len_len, *str_len);
else
{
return ASN1_MEM_ERROR;
}
return ASN1_SUCCESS;
}
| 165,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
base::MakeUnique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | void ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
std::make_unique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
| 173,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t DRMSource::read(MediaBuffer **buffer, const ReadOptions *options) {
Mutex::Autolock autoLock(mDRMLock);
status_t err;
if ((err = mOriginalMediaSource->read(buffer, options)) != OK) {
return err;
}
size_t len = (*buffer)->range_length();
char *src = (char *)(*buffer)->data() + (*buffer)->range_offset();
DrmBuffer encryptedDrmBuffer(src, len);
DrmBuffer decryptedDrmBuffer;
decryptedDrmBuffer.length = len;
decryptedDrmBuffer.data = new char[len];
DrmBuffer *pDecryptedDrmBuffer = &decryptedDrmBuffer;
if ((err = mDrmManagerClient->decrypt(mDecryptHandle, mTrackId,
&encryptedDrmBuffer, &pDecryptedDrmBuffer)) != NO_ERROR) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return err;
}
CHECK(pDecryptedDrmBuffer == &decryptedDrmBuffer);
const char *mime;
CHECK(getFormat()->findCString(kKeyMIMEType, &mime));
if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) && !mWantsNALFragments) {
uint8_t *dstData = (uint8_t*)src;
size_t srcOffset = 0;
size_t dstOffset = 0;
len = decryptedDrmBuffer.length;
while (srcOffset < len) {
CHECK(srcOffset + mNALLengthSize <= len);
size_t nalLength = 0;
const uint8_t* data = (const uint8_t*)(&decryptedDrmBuffer.data[srcOffset]);
switch (mNALLengthSize) {
case 1:
nalLength = *data;
break;
case 2:
nalLength = U16_AT(data);
break;
case 3:
nalLength = ((size_t)data[0] << 16) | U16_AT(&data[1]);
break;
case 4:
nalLength = U32_AT(data);
break;
default:
CHECK(!"Should not be here.");
break;
}
srcOffset += mNALLengthSize;
size_t end = srcOffset + nalLength;
if (end > len || end < srcOffset) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= (*buffer)->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &decryptedDrmBuffer.data[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, len);
(*buffer)->set_range((*buffer)->range_offset(), dstOffset);
} else {
memcpy(src, decryptedDrmBuffer.data, decryptedDrmBuffer.length);
(*buffer)->set_range((*buffer)->range_offset(), decryptedDrmBuffer.length);
}
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return OK;
}
Commit Message: Fix security vulnerability in libstagefright
bug: 28175045
Change-Id: Icee6c7eb5b761da4aa3e412fb71825508d74d38f
CWE ID: CWE-119 | status_t DRMSource::read(MediaBuffer **buffer, const ReadOptions *options) {
Mutex::Autolock autoLock(mDRMLock);
status_t err;
if ((err = mOriginalMediaSource->read(buffer, options)) != OK) {
return err;
}
size_t len = (*buffer)->range_length();
char *src = (char *)(*buffer)->data() + (*buffer)->range_offset();
DrmBuffer encryptedDrmBuffer(src, len);
DrmBuffer decryptedDrmBuffer;
decryptedDrmBuffer.length = len;
decryptedDrmBuffer.data = new char[len];
DrmBuffer *pDecryptedDrmBuffer = &decryptedDrmBuffer;
if ((err = mDrmManagerClient->decrypt(mDecryptHandle, mTrackId,
&encryptedDrmBuffer, &pDecryptedDrmBuffer)) != NO_ERROR) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return err;
}
CHECK(pDecryptedDrmBuffer == &decryptedDrmBuffer);
const char *mime;
CHECK(getFormat()->findCString(kKeyMIMEType, &mime));
if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) && !mWantsNALFragments) {
uint8_t *dstData = (uint8_t*)src;
size_t srcOffset = 0;
size_t dstOffset = 0;
len = decryptedDrmBuffer.length;
while (srcOffset < len) {
CHECK(srcOffset + mNALLengthSize <= len);
size_t nalLength = 0;
const uint8_t* data = (const uint8_t*)(&decryptedDrmBuffer.data[srcOffset]);
switch (mNALLengthSize) {
case 1:
nalLength = *data;
break;
case 2:
nalLength = U16_AT(data);
break;
case 3:
nalLength = ((size_t)data[0] << 16) | U16_AT(&data[1]);
break;
case 4:
nalLength = U32_AT(data);
break;
default:
CHECK(!"Should not be here.");
break;
}
srcOffset += mNALLengthSize;
size_t end = srcOffset + nalLength;
if (end > len || end < srcOffset) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
if (dstOffset > SIZE_MAX - 4 ||
dstOffset + 4 > SIZE_MAX - nalLength ||
dstOffset + 4 + nalLength > (*buffer)->size()) {
(*buffer)->release();
(*buffer) = NULL;
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &decryptedDrmBuffer.data[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, len);
(*buffer)->set_range((*buffer)->range_offset(), dstOffset);
} else {
memcpy(src, decryptedDrmBuffer.data, decryptedDrmBuffer.length);
(*buffer)->set_range((*buffer)->range_offset(), decryptedDrmBuffer.length);
}
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return OK;
}
| 173,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j));
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
Commit Message: Update AffiliationFetcher to use new Affiliation API wire format.
The new format is not backward compatible with the old one, therefore this CL updates the client side protobuf definitions to be in line with the API definition. However, this CL does not yet make use of any additional fields introduced in the new wire format.
BUG=437865
Review URL: https://codereview.chromium.org/996613002
Cr-Commit-Position: refs/heads/master@{#319860}
CWE ID: CWE-119 | bool AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j).id());
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
| 171,143 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < sizeof(struct eth_header)) {
l2_hdr->iov_len = 0;
return false;
}
l2_hdr->iov_len = sizeof(struct eth_header);
switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
case ETH_P_VLAN:
l2_hdr->iov_len += sizeof(struct vlan_header);
break;
case ETH_P_DVLAN:
l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
break;
}
if (bytes_read < l2_hdr->iov_len) {
l2_hdr->iov_len = 0;
return false;
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
switch (l3_proto) {
case ETH_P_IP:
l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, sizeof(struct ip_header));
if (bytes_read < sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
Commit Message:
CWE ID: CWE-119 | static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < sizeof(struct eth_header)) {
l2_hdr->iov_len = 0;
return false;
}
l2_hdr->iov_len = sizeof(struct eth_header);
switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
case ETH_P_VLAN:
l2_hdr->iov_len += sizeof(struct vlan_header);
break;
case ETH_P_DVLAN:
l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
break;
}
if (bytes_read < l2_hdr->iov_len) {
l2_hdr->iov_len = 0;
return false;
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
switch (l3_proto) {
case ETH_P_IP:
l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, sizeof(struct ip_header));
if (bytes_read < sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
if(l3_hdr->iov_len < sizeof(struct ip_header))
{
l3_hdr->iov_len = 0;
return false;
}
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
| 164,950 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ImageLoader::updateFromElement()
{
Document* document = m_element->document();
if (!document->renderer())
return;
AtomicString attr = m_element->imageSourceURL();
if (attr == m_failedLoadURL)
return;
CachedResourceHandle<CachedImage> newImage = 0;
if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
CachedResourceRequest request(ResourceRequest(document->completeURL(sourceURI(attr))));
request.setInitiator(element());
String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
if (!crossOriginMode.isNull()) {
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
updateRequestForAccessControl(request.mutableResourceRequest(), document->securityOrigin(), allowCredentials);
}
if (m_loadManually) {
bool autoLoadOtherImages = document->cachedResourceLoader()->autoLoadImages();
document->cachedResourceLoader()->setAutoLoadImages(false);
newImage = new CachedImage(request.resourceRequest());
newImage->setLoading(true);
newImage->setOwningCachedResourceLoader(document->cachedResourceLoader());
document->cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get());
document->cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages);
} else
newImage = document->cachedResourceLoader()->requestImage(request);
if (!newImage && !pageIsBeingDismissed(document)) {
m_failedLoadURL = attr;
m_hasPendingErrorEvent = true;
errorEventSender().dispatchEventSoon(this);
} else
clearFailedLoadURL();
} else if (!attr.isNull()) {
m_element->dispatchEvent(Event::create(eventNames().errorEvent, false, false));
}
CachedImage* oldImage = m_image.get();
if (newImage != oldImage) {
if (m_hasPendingBeforeLoadEvent) {
beforeLoadEventSender().cancelEvent(this);
m_hasPendingBeforeLoadEvent = false;
}
if (m_hasPendingLoadEvent) {
loadEventSender().cancelEvent(this);
m_hasPendingLoadEvent = false;
}
if (m_hasPendingErrorEvent && newImage) {
errorEventSender().cancelEvent(this);
m_hasPendingErrorEvent = false;
}
m_image = newImage;
m_hasPendingBeforeLoadEvent = !m_element->document()->isImageDocument() && newImage;
m_hasPendingLoadEvent = newImage;
m_imageComplete = !newImage;
if (newImage) {
if (!m_element->document()->isImageDocument()) {
if (!m_element->document()->hasListenerType(Document::BEFORELOAD_LISTENER))
dispatchPendingBeforeLoadEvent();
else
beforeLoadEventSender().dispatchEventSoon(this);
} else
updateRenderer();
newImage->addClient(this);
}
if (oldImage)
oldImage->removeClient(this);
}
if (RenderImageResource* imageResource = renderImageResource())
imageResource->resetAnimation();
updatedHasPendingEvent();
}
Commit Message: Error event was fired synchronously blowing away the input element from underneath. Remove the FIXME and fire it asynchronously using errorEventSender().
BUG=240124
Review URL: https://chromiumcodereview.appspot.com/14741011
git-svn-id: svn://svn.chromium.org/blink/trunk@150232 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416 | void ImageLoader::updateFromElement()
{
Document* document = m_element->document();
if (!document->renderer())
return;
AtomicString attr = m_element->imageSourceURL();
if (attr == m_failedLoadURL)
return;
CachedResourceHandle<CachedImage> newImage = 0;
if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
CachedResourceRequest request(ResourceRequest(document->completeURL(sourceURI(attr))));
request.setInitiator(element());
String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
if (!crossOriginMode.isNull()) {
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
updateRequestForAccessControl(request.mutableResourceRequest(), document->securityOrigin(), allowCredentials);
}
if (m_loadManually) {
bool autoLoadOtherImages = document->cachedResourceLoader()->autoLoadImages();
document->cachedResourceLoader()->setAutoLoadImages(false);
newImage = new CachedImage(request.resourceRequest());
newImage->setLoading(true);
newImage->setOwningCachedResourceLoader(document->cachedResourceLoader());
document->cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get());
document->cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages);
} else
newImage = document->cachedResourceLoader()->requestImage(request);
if (!newImage && !pageIsBeingDismissed(document)) {
m_failedLoadURL = attr;
m_hasPendingErrorEvent = true;
errorEventSender().dispatchEventSoon(this);
} else
clearFailedLoadURL();
} else if (!attr.isNull()) {
m_hasPendingErrorEvent = true;
errorEventSender().dispatchEventSoon(this);
}
CachedImage* oldImage = m_image.get();
if (newImage != oldImage) {
if (m_hasPendingBeforeLoadEvent) {
beforeLoadEventSender().cancelEvent(this);
m_hasPendingBeforeLoadEvent = false;
}
if (m_hasPendingLoadEvent) {
loadEventSender().cancelEvent(this);
m_hasPendingLoadEvent = false;
}
if (m_hasPendingErrorEvent && newImage) {
errorEventSender().cancelEvent(this);
m_hasPendingErrorEvent = false;
}
m_image = newImage;
m_hasPendingBeforeLoadEvent = !m_element->document()->isImageDocument() && newImage;
m_hasPendingLoadEvent = newImage;
m_imageComplete = !newImage;
if (newImage) {
if (!m_element->document()->isImageDocument()) {
if (!m_element->document()->hasListenerType(Document::BEFORELOAD_LISTENER))
dispatchPendingBeforeLoadEvent();
else
beforeLoadEventSender().dispatchEventSoon(this);
} else
updateRenderer();
newImage->addClient(this);
}
if (oldImage)
oldImage->removeClient(this);
}
if (RenderImageResource* imageResource = renderImageResource())
imageResource->resetAnimation();
updatedHasPendingEvent();
}
| 171,319 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
} else {
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
write = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
if (value != NULL) {
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
write = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
Commit Message: UriQuery.c: Catch integer overflow in ComposeQuery and ...Ex
CWE ID: CWE-190 | int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
int keyRequiredChars;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
int valueRequiredChars;
if ((keyLen >= INT_MAX / worstCase) || (valueLen >= INT_MAX / worstCase)) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
keyRequiredChars = worstCase * keyLen;
valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
} else {
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
write = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
if (value != NULL) {
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
write = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
| 168,975 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void find_entity_for_char(
unsigned int k,
enum entity_charset charset,
const entity_stage1_row *table,
const unsigned char **entity,
size_t *entity_len,
unsigned char *old,
size_t oldlen,
size_t *cursor)
{
unsigned stage1_idx = ENT_STAGE1_INDEX(k);
const entity_stage3_row *c;
if (stage1_idx > 0x1D) {
*entity = NULL;
*entity_len = 0;
return;
}
c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
if (!c->ambiguous) {
*entity = (const unsigned char *)c->data.ent.entity;
*entity_len = c->data.ent.entity_len;
} else {
/* peek at next char */
size_t cursor_before = *cursor;
int status = SUCCESS;
unsigned next_char;
if (!(*cursor < oldlen))
goto no_suitable_2nd;
next_char = get_next_char(charset, old, oldlen, cursor, &status);
if (status == FAILURE)
goto no_suitable_2nd;
{
const entity_multicodepoint_row *s, *e;
s = &c->data.multicodepoint_table[1];
e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
/* we could do a binary search but it's not worth it since we have
* at most two entries... */
for ( ; s <= e; s++) {
if (s->normal_entry.second_cp == next_char) {
*entity = s->normal_entry.entity;
*entity_len = s->normal_entry.entity_len;
return;
}
}
}
no_suitable_2nd:
*cursor = cursor_before;
*entity = (const unsigned char *)
c->data.multicodepoint_table[0].leading_entry.default_entity;
*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
}
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static inline void find_entity_for_char(
unsigned int k,
enum entity_charset charset,
const entity_stage1_row *table,
const unsigned char **entity,
size_t *entity_len,
unsigned char *old,
size_t oldlen,
size_t *cursor)
{
unsigned stage1_idx = ENT_STAGE1_INDEX(k);
const entity_stage3_row *c;
if (stage1_idx > 0x1D) {
*entity = NULL;
*entity_len = 0;
return;
}
c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
if (!c->ambiguous) {
*entity = (const unsigned char *)c->data.ent.entity;
*entity_len = c->data.ent.entity_len;
} else {
/* peek at next char */
size_t cursor_before = *cursor;
int status = SUCCESS;
unsigned next_char;
if (!(*cursor < oldlen))
goto no_suitable_2nd;
next_char = get_next_char(charset, old, oldlen, cursor, &status);
if (status == FAILURE)
goto no_suitable_2nd;
{
const entity_multicodepoint_row *s, *e;
s = &c->data.multicodepoint_table[1];
e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
/* we could do a binary search but it's not worth it since we have
* at most two entries... */
for ( ; s <= e; s++) {
if (s->normal_entry.second_cp == next_char) {
*entity = s->normal_entry.entity;
*entity_len = s->normal_entry.entity_len;
return;
}
}
}
no_suitable_2nd:
*cursor = cursor_before;
*entity = (const unsigned char *)
c->data.multicodepoint_table[0].leading_entry.default_entity;
*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
}
}
| 167,171 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436 | flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_byte_array_free (client->auth_buffer, TRUE);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
| 169,341 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void xfrm6_tunnel_spi_fini(void)
{
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static void xfrm6_tunnel_spi_fini(void)
| 165,881 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserPpapiHostImpl::DeleteInstance(PP_Instance instance) {
auto it = instance_map_.find(instance);
DCHECK(it != instance_map_.end());
for (auto& observer : it->second->observer_list)
observer.OnHostDestroyed();
instance_map_.erase(it);
}
Commit Message: Validate in-process plugin instance messages.
Bug: 733548, 733549
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba
Reviewed-on: https://chromium-review.googlesource.com/538908
Commit-Queue: Bill Budge <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480696}
CWE ID: CWE-20 | void BrowserPpapiHostImpl::DeleteInstance(PP_Instance instance) {
// NOTE: 'instance' may be coming from a compromised renderer process. We
// take care here to make sure an attacker can't cause a UAF by deleting a
// non-existent plugin instance.
// See http://crbug.com/733548.
auto it = instance_map_.find(instance);
if (it != instance_map_.end()) {
// We need to tell the observers for that instance that we are destroyed
// because we won't have the opportunity to once we remove them from the
// |instance_map_|. If the instance was deleted, observers for those
// instances should never call back into the host anyway, so it is safe to
// tell them that the host is destroyed.
for (auto& observer : it->second->observer_list)
observer.OnHostDestroyed();
instance_map_.erase(it);
} else {
NOTREACHED();
}
}
| 172,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual scoped_refptr<ui::Texture> CreateTransportClient(
const gfx::Size& size,
float device_scale_factor,
uint64 transport_handle) {
if (!shared_context_.get())
return NULL;
scoped_refptr<ImageTransportClientTexture> image(
new ImageTransportClientTexture(shared_context_.get(),
size, device_scale_factor,
transport_handle));
return image;
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | virtual scoped_refptr<ui::Texture> CreateTransportClient(
const gfx::Size& size,
float device_scale_factor,
const std::string& mailbox_name) {
if (!shared_context_.get())
return NULL;
scoped_refptr<ImageTransportClientTexture> image(
new ImageTransportClientTexture(shared_context_.get(),
size, device_scale_factor,
mailbox_name));
return image;
}
| 171,361 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_reader);
#endif
}
Commit Message:
CWE ID: | ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_writer);
#endif
}
| 164,883 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if ((stop >= 0) && (pos >= stop))
return E_FILE_FORMAT_INVALID;
long len;
id = ReadUInt(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if ((stop >= 0) && (pos >= stop))
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if ((stop >= 0) && ((pos + size) > stop))
return E_FILE_FORMAT_INVALID;
return 0; // success
}
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 mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos,
long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
// Invalid: Negative payload size, negative or 0 length integer, or integer
// larger than 64 bits (libwebm cannot handle them).
return E_FILE_FORMAT_INVALID;
}
// Avoid rolling over pos when very close to LONG_LONG_MAX.
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 173,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void file_sb_list_add(struct file *file, struct super_block *sb)
{
if (likely(!(file->f_mode & FMODE_WRITE)))
return;
if (!S_ISREG(file_inode(file)->i_mode))
return;
lg_local_lock(&files_lglock);
__file_sb_list_add(file, sb);
lg_local_unlock(&files_lglock);
}
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 | void file_sb_list_add(struct file *file, struct super_block *sb)
| 166,798 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int on_http_message_complete(http_parser* parser)
{
struct clt_info *info = parser->data;
ws_svr *svr = ws_svr_from_ses(info->ses);
info->request->version_major = parser->http_major;
info->request->version_minor = parser->http_minor;
info->request->method = parser->method;
dict_entry *entry;
dict_iterator *iter = dict_get_iterator(info->request->headers);
while ((entry = dict_next(iter)) != NULL) {
log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val);
}
dict_release_iterator(iter);
if (info->request->method != HTTP_GET)
goto error;
if (http_request_get_header(info->request, "Host") == NULL)
goto error;
double version = info->request->version_major + info->request->version_minor * 0.1;
if (version < 1.1)
goto error;
const char *upgrade = http_request_get_header(info->request, "Upgrade");
if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0)
goto error;
const char *connection = http_request_get_header(info->request, "Connection");
if (connection == NULL)
goto error;
else {
bool found_upgrade = false;
int count;
sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count);
if (tokens == NULL)
goto error;
for (int i = 0; i < count; i++) {
sds token = tokens[i];
sdstrim(token, " ");
if (strcasecmp(token, "Upgrade") == 0) {
found_upgrade = true;
break;
}
}
sdsfreesplitres(tokens, count);
if (!found_upgrade)
goto error;
}
const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version");
if (ws_version == NULL || strcmp(ws_version, "13") != 0)
goto error;
const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key");
if (ws_key == NULL)
goto error;
const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol");
if (protocol_list && !is_good_protocol(protocol_list, svr->protocol))
goto error;
if (strlen(svr->origin) > 0) {
const char *origin = http_request_get_header(info->request, "Origin");
if (origin == NULL || !is_good_origin(origin, svr->origin))
goto error;
}
if (svr->type.on_privdata_alloc) {
info->privdata = svr->type.on_privdata_alloc(svr);
if (info->privdata == NULL)
goto error;
}
info->upgrade = true;
info->remote = sdsnew(http_get_remote_ip(info->ses, info->request));
info->url = sdsnew(info->request->url);
if (svr->type.on_upgrade) {
svr->type.on_upgrade(info->ses, info->remote);
}
if (protocol_list) {
send_hand_shake_reply(info->ses, svr->protocol, ws_key);
} else {
send_hand_shake_reply(info->ses, NULL, ws_key);
}
return 0;
error:
ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses);
return -1;
}
Commit Message: Merge pull request #131 from benjaminchodroff/master
fix memory corruption and other 32bit overflows
CWE ID: CWE-190 | static int on_http_message_complete(http_parser* parser)
{
struct clt_info *info = parser->data;
ws_svr *svr = ws_svr_from_ses(info->ses);
info->request->version_major = parser->http_major;
info->request->version_minor = parser->http_minor;
info->request->method = parser->method;
dict_entry *entry;
dict_iterator *iter = dict_get_iterator(info->request->headers);
while ((entry = dict_next(iter)) != NULL) {
log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val);
}
dict_release_iterator(iter);
if (info->request->method != HTTP_GET)
goto error;
if (http_request_get_header(info->request, "Host") == NULL)
goto error;
double version = info->request->version_major + info->request->version_minor * 0.1;
if (version < 1.1)
goto error;
const char *upgrade = http_request_get_header(info->request, "Upgrade");
if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0)
goto error;
const char *connection = http_request_get_header(info->request, "Connection");
if (connection == NULL || strlen(connection) > UT_WS_SVR_MAX_HEADER_SIZE)
goto error;
else {
bool found_upgrade = false;
int count;
sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count);
if (tokens == NULL)
goto error;
for (int i = 0; i < count; i++) {
sds token = tokens[i];
sdstrim(token, " ");
if (strcasecmp(token, "Upgrade") == 0) {
found_upgrade = true;
break;
}
}
sdsfreesplitres(tokens, count);
if (!found_upgrade)
goto error;
}
const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version");
if (ws_version == NULL || strcmp(ws_version, "13") != 0)
goto error;
const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key");
if (ws_key == NULL)
goto error;
const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol");
if (protocol_list && !is_good_protocol(protocol_list, svr->protocol))
goto error;
if (strlen(svr->origin) > 0) {
const char *origin = http_request_get_header(info->request, "Origin");
if (origin == NULL || !is_good_origin(origin, svr->origin))
goto error;
}
if (svr->type.on_privdata_alloc) {
info->privdata = svr->type.on_privdata_alloc(svr);
if (info->privdata == NULL)
goto error;
}
info->upgrade = true;
info->remote = sdsnew(http_get_remote_ip(info->ses, info->request));
info->url = sdsnew(info->request->url);
if (svr->type.on_upgrade) {
svr->type.on_upgrade(info->ses, info->remote);
}
if (protocol_list) {
send_hand_shake_reply(info->ses, svr->protocol, ws_key);
} else {
send_hand_shake_reply(info->ses, NULL, ws_key);
}
return 0;
error:
ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses);
return -1;
}
| 169,018 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(locale_get_display_script)
{
get_icu_disp_value_src_php( LOC_SCRIPT_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_script)
PHP_FUNCTION(locale_get_display_script)
{
get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,187 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
ContentSecurityPolicy* policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
if (IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
}
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
// Plugin documents inherit their parent/opener's 'plugin-types' directive
// regardless of URL.
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
| 172,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
return image_transform_png_set_expand_add(this, that, colour_type,
bit_depth);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
#if PNG_LIBPNG_VER < 10700
return image_transform_png_set_expand_add(this, that, colour_type,
bit_depth);
#else
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* This should do nothing unless the color type is gray and the bit depth is
* less than 8:
*/
return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
#endif /* 1.7 or later */
}
| 173,630 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a,
long offset,int ch,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
long i,j;
int chptr=0;
if (!v) return -1;
for(i=offset;i<offset+n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim;j++){
a[chptr++][i]+=v[j];
if(chptr==ch){
chptr=0;
i++;
}
}
}
}
return 0;
}
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 | long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a,
long offset,int ch,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
long i,j;
int chptr=0;
if (!v) return -1;
for(i=offset;i<offset+n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim && i < offset + n;j++){
a[chptr++][i]+=v[j];
if(chptr==ch){
chptr=0;
i++;
}
}
}
}
return 0;
}
| 173,989 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
desc = util_format_description(elements[i].src_format);
if (!desc) {
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
if (vrend_state.have_vertex_attrib_binding) {
glGenVertexArrays(1, &v->id);
glBindVertexArray(v->id);
for (i = 0; i < num_elements; i++) {
struct vrend_vertex_element *ve = &v->elements[i];
if (util_format_is_pure_integer(ve->base.src_format))
glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset);
else
glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset);
glVertexAttribBinding(i, ve->base.vertex_buffer_index);
glVertexBindingDivisor(i, ve->base.instance_divisor);
glEnableVertexAttribArray(i);
}
}
ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle,
VIRGL_OBJECT_VERTEX_ELEMENTS);
if (!ret_handle) {
FREE(v);
return ENOMEM;
}
return 0;
}
Commit Message:
CWE ID: CWE-772 | int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v;
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v = CALLOC_STRUCT(vrend_vertex_element_array);
if (!v)
return ENOMEM;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
desc = util_format_description(elements[i].src_format);
if (!desc) {
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
if (vrend_state.have_vertex_attrib_binding) {
glGenVertexArrays(1, &v->id);
glBindVertexArray(v->id);
for (i = 0; i < num_elements; i++) {
struct vrend_vertex_element *ve = &v->elements[i];
if (util_format_is_pure_integer(ve->base.src_format))
glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset);
else
glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset);
glVertexAttribBinding(i, ve->base.vertex_buffer_index);
glVertexBindingDivisor(i, ve->base.instance_divisor);
glEnableVertexAttribArray(i);
}
}
ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle,
VIRGL_OBJECT_VERTEX_ELEMENTS);
if (!ret_handle) {
FREE(v);
return ENOMEM;
}
return 0;
}
| 164,944 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
#if defined(OS_WIN)
channel_layout = media::CHANNEL_LAYOUT_STEREO;
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 2 * 440;
}
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
if (sample_rate == 48000) {
buffer_size = 480;
} else {
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
Commit Message: Avoids crash in WebRTC audio clients for 96kHz render rate on Mac OSX.
TBR=xians
BUG=166523
TEST=Misc set of WebRTC audio clients on Mac.
Review URL: https://codereview.chromium.org/11773017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175323 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
#if defined(OS_WIN)
channel_layout = media::CHANNEL_LAYOUT_STEREO;
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 2 * 440;
}
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
// frame size to use for 96kHz, 48kHz and 44.1kHz.
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
| 171,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_read (SF_PRIVATE *psf, void *ptr, int bytes)
{ int count = 0 ;
if (psf->headindex >= SIGNED_SIZEOF (psf->header))
return psf_fread (ptr, 1, bytes, psf) ;
if (psf->headindex + bytes > SIGNED_SIZEOF (psf->header))
{ int most ;
most = SIGNED_SIZEOF (psf->header) - psf->headend ;
psf_fread (psf->header + psf->headend, 1, most, psf) ;
memcpy (ptr, psf->header + psf->headend, most) ;
psf->headend = psf->headindex += most ;
psf_fread ((char *) ptr + most, bytes - most, 1, psf) ;
return bytes ;
} ;
if (psf->headindex + bytes > psf->headend)
{ count = psf_fread (psf->header + psf->headend, 1, bytes - (psf->headend - psf->headindex), psf) ;
if (count != bytes - (int) (psf->headend - psf->headindex))
{ psf_log_printf (psf, "Error : psf_fread returned short count.\n") ;
return count ;
} ;
psf->headend += count ;
} ;
memcpy (ptr, psf->header + psf->headindex, bytes) ;
psf->headindex += bytes ;
return bytes ;
} /* header_read */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_read (SF_PRIVATE *psf, void *ptr, int bytes)
{ int count = 0 ;
if (psf->header.indx + bytes >= psf->header.len && psf_bump_header_allocation (psf, bytes))
return count ;
if (psf->header.indx + bytes > psf->header.end)
{ count = psf_fread (psf->header.ptr + psf->header.end, 1, bytes - (psf->header.end - psf->header.indx), psf) ;
if (count != bytes - (int) (psf->header.end - psf->header.indx))
{ psf_log_printf (psf, "Error : psf_fread returned short count.\n") ;
return count ;
} ;
psf->header.end += count ;
} ;
memcpy (ptr, psf->header.ptr + psf->header.indx, bytes) ;
psf->header.indx += bytes ;
return bytes ;
} /* header_read */
| 170,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t socket_write_and_transfer_fd(const socket_t *socket, const void *buf, size_t count, int fd) {
assert(socket != NULL);
assert(buf != NULL);
if (fd == INVALID_FD)
return socket_write(socket, buf, count);
struct msghdr msg;
struct iovec iov;
char control_buf[CMSG_SPACE(sizeof(int))];
iov.iov_base = (void *)buf;
iov.iov_len = count;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = control_buf;
msg.msg_controllen = sizeof(control_buf);
msg.msg_name = NULL;
msg.msg_namelen = 0;
struct cmsghdr *header = CMSG_FIRSTHDR(&msg);
header->cmsg_level = SOL_SOCKET;
header->cmsg_type = SCM_RIGHTS;
header->cmsg_len = CMSG_LEN(sizeof(int));
*(int *)CMSG_DATA(header) = fd;
ssize_t ret = sendmsg(socket->fd, &msg, MSG_DONTWAIT);
close(fd);
return ret;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | ssize_t socket_write_and_transfer_fd(const socket_t *socket, const void *buf, size_t count, int fd) {
assert(socket != NULL);
assert(buf != NULL);
if (fd == INVALID_FD)
return socket_write(socket, buf, count);
struct msghdr msg;
struct iovec iov;
char control_buf[CMSG_SPACE(sizeof(int))];
iov.iov_base = (void *)buf;
iov.iov_len = count;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = control_buf;
msg.msg_controllen = sizeof(control_buf);
msg.msg_name = NULL;
msg.msg_namelen = 0;
struct cmsghdr *header = CMSG_FIRSTHDR(&msg);
header->cmsg_level = SOL_SOCKET;
header->cmsg_type = SCM_RIGHTS;
header->cmsg_len = CMSG_LEN(sizeof(int));
*(int *)CMSG_DATA(header) = fd;
ssize_t ret = TEMP_FAILURE_RETRY(sendmsg(socket->fd, &msg, MSG_DONTWAIT));
close(fd);
return ret;
}
| 173,488 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path,
const char *name, V9fsPath *target)
{
if (dir_path) {
v9fs_path_sprintf(target, "%s/%s", dir_path->data, name);
} else {
v9fs_path_sprintf(target, "%s", name);
}
return 0;
}
Commit Message:
CWE ID: CWE-732 | static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path,
const char *name, V9fsPath *target)
{
if (dir_path) {
v9fs_path_sprintf(target, "%s/%s", dir_path->data, name);
} else if (strcmp(name, "/")) {
v9fs_path_sprintf(target, "%s", name);
} else {
/* We want the path of the export root to be relative, otherwise
* "*at()" syscalls would treat it as "/" in the host.
*/
v9fs_path_sprintf(target, "%s", ".");
}
return 0;
}
| 165,457 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_send_tls(gnutls_session * session, xmlNode * msg)
{
char *xml_text = NULL;
# if 0
const char *name = crm_element_name(msg);
if (safe_str_neq(name, "cib_command")) {
xmlNodeSetName(msg, "cib_result");
}
# endif
xml_text = dump_xml_unformatted(msg);
if (xml_text != NULL) {
char *unsent = xml_text;
int len = strlen(xml_text);
int rc = 0;
len++; /* null char */
crm_trace("Message size: %d", len);
while (TRUE) {
rc = gnutls_record_send(*session, unsent, len);
crm_debug("Sent %d bytes", rc);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_debug("Retry");
} else if (rc < 0) {
crm_debug("Connection terminated");
break;
} else if (rc < len) {
crm_debug("Only sent %d of %d bytes", rc, len);
len -= rc;
unsent += rc;
} else {
break;
}
}
}
free(xml_text);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_send_tls(gnutls_session * session, xmlNode * msg)
static int
crm_send_tls(gnutls_session * session, const char *buf, size_t len)
{
const char *unsent = buf;
int rc = 0;
int total_send;
if (buf == NULL) {
return -1;
}
total_send = len;
crm_trace("Message size: %d", len);
while (TRUE) {
rc = gnutls_record_send(*session, unsent, len);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_debug("Retry");
} else if (rc < 0) {
crm_err("Connection terminated rc = %d", rc);
break;
} else if (rc < len) {
crm_debug("Only sent %d of %d bytes", rc, len);
len -= rc;
unsent += rc;
} else {
crm_debug("Sent %d bytes", rc);
break;
}
}
return rc < 0 ? rc : total_send;
}
| 166,161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.