instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void 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: transform_enable(PNG_CONST char *name)
{
/* Everything starts out enabled, so if we see an 'enable' disabled
* everything else the first time round.
*/
static int all_disabled = 0;
int found_it = 0;
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 1;
found_it = 1;
}
else if (!all_disabled)
list->enable = 0;
list = list->list;
}
all_disabled = 1;
if (!found_it)
{
fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
name);
exit(99);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | transform_enable(PNG_CONST char *name)
image_transform_png_set_invert_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type & 4)
that->alpha_inverted = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_invert_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* Only has an effect on pixels with alpha: */
return (colour_type & 4) != 0;
}
IT(invert_alpha);
#undef PT
#define PT ITSTRUCT(invert_alpha)
#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
/* png_set_bgr */
#ifdef PNG_READ_BGR_SUPPORTED
/* Swap R,G,B channels to order B,G,R.
*
* png_set_bgr(png_structrp png_ptr)
*
* This only has an effect on RGB and RGBA pixels.
*/
static void
image_transform_png_set_bgr_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_bgr(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_bgr_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_RGBA)
that->swap_rgb = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_bgr_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_RGBA;
}
IT(bgr);
#undef PT
#define PT ITSTRUCT(bgr)
#endif /* PNG_READ_BGR_SUPPORTED */
/* png_set_swap_alpha */
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
/* Put the alpha channel first.
*
* png_set_swap_alpha(png_structrp png_ptr)
*
* This only has an effect on GA and RGBA pixels.
*/
static void
image_transform_png_set_swap_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_swap_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_swap_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_GA ||
that->colour_type == PNG_COLOR_TYPE_RGBA)
that->alpha_first = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_swap_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type == PNG_COLOR_TYPE_GA ||
colour_type == PNG_COLOR_TYPE_RGBA;
}
IT(swap_alpha);
#undef PT
#define PT ITSTRUCT(swap_alpha)
#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
/* png_set_swap */
#ifdef PNG_READ_SWAP_SUPPORTED
/* Byte swap 16-bit components.
*
* png_set_swap(png_structrp png_ptr)
*/
static void
image_transform_png_set_swap_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_swap(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_swap_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
that->swap16 = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_swap_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth == 16;
}
IT(swap);
#undef PT
#define PT ITSTRUCT(swap)
#endif /* PNG_READ_SWAP_SUPPORTED */
#ifdef PNG_READ_FILLER_SUPPORTED
/* Add a filler byte to 8-bit Gray or 24-bit RGB images.
*
* png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
*
* Flags:
*
* PNG_FILLER_BEFORE
* PNG_FILLER_AFTER
*/
#define data ITDATA(filler)
static struct
{
png_uint_32 filler;
int flags;
} data;
static void
image_transform_png_set_filler_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Need a random choice for 'before' and 'after' as well as for the
* filler. The 'filler' value has all 32 bits set, but only bit_depth
* will be used. At this point we don't know bit_depth.
*/
RANDOMIZE(data.filler);
data.flags = random_choice();
png_set_filler(pp, data.filler, data.flags);
/* The standard display handling stuff also needs to know that
* there is a filler, so set that here.
*/
that->this.filler = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_filler_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth >= 8 &&
(that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_GRAY))
{
const unsigned int max = (1U << that->bit_depth)-1;
that->alpha = data.filler & max;
that->alphaf = ((double)that->alpha) / max;
that->alphae = 0;
/* The filler has been stored in the alpha channel, we must record
* that this has been done for the checking later on, the color
* type is faked to have an alpha channel, but libpng won't report
* this; the app has to know the extra channel is there and this
* was recording in standard_display::filler above.
*/
that->colour_type |= 4; /* alpha added */
that->alpha_first = data.flags == PNG_FILLER_BEFORE;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_filler_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_GRAY);
}
#undef data
IT(filler);
#undef PT
#define PT ITSTRUCT(filler)
/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
#define data ITDATA(add_alpha)
static struct
{
png_uint_32 filler;
int flags;
} data;
static void
image_transform_png_set_add_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Need a random choice for 'before' and 'after' as well as for the
* filler. The 'filler' value has all 32 bits set, but only bit_depth
* will be used. At this point we don't know bit_depth.
*/
RANDOMIZE(data.filler);
data.flags = random_choice();
png_set_add_alpha(pp, data.filler, data.flags);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_add_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth >= 8 &&
(that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_GRAY))
{
const unsigned int max = (1U << that->bit_depth)-1;
that->alpha = data.filler & max;
that->alphaf = ((double)that->alpha) / max;
that->alphae = 0;
that->colour_type |= 4; /* alpha added */
that->alpha_first = data.flags == PNG_FILLER_BEFORE;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_add_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_GRAY);
}
#undef data
IT(add_alpha);
#undef PT
#define PT ITSTRUCT(add_alpha)
#endif /* PNG_READ_FILLER_SUPPORTED */
/* png_set_packing */
#ifdef PNG_READ_PACK_SUPPORTED
/* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
*
* png_set_packing(png_structrp png_ptr)
*
* This should only affect grayscale and palette images with less than 8 bits
* per pixel.
*/
static void
image_transform_png_set_packing_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_packing(pp);
that->unpacked = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_packing_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* The general expand case depends on what the colour type is,
* low bit-depth pixel values are unpacked into bytes without
* scaling, so sample_depth is not changed.
*/
if (that->bit_depth < 8) /* grayscale or palette */
that->bit_depth = 8;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_packing_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* Nothing should happen unless the bit depth is less than 8: */
return bit_depth < 8;
}
IT(packing);
#undef PT
#define PT ITSTRUCT(packing)
#endif /* PNG_READ_PACK_SUPPORTED */
/* png_set_packswap */
#ifdef PNG_READ_PACKSWAP_SUPPORTED
/* Swap pixels packed into bytes; reverses the order on screen so that
* the high order bits correspond to the rightmost pixels.
*
* png_set_packswap(png_structrp png_ptr)
*/
static void
image_transform_png_set_packswap_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_packswap(pp);
that->this.littleendian = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_packswap_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth < 8)
that->littleendian = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_packswap_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth < 8;
}
IT(packswap);
#undef PT
#define PT ITSTRUCT(packswap)
#endif /* PNG_READ_PACKSWAP_SUPPORTED */
/* png_set_invert_mono */
#ifdef PNG_READ_INVERT_MONO_SUPPORTED
/* Invert the gray channel
*
* png_set_invert_mono(png_structrp png_ptr)
*/
static void
image_transform_png_set_invert_mono_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_invert_mono(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_invert_mono_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type & 4)
that->mono_inverted = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_invert_mono_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* Only has an effect on pixels with no colour: */
return (colour_type & 2) == 0;
}
IT(invert_mono);
#undef PT
#define PT ITSTRUCT(invert_mono)
#endif /* PNG_READ_INVERT_MONO_SUPPORTED */
#ifdef PNG_READ_SHIFT_SUPPORTED
/* png_set_shift(png_structp, png_const_color_8p true_bits)
*
* The output pixels will be shifted by the given true_bits
* values.
*/
#define data ITDATA(shift)
static png_color_8 data;
static void
image_transform_png_set_shift_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Get a random set of shifts. The shifts need to do something
* to test the transform, so they are limited to the bit depth
* of the input image. Notice that in the following the 'gray'
* field is randomized independently. This acts as a check that
* libpng does use the correct field.
*/
const unsigned int depth = that->this.bit_depth;
data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
png_set_shift(pp, &data);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_shift_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* Copy the correct values into the sBIT fields, libpng does not do
* anything to palette data:
*/
if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
{
that->sig_bits = 1;
/* The sBIT fields are reset to the values previously sent to
* png_set_shift according to the colour type.
* does.
*/
if (that->colour_type & 2) /* RGB channels */
{
that->red_sBIT = data.red;
that->green_sBIT = data.green;
that->blue_sBIT = data.blue;
}
else /* One grey channel */
that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
that->alpha_sBIT = data.alpha;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_shift_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type != PNG_COLOR_TYPE_PALETTE;
}
IT(shift);
#undef PT
#define PT ITSTRUCT(shift)
#endif /* PNG_READ_SHIFT_SUPPORTED */
#ifdef THIS_IS_THE_PROFORMA
static void
image_transform_png_set_@_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_@(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_@_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_@_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return 1;
}
IT(@);
#endif
/* This may just be 'end' if all the transforms are disabled! */
static image_transform *const image_transform_first = &PT;
static void
transform_enable(const char *name)
{
/* Everything starts out enabled, so if we see an 'enable' disabled
* everything else the first time round.
*/
static int all_disabled = 0;
int found_it = 0;
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 1;
found_it = 1;
}
else if (!all_disabled)
list->enable = 0;
list = list->list;
}
all_disabled = 1;
if (!found_it)
{
fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
name);
exit(99);
}
}
| 173,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,
u64 *cookie_ret, struct rds_mr **mr_ret)
{
struct rds_mr *mr = NULL, *found;
unsigned int nr_pages;
struct page **pages = NULL;
struct scatterlist *sg;
void *trans_private;
unsigned long flags;
rds_rdma_cookie_t cookie;
unsigned int nents;
long i;
int ret;
if (rs->rs_bound_addr == 0) {
ret = -ENOTCONN; /* XXX not a great errno */
goto out;
}
if (!rs->rs_transport->get_mr) {
ret = -EOPNOTSUPP;
goto out;
}
nr_pages = rds_pages_in_vec(&args->vec);
if (nr_pages == 0) {
ret = -EINVAL;
goto out;
}
/* Restrict the size of mr irrespective of underlying transport
* To account for unaligned mr regions, subtract one from nr_pages
*/
if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {
ret = -EMSGSIZE;
goto out;
}
rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n",
args->vec.addr, args->vec.bytes, nr_pages);
/* XXX clamp nr_pages to limit the size of this alloc? */
pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
if (!pages) {
ret = -ENOMEM;
goto out;
}
mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);
if (!mr) {
ret = -ENOMEM;
goto out;
}
refcount_set(&mr->r_refcount, 1);
RB_CLEAR_NODE(&mr->r_rb_node);
mr->r_trans = rs->rs_transport;
mr->r_sock = rs;
if (args->flags & RDS_RDMA_USE_ONCE)
mr->r_use_once = 1;
if (args->flags & RDS_RDMA_INVALIDATE)
mr->r_invalidate = 1;
if (args->flags & RDS_RDMA_READWRITE)
mr->r_write = 1;
/*
* Pin the pages that make up the user buffer and transfer the page
* pointers to the mr's sg array. We check to see if we've mapped
* the whole region after transferring the partial page references
* to the sg array so that we can have one page ref cleanup path.
*
* For now we have no flag that tells us whether the mapping is
* r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to
* the zero page.
*/
ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);
if (ret < 0)
goto out;
nents = ret;
sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);
if (!sg) {
ret = -ENOMEM;
goto out;
}
WARN_ON(!nents);
sg_init_table(sg, nents);
/* Stick all pages into the scatterlist */
for (i = 0 ; i < nents; i++)
sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);
rdsdebug("RDS: trans_private nents is %u\n", nents);
/* Obtain a transport specific MR. If this succeeds, the
* s/g list is now owned by the MR.
* Note that dma_map() implies that pending writes are
* flushed to RAM, so no dma_sync is needed here. */
trans_private = rs->rs_transport->get_mr(sg, nents, rs,
&mr->r_key);
if (IS_ERR(trans_private)) {
for (i = 0 ; i < nents; i++)
put_page(sg_page(&sg[i]));
kfree(sg);
ret = PTR_ERR(trans_private);
goto out;
}
mr->r_trans_private = trans_private;
rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n",
mr->r_key, (void *)(unsigned long) args->cookie_addr);
/* The user may pass us an unaligned address, but we can only
* map page aligned regions. So we keep the offset, and build
* a 64bit cookie containing <R_Key, offset> and pass that
* around. */
cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);
if (cookie_ret)
*cookie_ret = cookie;
if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {
ret = -EFAULT;
goto out;
}
/* Inserting the new MR into the rbtree bumps its
* reference count. */
spin_lock_irqsave(&rs->rs_rdma_lock, flags);
found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);
spin_unlock_irqrestore(&rs->rs_rdma_lock, flags);
BUG_ON(found && found != mr);
rdsdebug("RDS: get_mr key is %x\n", mr->r_key);
if (mr_ret) {
refcount_inc(&mr->r_refcount);
*mr_ret = mr;
}
ret = 0;
out:
kfree(pages);
if (mr)
rds_mr_put(mr);
return ret;
}
Commit Message: rds: Fix NULL pointer dereference in __rds_rdma_map
This is a fix for syzkaller719569, where memory registration was
attempted without any underlying transport being loaded.
Analysis of the case reveals that it is the setsockopt() RDS_GET_MR
(2) and RDS_GET_MR_FOR_DEST (7) that are vulnerable.
Here is an example stack trace when the bug is hit:
BUG: unable to handle kernel NULL pointer dereference at 00000000000000c0
IP: __rds_rdma_map+0x36/0x440 [rds]
PGD 2f93d03067 P4D 2f93d03067 PUD 2f93d02067 PMD 0
Oops: 0000 [#1] SMP
Modules linked in: bridge stp llc tun rpcsec_gss_krb5 nfsv4
dns_resolver nfs fscache rds binfmt_misc sb_edac intel_powerclamp
coretemp kvm_intel kvm irqbypass crct10dif_pclmul c rc32_pclmul
ghash_clmulni_intel pcbc aesni_intel crypto_simd glue_helper cryptd
iTCO_wdt mei_me sg iTCO_vendor_support ipmi_si mei ipmi_devintf nfsd
shpchp pcspkr i2c_i801 ioatd ma ipmi_msghandler wmi lpc_ich mfd_core
auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2
mgag200 i2c_algo_bit drm_kms_helper ixgbe syscopyarea ahci sysfillrect
sysimgblt libahci mdio fb_sys_fops ttm ptp libata sd_mod mlx4_core drm
crc32c_intel pps_core megaraid_sas i2c_core dca dm_mirror
dm_region_hash dm_log dm_mod
CPU: 48 PID: 45787 Comm: repro_set2 Not tainted 4.14.2-3.el7uek.x86_64 #2
Hardware name: Oracle Corporation ORACLE SERVER X5-2L/ASM,MOBO TRAY,2U, BIOS 31110000 03/03/2017
task: ffff882f9190db00 task.stack: ffffc9002b994000
RIP: 0010:__rds_rdma_map+0x36/0x440 [rds]
RSP: 0018:ffffc9002b997df0 EFLAGS: 00010202
RAX: 0000000000000000 RBX: ffff882fa2182580 RCX: 0000000000000000
RDX: 0000000000000000 RSI: ffffc9002b997e40 RDI: ffff882fa2182580
RBP: ffffc9002b997e30 R08: 0000000000000000 R09: 0000000000000002
R10: ffff885fb29e3838 R11: 0000000000000000 R12: ffff882fa2182580
R13: ffff882fa2182580 R14: 0000000000000002 R15: 0000000020000ffc
FS: 00007fbffa20b700(0000) GS:ffff882fbfb80000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000000000c0 CR3: 0000002f98a66006 CR4: 00000000001606e0
Call Trace:
rds_get_mr+0x56/0x80 [rds]
rds_setsockopt+0x172/0x340 [rds]
? __fget_light+0x25/0x60
? __fdget+0x13/0x20
SyS_setsockopt+0x80/0xe0
do_syscall_64+0x67/0x1b0
entry_SYSCALL64_slow_path+0x25/0x25
RIP: 0033:0x7fbff9b117f9
RSP: 002b:00007fbffa20aed8 EFLAGS: 00000293 ORIG_RAX: 0000000000000036
RAX: ffffffffffffffda RBX: 00000000000c84a4 RCX: 00007fbff9b117f9
RDX: 0000000000000002 RSI: 0000400000000114 RDI: 000000000000109b
RBP: 00007fbffa20af10 R08: 0000000000000020 R09: 00007fbff9dd7860
R10: 0000000020000ffc R11: 0000000000000293 R12: 0000000000000000
R13: 00007fbffa20b9c0 R14: 00007fbffa20b700 R15: 0000000000000021
Code: 41 56 41 55 49 89 fd 41 54 53 48 83 ec 18 8b 87 f0 02 00 00 48
89 55 d0 48 89 4d c8 85 c0 0f 84 2d 03 00 00 48 8b 87 00 03 00 00 <48>
83 b8 c0 00 00 00 00 0f 84 25 03 00 0 0 48 8b 06 48 8b 56 08
The fix is to check the existence of an underlying transport in
__rds_rdma_map().
Signed-off-by: Håkon Bugge <[email protected]>
Reported-by: syzbot <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,
u64 *cookie_ret, struct rds_mr **mr_ret)
{
struct rds_mr *mr = NULL, *found;
unsigned int nr_pages;
struct page **pages = NULL;
struct scatterlist *sg;
void *trans_private;
unsigned long flags;
rds_rdma_cookie_t cookie;
unsigned int nents;
long i;
int ret;
if (rs->rs_bound_addr == 0 || !rs->rs_transport) {
ret = -ENOTCONN; /* XXX not a great errno */
goto out;
}
if (!rs->rs_transport->get_mr) {
ret = -EOPNOTSUPP;
goto out;
}
nr_pages = rds_pages_in_vec(&args->vec);
if (nr_pages == 0) {
ret = -EINVAL;
goto out;
}
/* Restrict the size of mr irrespective of underlying transport
* To account for unaligned mr regions, subtract one from nr_pages
*/
if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {
ret = -EMSGSIZE;
goto out;
}
rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n",
args->vec.addr, args->vec.bytes, nr_pages);
/* XXX clamp nr_pages to limit the size of this alloc? */
pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
if (!pages) {
ret = -ENOMEM;
goto out;
}
mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);
if (!mr) {
ret = -ENOMEM;
goto out;
}
refcount_set(&mr->r_refcount, 1);
RB_CLEAR_NODE(&mr->r_rb_node);
mr->r_trans = rs->rs_transport;
mr->r_sock = rs;
if (args->flags & RDS_RDMA_USE_ONCE)
mr->r_use_once = 1;
if (args->flags & RDS_RDMA_INVALIDATE)
mr->r_invalidate = 1;
if (args->flags & RDS_RDMA_READWRITE)
mr->r_write = 1;
/*
* Pin the pages that make up the user buffer and transfer the page
* pointers to the mr's sg array. We check to see if we've mapped
* the whole region after transferring the partial page references
* to the sg array so that we can have one page ref cleanup path.
*
* For now we have no flag that tells us whether the mapping is
* r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to
* the zero page.
*/
ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);
if (ret < 0)
goto out;
nents = ret;
sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);
if (!sg) {
ret = -ENOMEM;
goto out;
}
WARN_ON(!nents);
sg_init_table(sg, nents);
/* Stick all pages into the scatterlist */
for (i = 0 ; i < nents; i++)
sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);
rdsdebug("RDS: trans_private nents is %u\n", nents);
/* Obtain a transport specific MR. If this succeeds, the
* s/g list is now owned by the MR.
* Note that dma_map() implies that pending writes are
* flushed to RAM, so no dma_sync is needed here. */
trans_private = rs->rs_transport->get_mr(sg, nents, rs,
&mr->r_key);
if (IS_ERR(trans_private)) {
for (i = 0 ; i < nents; i++)
put_page(sg_page(&sg[i]));
kfree(sg);
ret = PTR_ERR(trans_private);
goto out;
}
mr->r_trans_private = trans_private;
rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n",
mr->r_key, (void *)(unsigned long) args->cookie_addr);
/* The user may pass us an unaligned address, but we can only
* map page aligned regions. So we keep the offset, and build
* a 64bit cookie containing <R_Key, offset> and pass that
* around. */
cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);
if (cookie_ret)
*cookie_ret = cookie;
if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {
ret = -EFAULT;
goto out;
}
/* Inserting the new MR into the rbtree bumps its
* reference count. */
spin_lock_irqsave(&rs->rs_rdma_lock, flags);
found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);
spin_unlock_irqrestore(&rs->rs_rdma_lock, flags);
BUG_ON(found && found != mr);
rdsdebug("RDS: get_mr key is %x\n", mr->r_key);
if (mr_ret) {
refcount_inc(&mr->r_refcount);
*mr_ret = mr;
}
ret = 0;
out:
kfree(pages);
if (mr)
rds_mr_put(mr);
return ret;
}
| 169,309 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
Commit Message: fs: prevent page refcount overflow in pipe_buf_get
Change pipe_buf_get() to return a bool indicating whether it succeeded
in raising the refcount of the page (if the thing in the pipe is a page).
This removes another mechanism for overflowing the page refcount. All
callers converted to handle a failure.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Matthew Wilcox <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
| 170,231 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AudioOutputAuthorizationHandler::AudioOutputAuthorizationHandler(
media::AudioManager* audio_manager,
MediaStreamManager* media_stream_manager,
int render_process_id,
const std::string& salt)
: audio_manager_(audio_manager),
media_stream_manager_(media_stream_manager),
permission_checker_(base::MakeUnique<MediaDevicesPermissionChecker>()),
render_process_id_(render_process_id),
salt_(salt),
weak_factory_(this) {
DCHECK(media_stream_manager_);
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | AudioOutputAuthorizationHandler::AudioOutputAuthorizationHandler(
media::AudioSystem* audio_system,
MediaStreamManager* media_stream_manager,
int render_process_id,
const std::string& salt)
: audio_system_(audio_system),
media_stream_manager_(media_stream_manager),
permission_checker_(base::MakeUnique<MediaDevicesPermissionChecker>()),
render_process_id_(render_process_id),
salt_(salt),
weak_factory_(this) {
DCHECK(media_stream_manager_);
}
| 171,980 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xmkstemp(char **tmpname, char *dir)
{
char *localtmp;
char *tmpenv;
mode_t old_mode;
int fd, rc;
/* Some use cases must be capable of being moved atomically
* with rename(2), which is the reason why dir is here. */
if (dir != NULL)
tmpenv = dir;
else
tmpenv = getenv("TMPDIR");
if (tmpenv)
rc = asprintf(&localtmp, "%s/%s.XXXXXX", tmpenv,
program_invocation_short_name);
else
rc = asprintf(&localtmp, "%s/%s.XXXXXX", _PATH_TMP,
program_invocation_short_name);
if (rc < 0)
return -1;
old_mode = umask(077);
fd = mkostemp(localtmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC);
umask(old_mode);
if (fd == -1) {
free(localtmp);
localtmp = NULL;
}
*tmpname = localtmp;
return fd;
}
Commit Message: chsh, chfn, vipw: fix filenames collision
The utils when compiled WITHOUT libuser then mkostemp()ing
"/etc/%s.XXXXXX" where the filename prefix is argv[0] basename.
An attacker could repeatedly execute the util with modified argv[0]
and after many many attempts mkostemp() may generate suffix which
makes sense. The result maybe temporary file with name like rc.status
ld.so.preload or krb5.keytab, etc.
Note that distros usually use libuser based ch{sh,fn} or stuff from
shadow-utils.
It's probably very minor security bug.
Addresses: CVE-2015-5224
Signed-off-by: Karel Zak <[email protected]>
CWE ID: CWE-264 | int xmkstemp(char **tmpname, char *dir)
int xmkstemp(char **tmpname, const char *dir, const char *prefix)
{
char *localtmp;
const char *tmpenv;
mode_t old_mode;
int fd, rc;
/* Some use cases must be capable of being moved atomically
* with rename(2), which is the reason why dir is here. */
tmpenv = dir ? dir : getenv("TMPDIR");
if (!tmpenv)
tmpenv = _PATH_TMP;
rc = asprintf(&localtmp, "%s/%s.XXXXXX", tmpenv, prefix);
if (rc < 0)
return -1;
old_mode = umask(077);
fd = mkostemp(localtmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC);
umask(old_mode);
if (fd == -1) {
free(localtmp);
localtmp = NULL;
}
*tmpname = localtmp;
return fd;
}
| 168,873 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: monitor_init(void)
{
struct ssh *ssh = active_state; /* XXX */
struct monitor *mon;
mon = xcalloc(1, sizeof(*mon));
monitor_openfds(mon, 1);
/* Used to share zlib space across processes */
if (options.compression) {
mon->m_zback = mm_create(NULL, MM_MEMSIZE);
mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
/* Compression needs to share state across borders */
ssh_packet_set_compress_hooks(ssh, mon->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
return mon;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | monitor_init(void)
{
struct monitor *mon;
mon = xcalloc(1, sizeof(*mon));
monitor_openfds(mon, 1);
return mon;
}
| 168,649 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string utf16ToUtf8(const StringPiece16& utf16) {
ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
if (utf8Length <= 0) {
return {};
}
std::string utf8;
utf8.resize(utf8Length);
utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin());
return utf8;
}
Commit Message: Add bound checks to utf16_to_utf8
Test: ran libaapt2_tests64
Bug: 29250543
Change-Id: I1ebc017af623b6514cf0c493e8cd8e1d59ea26c3
(cherry picked from commit 4781057e78f63e0e99af109cebf3b6a78f4bfbb6)
CWE ID: CWE-119 | std::string utf16ToUtf8(const StringPiece16& utf16) {
ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
if (utf8Length <= 0) {
return {};
}
std::string utf8;
// Make room for '\0' explicitly.
utf8.resize(utf8Length + 1);
utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8Length + 1);
utf8.resize(utf8Length);
return utf8;
}
| 174,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: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
Commit Message:
CWE ID: CWE-17 | int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
| 164,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ResourceMultiBufferDataProvider::DidReceiveResponse(
const WebURLResponse& response) {
#if DCHECK_IS_ON()
std::string version;
switch (response.HttpVersion()) {
case WebURLResponse::kHTTPVersion_0_9:
version = "0.9";
break;
case WebURLResponse::kHTTPVersion_1_0:
version = "1.0";
break;
case WebURLResponse::kHTTPVersion_1_1:
version = "1.1";
break;
case WebURLResponse::kHTTPVersion_2_0:
version = "2.1";
break;
case WebURLResponse::kHTTPVersionUnknown:
version = "unknown";
break;
}
DVLOG(1) << "didReceiveResponse: HTTP/" << version << " "
<< response.HttpStatusCode();
#endif
DCHECK(active_loader_);
scoped_refptr<UrlData> destination_url_data(url_data_);
if (!redirects_to_.is_empty()) {
destination_url_data =
url_data_->url_index()->GetByUrl(redirects_to_, cors_mode_);
redirects_to_ = GURL();
}
base::Time last_modified;
if (base::Time::FromString(
response.HttpHeaderField("Last-Modified").Utf8().data(),
&last_modified)) {
destination_url_data->set_last_modified(last_modified);
}
destination_url_data->set_etag(
response.HttpHeaderField("ETag").Utf8().data());
destination_url_data->set_valid_until(base::Time::Now() +
GetCacheValidUntil(response));
uint32_t reasons = GetReasonsForUncacheability(response);
destination_url_data->set_cacheable(reasons == 0);
UMA_HISTOGRAM_BOOLEAN("Media.CacheUseful", reasons == 0);
int shift = 0;
int max_enum = base::bits::Log2Ceiling(kMaxReason);
while (reasons) {
DCHECK_LT(shift, max_enum); // Sanity check.
if (reasons & 0x1) {
UMA_HISTOGRAM_EXACT_LINEAR("Media.UncacheableReason", shift,
max_enum); // PRESUBMIT_IGNORE_UMA_MAX
}
reasons >>= 1;
++shift;
}
int64_t content_length = response.ExpectedContentLength();
bool end_of_file = false;
bool do_fail = false;
bytes_to_discard_ = 0;
if (destination_url_data->url().SchemeIsHTTPOrHTTPS()) {
bool partial_response = (response.HttpStatusCode() == kHttpPartialContent);
bool ok_response = (response.HttpStatusCode() == kHttpOK);
std::string accept_ranges =
response.HttpHeaderField("Accept-Ranges").Utf8();
if (accept_ranges.find("bytes") != std::string::npos)
destination_url_data->set_range_supported();
if (partial_response &&
VerifyPartialResponse(response, destination_url_data)) {
destination_url_data->set_range_supported();
} else if (ok_response) {
destination_url_data->set_length(content_length);
bytes_to_discard_ = byte_pos();
} else if (response.HttpStatusCode() == kHttpRangeNotSatisfiable) {
end_of_file = true;
} else {
active_loader_.reset();
do_fail = true;
}
} else {
destination_url_data->set_range_supported();
if (content_length != kPositionNotSpecified) {
destination_url_data->set_length(content_length + byte_pos());
}
}
if (!do_fail) {
destination_url_data =
url_data_->url_index()->TryInsert(destination_url_data);
}
destination_url_data->set_has_opaque_data(
network::cors::IsCORSCrossOriginResponseType(response.GetType()));
if (destination_url_data != url_data_) {
scoped_refptr<UrlData> old_url_data(url_data_);
destination_url_data->Use();
std::unique_ptr<DataProvider> self(
url_data_->multibuffer()->RemoveProvider(this));
url_data_ = destination_url_data.get();
url_data_->multibuffer()->AddProvider(std::move(self));
old_url_data->RedirectTo(destination_url_data);
}
if (do_fail) {
destination_url_data->Fail();
return; // "this" may be deleted now.
}
const GURL& original_url = response.WasFetchedViaServiceWorker()
? response.OriginalURLViaServiceWorker()
: response.Url();
if (!url_data_->ValidateDataOrigin(original_url.GetOrigin())) {
active_loader_.reset();
url_data_->Fail();
return; // "this" may be deleted now.
}
if (end_of_file) {
fifo_.push_back(DataBuffer::CreateEOSBuffer());
url_data_->multibuffer()->OnDataProviderEvent(this);
}
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | void ResourceMultiBufferDataProvider::DidReceiveResponse(
const WebURLResponse& response) {
#if DCHECK_IS_ON()
std::string version;
switch (response.HttpVersion()) {
case WebURLResponse::kHTTPVersion_0_9:
version = "0.9";
break;
case WebURLResponse::kHTTPVersion_1_0:
version = "1.0";
break;
case WebURLResponse::kHTTPVersion_1_1:
version = "1.1";
break;
case WebURLResponse::kHTTPVersion_2_0:
version = "2.1";
break;
case WebURLResponse::kHTTPVersionUnknown:
version = "unknown";
break;
}
DVLOG(1) << "didReceiveResponse: HTTP/" << version << " "
<< response.HttpStatusCode();
#endif
DCHECK(active_loader_);
scoped_refptr<UrlData> destination_url_data(url_data_);
if (!redirects_to_.is_empty()) {
destination_url_data =
url_data_->url_index()->GetByUrl(redirects_to_, cors_mode_);
redirects_to_ = GURL();
}
base::Time last_modified;
if (base::Time::FromString(
response.HttpHeaderField("Last-Modified").Utf8().data(),
&last_modified)) {
destination_url_data->set_last_modified(last_modified);
}
destination_url_data->set_etag(
response.HttpHeaderField("ETag").Utf8().data());
destination_url_data->set_valid_until(base::Time::Now() +
GetCacheValidUntil(response));
uint32_t reasons = GetReasonsForUncacheability(response);
destination_url_data->set_cacheable(reasons == 0);
UMA_HISTOGRAM_BOOLEAN("Media.CacheUseful", reasons == 0);
int shift = 0;
int max_enum = base::bits::Log2Ceiling(kMaxReason);
while (reasons) {
DCHECK_LT(shift, max_enum); // Sanity check.
if (reasons & 0x1) {
UMA_HISTOGRAM_EXACT_LINEAR("Media.UncacheableReason", shift,
max_enum); // PRESUBMIT_IGNORE_UMA_MAX
}
reasons >>= 1;
++shift;
}
int64_t content_length = response.ExpectedContentLength();
bool end_of_file = false;
bool do_fail = false;
// We get the response type here because aborting the loader may change it.
const auto response_type = response.GetType();
bytes_to_discard_ = 0;
if (destination_url_data->url().SchemeIsHTTPOrHTTPS()) {
bool partial_response = (response.HttpStatusCode() == kHttpPartialContent);
bool ok_response = (response.HttpStatusCode() == kHttpOK);
std::string accept_ranges =
response.HttpHeaderField("Accept-Ranges").Utf8();
if (accept_ranges.find("bytes") != std::string::npos)
destination_url_data->set_range_supported();
if (partial_response &&
VerifyPartialResponse(response, destination_url_data)) {
destination_url_data->set_range_supported();
} else if (ok_response) {
destination_url_data->set_length(content_length);
bytes_to_discard_ = byte_pos();
} else if (response.HttpStatusCode() == kHttpRangeNotSatisfiable) {
end_of_file = true;
} else {
active_loader_.reset();
do_fail = true;
}
} else {
destination_url_data->set_range_supported();
if (content_length != kPositionNotSpecified) {
destination_url_data->set_length(content_length + byte_pos());
}
}
if (!do_fail) {
destination_url_data =
url_data_->url_index()->TryInsert(destination_url_data);
}
// This is vital for security!
destination_url_data->set_is_cors_cross_origin(
network::cors::IsCORSCrossOriginResponseType(response_type));
if (destination_url_data != url_data_) {
scoped_refptr<UrlData> old_url_data(url_data_);
destination_url_data->Use();
std::unique_ptr<DataProvider> self(
url_data_->multibuffer()->RemoveProvider(this));
url_data_ = destination_url_data.get();
url_data_->multibuffer()->AddProvider(std::move(self));
old_url_data->RedirectTo(destination_url_data);
}
if (do_fail) {
destination_url_data->Fail();
return; // "this" may be deleted now.
}
const GURL& original_url = response.WasFetchedViaServiceWorker()
? response.OriginalURLViaServiceWorker()
: response.Url();
if (!url_data_->ValidateDataOrigin(original_url.GetOrigin())) {
active_loader_.reset();
url_data_->Fail();
return; // "this" may be deleted now.
}
if (end_of_file) {
fifo_.push_back(DataBuffer::CreateEOSBuffer());
url_data_->multibuffer()->OnDataProviderEvent(this);
}
}
| 172,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT16 count;
BITMAP_DATA* newdata;
count = bitmapUpdate->number * 2;
newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,
sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
Commit Message: Fixed CVE-2018-8786
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119 | BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT32 count = bitmapUpdate->number * 2;
BITMAP_DATA* newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,
sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
| 169,293 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WriteProfile(j_compress_ptr jpeg_info,Image *image)
{
const char
*name;
const StringInfo
*profile;
MagickBooleanType
iptc;
register ssize_t
i;
size_t
length,
tag_length;
StringInfo
*custom_profile;
/*
Save image profile as a APP marker.
*/
iptc=MagickFalse;
custom_profile=AcquireStringInfo(65535L);
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
register unsigned char
*p;
profile=GetImageProfile(image,name);
p=GetStringInfoDatum(custom_profile);
if (LocaleCompare(name,"EXIF") == 0)
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile)+i,
(unsigned int) length);
}
if (LocaleCompare(name,"ICC") == 0)
{
register unsigned char
*p;
tag_length=strlen(ICC_PROFILE);
p=GetStringInfoDatum(custom_profile);
(void) CopyMagickMemory(p,ICC_PROFILE,tag_length);
p[tag_length]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65519L);
p[12]=(unsigned char) ((i/65519L)+1);
p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1);
(void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i,
length);
jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+3));
}
}
if (((LocaleCompare(name,"IPTC") == 0) ||
(LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse))
{
size_t
roundup;
iptc=MagickTrue;
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65500L);
roundup=(size_t) (length & 0x01);
if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0)
{
(void) memcpy(p,"Photoshop 3.0 ",14);
tag_length=14;
}
else
{
(void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24);
tag_length=26;
p[24]=(unsigned char) (length >> 8);
p[25]=(unsigned char) (length & 0xff);
}
p[13]=0x00;
(void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length);
if (roundup != 0)
p[length+tag_length]='\0';
jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+roundup));
}
}
if (LocaleCompare(name,"XMP") == 0)
{
StringInfo
*xmp_profile;
/*
Add namespace to XMP profile.
*/
xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ ");
if (xmp_profile != (StringInfo *) NULL)
{
if (profile != (StringInfo *) NULL)
ConcatenateStringInfo(xmp_profile,profile);
GetStringInfoDatum(xmp_profile)[28]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,
GetStringInfoDatum(xmp_profile)+i,(unsigned int) length);
}
xmp_profile=DestroyStringInfo(xmp_profile);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile));
name=GetNextImageProfile(image);
}
custom_profile=DestroyStringInfo(custom_profile);
}
Commit Message: Changed the JPEG writer to raise a warning when the exif profile exceeds 65533 bytes and truncate it.
CWE ID: CWE-119 | static void WriteProfile(j_compress_ptr jpeg_info,Image *image)
{
const char
*name;
const StringInfo
*profile;
MagickBooleanType
iptc;
register ssize_t
i;
size_t
length,
tag_length;
StringInfo
*custom_profile;
/*
Save image profile as a APP marker.
*/
iptc=MagickFalse;
custom_profile=AcquireStringInfo(65535L);
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
register unsigned char
*p;
profile=GetImageProfile(image,name);
p=GetStringInfoDatum(custom_profile);
if (LocaleCompare(name,"EXIF") == 0)
{
length=GetStringInfoLength(profile);
if (length > 65533L)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderWarning,"ExifProfileSizeExceedsLimit",image->filename);
length=65533L;
}
jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile),
(unsigned int) length);
}
if (LocaleCompare(name,"ICC") == 0)
{
register unsigned char
*p;
tag_length=strlen(ICC_PROFILE);
p=GetStringInfoDatum(custom_profile);
(void) CopyMagickMemory(p,ICC_PROFILE,tag_length);
p[tag_length]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65519L);
p[12]=(unsigned char) ((i/65519L)+1);
p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1);
(void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i,
length);
jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+3));
}
}
if (((LocaleCompare(name,"IPTC") == 0) ||
(LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse))
{
size_t
roundup;
iptc=MagickTrue;
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65500L);
roundup=(size_t) (length & 0x01);
if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0)
{
(void) memcpy(p,"Photoshop 3.0 ",14);
tag_length=14;
}
else
{
(void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24);
tag_length=26;
p[24]=(unsigned char) (length >> 8);
p[25]=(unsigned char) (length & 0xff);
}
p[13]=0x00;
(void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length);
if (roundup != 0)
p[length+tag_length]='\0';
jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+roundup));
}
}
if (LocaleCompare(name,"XMP") == 0)
{
StringInfo
*xmp_profile;
/*
Add namespace to XMP profile.
*/
xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ ");
if (xmp_profile != (StringInfo *) NULL)
{
if (profile != (StringInfo *) NULL)
ConcatenateStringInfo(xmp_profile,profile);
GetStringInfoDatum(xmp_profile)[28]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,
GetStringInfoDatum(xmp_profile)+i,(unsigned int) length);
}
xmp_profile=DestroyStringInfo(xmp_profile);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile));
name=GetNextImageProfile(image);
}
custom_profile=DestroyStringInfo(custom_profile);
}
| 168,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void follow_dotdot(struct nameidata *nd)
{
if (!nd->root.mnt)
set_root(nd);
while(1) {
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
/* rare case of legitimate dget_parent()... */
nd->path.dentry = dget_parent(nd->path.dentry);
dput(old);
break;
}
if (!follow_up(&nd->path))
break;
}
follow_mount(&nd->path);
nd->inode = nd->path.dentry->d_inode;
}
Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root
In rare cases a directory can be renamed out from under a bind mount.
In those cases without special handling it becomes possible to walk up
the directory tree to the root dentry of the filesystem and down
from the root dentry to every other file or directory on the filesystem.
Like division by zero .. from an unconnected path can not be given
a useful semantic as there is no predicting at which path component
the code will realize it is unconnected. We certainly can not match
the current behavior as the current behavior is a security hole.
Therefore when encounting .. when following an unconnected path
return -ENOENT.
- Add a function path_connected to verify path->dentry is reachable
from path->mnt.mnt_root. AKA to validate that rename did not do
something nasty to the bind mount.
To avoid races path_connected must be called after following a path
component to it's next path component.
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-254 | static void follow_dotdot(struct nameidata *nd)
static int follow_dotdot(struct nameidata *nd)
{
if (!nd->root.mnt)
set_root(nd);
while(1) {
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
/* rare case of legitimate dget_parent()... */
nd->path.dentry = dget_parent(nd->path.dentry);
dput(old);
if (unlikely(!path_connected(&nd->path)))
return -ENOENT;
break;
}
if (!follow_up(&nd->path))
break;
}
follow_mount(&nd->path);
nd->inode = nd->path.dentry->d_inode;
return 0;
}
| 166,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sig_server_setup_fill_chatnet(IRC_SERVER_CONNECT_REC *conn,
IRC_CHATNET_REC *ircnet)
{
if (!IS_IRC_SERVER_CONNECT(conn))
return;
g_return_if_fail(IS_IRCNET(ircnet));
if (ircnet->alternate_nick != NULL) {
g_free_and_null(conn->alternate_nick);
conn->alternate_nick = g_strdup(ircnet->alternate_nick);
}
if (ircnet->usermode != NULL) {
g_free_and_null(conn->usermode);
conn->usermode = g_strdup(ircnet->usermode);
}
if (ircnet->max_kicks > 0) conn->max_kicks = ircnet->max_kicks;
if (ircnet->max_msgs > 0) conn->max_msgs = ircnet->max_msgs;
if (ircnet->max_modes > 0) conn->max_modes = ircnet->max_modes;
if (ircnet->max_whois > 0) conn->max_whois = ircnet->max_whois;
if (ircnet->max_cmds_at_once > 0)
conn->max_cmds_at_once = ircnet->max_cmds_at_once;
if (ircnet->cmd_queue_speed > 0)
conn->cmd_queue_speed = ircnet->cmd_queue_speed;
if (ircnet->max_query_chans > 0)
conn->max_query_chans = ircnet->max_query_chans;
/* Validate the SASL parameters filled by sig_chatnet_read() or cmd_network_add */
conn->sasl_mechanism = SASL_MECHANISM_NONE;
conn->sasl_username = NULL;
conn->sasl_password = NULL;
if (ircnet->sasl_mechanism != NULL) {
if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "plain")) {
/* The PLAIN method needs both the username and the password */
conn->sasl_mechanism = SASL_MECHANISM_PLAIN;
if (ircnet->sasl_username != NULL && *ircnet->sasl_username &&
ircnet->sasl_password != NULL && *ircnet->sasl_password) {
conn->sasl_username = ircnet->sasl_username;
conn->sasl_password = ircnet->sasl_password;
} else
g_warning("The fields sasl_username and sasl_password are either missing or empty");
}
else if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "external")) {
conn->sasl_mechanism = SASL_MECHANISM_EXTERNAL;
}
else
g_warning("Unsupported SASL mechanism \"%s\" selected", ircnet->sasl_mechanism);
}
}
Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect
copy sasl username and password values
CWE ID: CWE-416 | static void sig_server_setup_fill_chatnet(IRC_SERVER_CONNECT_REC *conn,
IRC_CHATNET_REC *ircnet)
{
if (!IS_IRC_SERVER_CONNECT(conn))
return;
g_return_if_fail(IS_IRCNET(ircnet));
if (ircnet->alternate_nick != NULL) {
g_free_and_null(conn->alternate_nick);
conn->alternate_nick = g_strdup(ircnet->alternate_nick);
}
if (ircnet->usermode != NULL) {
g_free_and_null(conn->usermode);
conn->usermode = g_strdup(ircnet->usermode);
}
if (ircnet->max_kicks > 0) conn->max_kicks = ircnet->max_kicks;
if (ircnet->max_msgs > 0) conn->max_msgs = ircnet->max_msgs;
if (ircnet->max_modes > 0) conn->max_modes = ircnet->max_modes;
if (ircnet->max_whois > 0) conn->max_whois = ircnet->max_whois;
if (ircnet->max_cmds_at_once > 0)
conn->max_cmds_at_once = ircnet->max_cmds_at_once;
if (ircnet->cmd_queue_speed > 0)
conn->cmd_queue_speed = ircnet->cmd_queue_speed;
if (ircnet->max_query_chans > 0)
conn->max_query_chans = ircnet->max_query_chans;
/* Validate the SASL parameters filled by sig_chatnet_read() or cmd_network_add */
conn->sasl_mechanism = SASL_MECHANISM_NONE;
conn->sasl_username = NULL;
conn->sasl_password = NULL;
if (ircnet->sasl_mechanism != NULL) {
if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "plain")) {
/* The PLAIN method needs both the username and the password */
conn->sasl_mechanism = SASL_MECHANISM_PLAIN;
if (ircnet->sasl_username != NULL && *ircnet->sasl_username &&
ircnet->sasl_password != NULL && *ircnet->sasl_password) {
conn->sasl_username = g_strdup(ircnet->sasl_username);
conn->sasl_password = g_strdup(ircnet->sasl_password);
} else
g_warning("The fields sasl_username and sasl_password are either missing or empty");
}
else if (!g_ascii_strcasecmp(ircnet->sasl_mechanism, "external")) {
conn->sasl_mechanism = SASL_MECHANISM_EXTERNAL;
}
else
g_warning("Unsupported SASL mechanism \"%s\" selected", ircnet->sasl_mechanism);
}
}
| 169,644 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
size_t imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
unsigned imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
| 172,503 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 encode_msg(struct sip_msg *msg,char *payload,int len)
{
int i,j,k,u,request;
unsigned short int h;
struct hdr_field* hf;
struct msg_start* ms;
struct sip_uri miuri;
char *myerror=NULL;
ptrdiff_t diff;
if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN)
return -1;
if(parse_headers(msg,HDR_EOH_F,0)<0){
myerror="in parse_headers";
goto error;
}
memset(payload,0,len);
ms=&msg->first_line;
if(ms->type == SIP_REQUEST)
request=1;
else if(ms->type == SIP_REPLY)
request=0;
else{
myerror="message is neither request nor response";
goto error;
}
if(request) {
for(h=0;h<32;j=(0x01<<h),h++)
if(j & ms->u.request.method_value)
break;
} else {
h=(unsigned short)(ms->u.reply.statuscode);
}
if(h==32){/*statuscode wont be 32...*/
myerror="unknown message type\n";
goto error;
}
h=htons(h);
/*first goes the message code type*/
memcpy(payload,&h,2);
h=htons((unsigned short int)msg->len);
/*then goes the message start idx, but we'll put it later*/
/*then goes the message length (we hope it to be less than 65535 bytes...)*/
memcpy(&payload[MSG_LEN_IDX],&h,2);
/*then goes the content start index (starting from SIP MSG START)*/
if(0>(diff=(get_body(msg)-(msg->buf)))){
myerror="body starts before the message (uh ?)";
goto error;
}else
h=htons((unsigned short int)diff);
memcpy(payload+CONTENT_IDX,&h,2);
payload[METHOD_CODE_IDX]=(unsigned char)(request?
(ms->u.request.method.s-msg->buf):
(ms->u.reply.status.s-msg->buf));
payload[METHOD_CODE_IDX+1]=(unsigned char)(request?
(ms->u.request.method.len):
(ms->u.reply.status.len));
payload[URI_REASON_IDX]=(unsigned char)(request?
(ms->u.request.uri.s-msg->buf):
(ms->u.reply.reason.s-msg->buf));
payload[URI_REASON_IDX+1]=(unsigned char)(request?
(ms->u.request.uri.len):
(ms->u.reply.reason.len));
payload[VERSION_IDX]=(unsigned char)(request?
(ms->u.request.version.s-msg->buf):
(ms->u.reply.version.s-msg->buf));
if(request){
if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){
LM_ERR("<%.*s>\n",ms->u.request.uri.len,ms->u.request.uri.s);
myerror="while parsing the R-URI";
goto error;
}
if(0>(j=encode_uri2(msg->buf,
ms->u.request.method.s-msg->buf+ms->len,
ms->u.request.uri,&miuri,
(unsigned char*)&payload[REQUEST_URI_IDX+1])))
{
myerror="ENCODE_MSG: ERROR while encoding the R-URI";
goto error;
}
payload[REQUEST_URI_IDX]=(unsigned char)j;
k=REQUEST_URI_IDX+1+j;
}else
k=REQUEST_URI_IDX;
u=k;
k++;
for(i=0,hf=msg->headers;hf;hf=hf->next,i++);
i++;/*we do as if there was an extra header, that marks the end of
the previous header in the headers hashtable(read below)*/
j=k+3*i;
for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){
payload[k]=(unsigned char)(hf->type & 0xFF);
h=htons(j);
/*now goes a payload-based-ptr to where the header-code starts*/
memcpy(&payload[k+1],&h,2);
/*TODO fix this... fixed with k-=3?*/
if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){
LM_ERR("encoding header %.*s\n",hf->name.len,hf->name.s);
goto error;
k-=3;
continue;
}
j+=(unsigned short int)i;
}
/*now goes the number of headers that have been found, right after the meta-msg-section*/
payload[u]=(unsigned char)((k-u-1)/3);
j=htons(j);
/*now copy the number of bytes that the headers-meta-section has occupied,right afther
* headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...]
* this is to know where the LAST header ends, since the length of each header-struct
* is calculated substracting the nextHeaderStart - presentHeaderStart
* the k+1 is because payload[k] is usually the letter*/
memcpy(&payload[k+1],&j,2);
k+=3;
j=ntohs(j);
/*now we copy the headers-meta-section after the msg-headers-meta-section*/
/*memcpy(&payload[k],payload2,j);*/
/*j+=k;*/
/*pkg_free(payload2);*/
/*now we copy the actual message after the headers-meta-section*/
memcpy(&payload[j],msg->buf,msg->len);
LM_DBG("msglen = %d,msg starts at %d\n",msg->len,j);
j=htons(j);
/*now we copy at the beginning, the index to where the actual message starts*/
memcpy(&payload[MSG_START_IDX],&j,2);
return GET_PAY_SIZE( payload );
error:
LM_ERR("%s\n",myerror);
return -1;
}
Commit Message: seas: safety check for target buffer size before copying message in encode_msg()
- avoid buffer overflow for large SIP messages
- reported by Stelios Tsampas
CWE ID: CWE-119 | int encode_msg(struct sip_msg *msg,char *payload,int len)
{
int i,j,k,u,request;
unsigned short int h;
struct hdr_field* hf;
struct msg_start* ms;
struct sip_uri miuri;
char *myerror=NULL;
ptrdiff_t diff;
if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN)
return -1;
if(parse_headers(msg,HDR_EOH_F,0)<0){
myerror="in parse_headers";
goto error;
}
memset(payload,0,len);
ms=&msg->first_line;
if(ms->type == SIP_REQUEST)
request=1;
else if(ms->type == SIP_REPLY)
request=0;
else{
myerror="message is neither request nor response";
goto error;
}
if(request) {
for(h=0;h<32;j=(0x01<<h),h++)
if(j & ms->u.request.method_value)
break;
} else {
h=(unsigned short)(ms->u.reply.statuscode);
}
if(h==32){/*statuscode wont be 32...*/
myerror="unknown message type\n";
goto error;
}
h=htons(h);
/*first goes the message code type*/
memcpy(payload,&h,2);
h=htons((unsigned short int)msg->len);
/*then goes the message start idx, but we'll put it later*/
/*then goes the message length (we hope it to be less than 65535 bytes...)*/
memcpy(&payload[MSG_LEN_IDX],&h,2);
/*then goes the content start index (starting from SIP MSG START)*/
if(0>(diff=(get_body(msg)-(msg->buf)))){
myerror="body starts before the message (uh ?)";
goto error;
}else
h=htons((unsigned short int)diff);
memcpy(payload+CONTENT_IDX,&h,2);
payload[METHOD_CODE_IDX]=(unsigned char)(request?
(ms->u.request.method.s-msg->buf):
(ms->u.reply.status.s-msg->buf));
payload[METHOD_CODE_IDX+1]=(unsigned char)(request?
(ms->u.request.method.len):
(ms->u.reply.status.len));
payload[URI_REASON_IDX]=(unsigned char)(request?
(ms->u.request.uri.s-msg->buf):
(ms->u.reply.reason.s-msg->buf));
payload[URI_REASON_IDX+1]=(unsigned char)(request?
(ms->u.request.uri.len):
(ms->u.reply.reason.len));
payload[VERSION_IDX]=(unsigned char)(request?
(ms->u.request.version.s-msg->buf):
(ms->u.reply.version.s-msg->buf));
if(request){
if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){
LM_ERR("<%.*s>\n",ms->u.request.uri.len,ms->u.request.uri.s);
myerror="while parsing the R-URI";
goto error;
}
if(0>(j=encode_uri2(msg->buf,
ms->u.request.method.s-msg->buf+ms->len,
ms->u.request.uri,&miuri,
(unsigned char*)&payload[REQUEST_URI_IDX+1])))
{
myerror="ENCODE_MSG: ERROR while encoding the R-URI";
goto error;
}
payload[REQUEST_URI_IDX]=(unsigned char)j;
k=REQUEST_URI_IDX+1+j;
}else
k=REQUEST_URI_IDX;
u=k;
k++;
for(i=0,hf=msg->headers;hf;hf=hf->next,i++);
i++;/*we do as if there was an extra header, that marks the end of
the previous header in the headers hashtable(read below)*/
j=k+3*i;
for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){
payload[k]=(unsigned char)(hf->type & 0xFF);
h=htons(j);
/*now goes a payload-based-ptr to where the header-code starts*/
memcpy(&payload[k+1],&h,2);
/*TODO fix this... fixed with k-=3?*/
if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){
LM_ERR("encoding header %.*s\n",hf->name.len,hf->name.s);
goto error;
k-=3;
continue;
}
j+=(unsigned short int)i;
}
/*now goes the number of headers that have been found, right after the meta-msg-section*/
payload[u]=(unsigned char)((k-u-1)/3);
j=htons(j);
/*now copy the number of bytes that the headers-meta-section has occupied,right afther
* headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...]
* this is to know where the LAST header ends, since the length of each header-struct
* is calculated substracting the nextHeaderStart - presentHeaderStart
* the k+1 is because payload[k] is usually the letter*/
memcpy(&payload[k+1],&j,2);
k+=3;
j=ntohs(j);
/*now we copy the headers-meta-section after the msg-headers-meta-section*/
/*memcpy(&payload[k],payload2,j);*/
/*j+=k;*/
/*pkg_free(payload2);*/
/*now we copy the actual message after the headers-meta-section*/
if(len < j + msg->len + 1) {
LM_ERR("not enough space to encode sip message\n");
return -1;
}
memcpy(&payload[j],msg->buf,msg->len);
LM_DBG("msglen = %d,msg starts at %d\n",msg->len,j);
j=htons(j);
/*now we copy at the beginning, the index to where the actual message starts*/
memcpy(&payload[MSG_START_IDX],&j,2);
return GET_PAY_SIZE( payload );
error:
LM_ERR("%s\n",myerror);
return -1;
}
| 167,411 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{
rdpCredssp* credssp;
credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp));
ZeroMemory(credssp, sizeof(rdpCredssp));
if (credssp != NULL)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
credssp->instance = instance;
credssp->settings = settings;
credssp->server = settings->ServerMode;
credssp->transport = transport;
credssp->send_seq_num = 0;
credssp->recv_seq_num = 0;
ZeroMemory(&credssp->negoToken, sizeof(SecBuffer));
ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));
ZeroMemory(&credssp->authInfo, sizeof(SecBuffer));
SecInvalidateHandle(&credssp->context);
if (credssp->server)
{
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"),
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
if (status == ERROR_SUCCESS)
{
credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
(BYTE*) credssp->SspiModule, &dwSize);
if (status == ERROR_SUCCESS)
{
_tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule);
RegCloseKey(hKey);
}
}
}
}
}
return credssp;
}
| 167,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: OmniboxPopupViewGtk::OmniboxPopupViewGtk(const gfx::Font& font,
OmniboxView* omnibox_view,
AutocompleteEditModel* edit_model,
GtkWidget* location_bar)
: model_(new AutocompletePopupModel(this, edit_model)),
omnibox_view_(omnibox_view),
location_bar_(location_bar),
window_(gtk_window_new(GTK_WINDOW_POPUP)),
layout_(NULL),
theme_service_(ThemeServiceGtk::GetFrom(edit_model->profile())),
font_(font.DeriveFont(kEditFontAdjust)),
ignore_mouse_drag_(false),
opened_(false) {
gtk_widget_set_can_focus(window_, FALSE);
gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
gtk_widget_set_app_paintable(window_, TRUE);
gtk_widget_set_double_buffered(window_, TRUE);
layout_ = gtk_widget_create_pango_layout(window_, NULL);
pango_layout_set_auto_dir(layout_, FALSE);
pango_layout_set_ellipsize(layout_, PANGO_ELLIPSIZE_END);
gtk_widget_add_events(window_, GDK_BUTTON_MOTION_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK);
g_signal_connect(window_, "motion-notify-event",
G_CALLBACK(HandleMotionThunk), this);
g_signal_connect(window_, "button-press-event",
G_CALLBACK(HandleButtonPressThunk), this);
g_signal_connect(window_, "button-release-event",
G_CALLBACK(HandleButtonReleaseThunk), this);
g_signal_connect(window_, "expose-event",
G_CALLBACK(HandleExposeThunk), this);
registrar_.Add(this,
chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(theme_service_));
theme_service_->InitThemesFor(this);
}
Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model.
BUG=123530
TEST=none
Review URL: http://codereview.chromium.org/10103012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | OmniboxPopupViewGtk::OmniboxPopupViewGtk(const gfx::Font& font,
OmniboxView* omnibox_view,
AutocompleteEditModel* edit_model,
GtkWidget* location_bar)
: signal_registrar_(new ui::GtkSignalRegistrar),
model_(new AutocompletePopupModel(this, edit_model)),
omnibox_view_(omnibox_view),
location_bar_(location_bar),
window_(gtk_window_new(GTK_WINDOW_POPUP)),
layout_(NULL),
theme_service_(ThemeServiceGtk::GetFrom(edit_model->profile())),
font_(font.DeriveFont(kEditFontAdjust)),
ignore_mouse_drag_(false),
opened_(false) {
gtk_widget_set_can_focus(window_, FALSE);
gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
gtk_widget_set_app_paintable(window_, TRUE);
gtk_widget_set_double_buffered(window_, TRUE);
layout_ = gtk_widget_create_pango_layout(window_, NULL);
pango_layout_set_auto_dir(layout_, FALSE);
pango_layout_set_ellipsize(layout_, PANGO_ELLIPSIZE_END);
gtk_widget_add_events(window_, GDK_BUTTON_MOTION_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK);
signal_registrar_->Connect(window_, "motion-notify-event",
G_CALLBACK(HandleMotionThunk), this);
signal_registrar_->Connect(window_, "button-press-event",
G_CALLBACK(HandleButtonPressThunk), this);
signal_registrar_->Connect(window_, "button-release-event",
G_CALLBACK(HandleButtonReleaseThunk), this);
signal_registrar_->Connect(window_, "expose-event",
G_CALLBACK(HandleExposeThunk), this);
registrar_.Add(this,
chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(theme_service_));
theme_service_->InitThemesFor(this);
}
| 171,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 bool access_pmu_evcntr(struct kvm_vcpu *vcpu,
struct sys_reg_params *p,
const struct sys_reg_desc *r)
{
u64 idx;
if (!kvm_arm_pmu_v3_ready(vcpu))
return trap_raz_wi(vcpu, p, r);
if (r->CRn == 9 && r->CRm == 13) {
if (r->Op2 == 2) {
/* PMXEVCNTR_EL0 */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = vcpu_sys_reg(vcpu, PMSELR_EL0)
& ARMV8_PMU_COUNTER_MASK;
} else if (r->Op2 == 0) {
/* PMCCNTR_EL0 */
if (pmu_access_cycle_counter_el0_disabled(vcpu))
return false;
idx = ARMV8_PMU_CYCLE_IDX;
} else {
BUG();
}
} else if (r->CRn == 14 && (r->CRm & 12) == 8) {
/* PMEVCNTRn_EL0 */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = ((r->CRm & 3) << 3) | (r->Op2 & 7);
} else {
BUG();
}
if (!pmu_counter_idx_valid(vcpu, idx))
return false;
if (p->is_write) {
if (pmu_access_el0_disabled(vcpu))
return false;
kvm_pmu_set_counter_value(vcpu, idx, p->regval);
} else {
p->regval = kvm_pmu_get_counter_value(vcpu, idx);
}
return true;
}
Commit Message: arm64: KVM: pmu: Fix AArch32 cycle counter access
We're missing the handling code for the cycle counter accessed
from a 32bit guest, leading to unexpected results.
Cc: [email protected] # 4.6+
Signed-off-by: Wei Huang <[email protected]>
Signed-off-by: Marc Zyngier <[email protected]>
CWE ID: CWE-617 | static bool access_pmu_evcntr(struct kvm_vcpu *vcpu,
struct sys_reg_params *p,
const struct sys_reg_desc *r)
{
u64 idx;
if (!kvm_arm_pmu_v3_ready(vcpu))
return trap_raz_wi(vcpu, p, r);
if (r->CRn == 9 && r->CRm == 13) {
if (r->Op2 == 2) {
/* PMXEVCNTR_EL0 */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = vcpu_sys_reg(vcpu, PMSELR_EL0)
& ARMV8_PMU_COUNTER_MASK;
} else if (r->Op2 == 0) {
/* PMCCNTR_EL0 */
if (pmu_access_cycle_counter_el0_disabled(vcpu))
return false;
idx = ARMV8_PMU_CYCLE_IDX;
} else {
return false;
}
} else if (r->CRn == 0 && r->CRm == 9) {
/* PMCCNTR */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = ARMV8_PMU_CYCLE_IDX;
} else if (r->CRn == 14 && (r->CRm & 12) == 8) {
/* PMEVCNTRn_EL0 */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = ((r->CRm & 3) << 3) | (r->Op2 & 7);
} else {
return false;
}
if (!pmu_counter_idx_valid(vcpu, idx))
return false;
if (p->is_write) {
if (pmu_access_el0_disabled(vcpu))
return false;
kvm_pmu_set_counter_value(vcpu, idx, p->regval);
} else {
p->regval = kvm_pmu_get_counter_value(vcpu, idx);
}
return true;
}
| 167,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: void RenderFrameImpl::OnSelectPopupMenuItems(
bool canceled,
const std::vector<int>& selected_indices) {
if (!external_popup_menu_)
return;
blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItems(canceled, selected_indices);
external_popup_menu_.reset();
}
Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s)
ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl.
We need to reset external_popup_menu_ before calling it.
Bug: 912211
Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc
Reviewed-on: https://chromium-review.googlesource.com/c/1381325
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618026}
CWE ID: CWE-416 | void RenderFrameImpl::OnSelectPopupMenuItems(
bool canceled,
const std::vector<int>& selected_indices) {
if (!external_popup_menu_)
return;
blink::WebScopedUserGesture gesture(frame_);
// We need to reset |external_popup_menu_| before calling DidSelectItems(),
// which might delete |this|.
// See ExternalPopupMenuRemoveTest.RemoveFrameOnChange
std::unique_ptr<ExternalPopupMenu> popup;
popup.swap(external_popup_menu_);
popup->DidSelectItems(canceled, selected_indices);
}
| 173,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ResourceCoordinatorService::OnStart() {
ref_factory_.reset(new service_manager::ServiceContextRefFactory(
base::Bind(&service_manager::ServiceContext::RequestQuit,
base::Unretained(context()))));
ukm_recorder_ = ukm::MojoUkmRecorder::Create(context()->connector());
registry_.AddInterface(
base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface,
base::Unretained(&introspector_)));
auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>();
registry_.AddInterface(
base::Bind(&PageSignalGeneratorImpl::BindToInterface,
base::Unretained(page_signal_generator_impl.get())));
coordination_unit_manager_.RegisterObserver(
std::move(page_signal_generator_impl));
coordination_unit_manager_.RegisterObserver(
std::make_unique<MetricsCollector>());
coordination_unit_manager_.RegisterObserver(
std::make_unique<IPCVolumeReporter>(
std::make_unique<base::OneShotTimer>()));
coordination_unit_manager_.OnStart(®istry_, ref_factory_.get());
coordination_unit_manager_.set_ukm_recorder(ukm_recorder_.get());
memory_instrumentation_coordinator_ =
std::make_unique<memory_instrumentation::CoordinatorImpl>(
context()->connector());
registry_.AddInterface(base::BindRepeating(
&memory_instrumentation::CoordinatorImpl::BindCoordinatorRequest,
base::Unretained(memory_instrumentation_coordinator_.get())));
tracing_agent_registry_ = std::make_unique<tracing::AgentRegistry>();
registry_.AddInterface(
base::BindRepeating(&tracing::AgentRegistry::BindAgentRegistryRequest,
base::Unretained(tracing_agent_registry_.get())));
tracing_coordinator_ = std::make_unique<tracing::Coordinator>();
registry_.AddInterface(
base::BindRepeating(&tracing::Coordinator::BindCoordinatorRequest,
base::Unretained(tracing_coordinator_.get())));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void ResourceCoordinatorService::OnStart() {
ref_factory_.reset(new service_manager::ServiceContextRefFactory(
base::Bind(&service_manager::ServiceContext::RequestQuit,
base::Unretained(context()))));
ukm_recorder_ = ukm::MojoUkmRecorder::Create(context()->connector());
registry_.AddInterface(
base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface,
base::Unretained(&introspector_)));
auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>();
registry_.AddInterface(
base::Bind(&PageSignalGeneratorImpl::BindToInterface,
base::Unretained(page_signal_generator_impl.get())));
coordination_unit_manager_.RegisterObserver(
std::move(page_signal_generator_impl));
coordination_unit_manager_.RegisterObserver(
std::make_unique<MetricsCollector>());
coordination_unit_manager_.RegisterObserver(
std::make_unique<IPCVolumeReporter>(
std::make_unique<base::OneShotTimer>()));
coordination_unit_manager_.OnStart(®istry_, ref_factory_.get());
coordination_unit_manager_.set_ukm_recorder(ukm_recorder_.get());
memory_instrumentation_coordinator_ =
std::make_unique<memory_instrumentation::CoordinatorImpl>(
context()->connector());
registry_.AddInterface(base::BindRepeating(
&memory_instrumentation::CoordinatorImpl::BindCoordinatorRequest,
base::Unretained(memory_instrumentation_coordinator_.get())));
registry_.AddInterface(base::BindRepeating(
&memory_instrumentation::CoordinatorImpl::BindHeapProfilerHelperRequest,
base::Unretained(memory_instrumentation_coordinator_.get())));
tracing_agent_registry_ = std::make_unique<tracing::AgentRegistry>();
registry_.AddInterface(
base::BindRepeating(&tracing::AgentRegistry::BindAgentRegistryRequest,
base::Unretained(tracing_agent_registry_.get())));
tracing_coordinator_ = std::make_unique<tracing::Coordinator>();
registry_.AddInterface(
base::BindRepeating(&tracing::Coordinator::BindCoordinatorRequest,
base::Unretained(tracing_coordinator_.get())));
}
| 172,919 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 std::string& AppControllerImpl::MaybeGetAndroidPackageName(
const std::string& app_id) {
const auto& package_name_it = android_package_map_.find(app_id);
if (package_name_it != android_package_map_.end()) {
return package_name_it->second;
}
ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_);
if (!arc_prefs_) {
return base::EmptyString();
}
std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info =
arc_prefs_->GetApp(app_id);
if (!arc_info) {
return base::EmptyString();
}
android_package_map_[app_id] = arc_info->package_name;
return android_package_map_[app_id];
}
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 | const std::string& AppControllerImpl::MaybeGetAndroidPackageName(
const std::string& AppControllerService::MaybeGetAndroidPackageName(
const std::string& app_id) {
const auto& package_name_it = android_package_map_.find(app_id);
if (package_name_it != android_package_map_.end()) {
return package_name_it->second;
}
ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_);
if (!arc_prefs_) {
return base::EmptyString();
}
std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info =
arc_prefs_->GetApp(app_id);
if (!arc_info) {
return base::EmptyString();
}
android_package_map_[app_id] = arc_info->package_name;
return android_package_map_[app_id];
}
| 172,086 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssl3_take_mac(SSL *s)
{
const char *sender;
int slen;
if (s->state & SSL_ST_CONNECT)
{
sender=s->method->ssl3_enc->server_finished_label;
sender=s->method->ssl3_enc->client_finished_label;
slen=s->method->ssl3_enc->client_finished_label_len;
}
s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
sender,slen,s->s3->tmp.peer_finish_md);
}
Commit Message:
CWE ID: CWE-20 | static void ssl3_take_mac(SSL *s)
{
const char *sender;
int slen;
/* If no new cipher setup return immediately: other functions will
* set the appropriate error.
*/
if (s->s3->tmp.new_cipher == NULL)
return;
if (s->state & SSL_ST_CONNECT)
{
sender=s->method->ssl3_enc->server_finished_label;
sender=s->method->ssl3_enc->client_finished_label;
slen=s->method->ssl3_enc->client_finished_label_len;
}
s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
sender,slen,s->s3->tmp.peer_finish_md);
}
| 165,360 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | static inline int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,363 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(browser_context_);
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
| 172,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284 | DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
frame_tree_node_id_(-1),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
| 173,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
sk_read_actor_t recv_actor)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
u32 seq = tp->copied_seq;
u32 offset;
int copied = 0;
if (sk->sk_state == TCP_LISTEN)
return -ENOTCONN;
while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
if (offset < skb->len) {
int used;
size_t len;
len = skb->len - offset;
/* Stop reading if we hit a patch of urgent data */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - seq;
if (urg_offset < len)
len = urg_offset;
if (!len)
break;
}
used = recv_actor(desc, skb, offset, len);
if (used < 0) {
if (!copied)
copied = used;
break;
} else if (used <= len) {
seq += used;
copied += used;
offset += used;
}
/*
* If recv_actor drops the lock (e.g. TCP splice
* receive) the skb pointer might be invalid when
* getting here: tcp_collapse might have deleted it
* while aggregating skbs from the socket queue.
*/
skb = tcp_recv_skb(sk, seq-1, &offset);
if (!skb || (offset+1 != skb->len))
break;
}
if (tcp_hdr(skb)->fin) {
sk_eat_skb(sk, skb, 0);
++seq;
break;
}
sk_eat_skb(sk, skb, 0);
if (!desc->count)
break;
}
tp->copied_seq = seq;
tcp_rcv_space_adjust(sk);
/* Clean up data we have read: This will do ACK frames. */
if (copied > 0)
tcp_cleanup_rbuf(sk, copied);
return copied;
}
Commit Message: net: Fix oops from tcp_collapse() when using splice()
tcp_read_sock() can have a eat skbs without immediately advancing copied_seq.
This can cause a panic in tcp_collapse() if it is called as a result
of the recv_actor dropping the socket lock.
A userspace program that splices data from a socket to either another
socket or to a file can trigger this bug.
Signed-off-by: Steven J. Magnani <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
sk_read_actor_t recv_actor)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
u32 seq = tp->copied_seq;
u32 offset;
int copied = 0;
if (sk->sk_state == TCP_LISTEN)
return -ENOTCONN;
while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
if (offset < skb->len) {
int used;
size_t len;
len = skb->len - offset;
/* Stop reading if we hit a patch of urgent data */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - seq;
if (urg_offset < len)
len = urg_offset;
if (!len)
break;
}
used = recv_actor(desc, skb, offset, len);
if (used < 0) {
if (!copied)
copied = used;
break;
} else if (used <= len) {
seq += used;
copied += used;
offset += used;
}
/*
* If recv_actor drops the lock (e.g. TCP splice
* receive) the skb pointer might be invalid when
* getting here: tcp_collapse might have deleted it
* while aggregating skbs from the socket queue.
*/
skb = tcp_recv_skb(sk, seq-1, &offset);
if (!skb || (offset+1 != skb->len))
break;
}
if (tcp_hdr(skb)->fin) {
sk_eat_skb(sk, skb, 0);
++seq;
break;
}
sk_eat_skb(sk, skb, 0);
if (!desc->count)
break;
tp->copied_seq = seq;
}
tp->copied_seq = seq;
tcp_rcv_space_adjust(sk);
/* Clean up data we have read: This will do ACK frames. */
if (copied > 0)
tcp_cleanup_rbuf(sk, copied);
return copied;
}
| 166,084 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char *pt;
unsigned char l, lg, n = 0;
int fac_national_digis_received = 0;
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
if (*p == FAC_NATIONAL_RAND)
facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_NATIONAL_DEST_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);
facilities->source_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_SRC_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);
facilities->dest_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_FAIL_CALL) {
memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_FAIL_ADD) {
memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_DIGIS) {
fac_national_digis_received = 1;
facilities->source_ndigis = 0;
facilities->dest_ndigis = 0;
for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {
if (pt[6] & AX25_HBIT)
memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);
else
memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);
}
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
Commit Message: ROSE: prevent heap corruption with bad facilities
When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for
a remote host to provide more digipeaters than expected, resulting in
heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and
abort facilities parsing on failure.
Additionally, when parsing the FAC_CCITT_DEST_NSAP and
FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length
of less than 10, resulting in an underflow in a memcpy size, causing a
kernel panic due to massive heap corruption. A length of greater than
20 results in a stack overflow of the callsign array. Abort facilities
parsing on these invalid length values.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char *pt;
unsigned char l, lg, n = 0;
int fac_national_digis_received = 0;
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
if (*p == FAC_NATIONAL_RAND)
facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_NATIONAL_DEST_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);
facilities->source_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_SRC_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);
facilities->dest_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_FAIL_CALL) {
memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_FAIL_ADD) {
memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_DIGIS) {
fac_national_digis_received = 1;
facilities->source_ndigis = 0;
facilities->dest_ndigis = 0;
for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {
if (pt[6] & AX25_HBIT) {
if (facilities->dest_ndigis >= ROSE_MAX_DIGIS)
return -1;
memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);
} else {
if (facilities->source_ndigis >= ROSE_MAX_DIGIS)
return -1;
memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);
}
}
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
| 165,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_marker (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 24) ;
} ;
} /* header_put_marker */
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_marker (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = (x >> 16) ;
psf->header.ptr [psf->header.indx++] = (x >> 24) ;
} /* header_put_marker */
| 170,060 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CheckSad(unsigned int max_sad) {
unsigned int reference_sad, exp_sad;
reference_sad = ReferenceSAD(max_sad);
exp_sad = SAD(max_sad);
if (reference_sad <= max_sad) {
ASSERT_EQ(exp_sad, reference_sad);
} else {
ASSERT_GE(exp_sad, reference_sad);
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void CheckSad(unsigned int max_sad) {
| 174,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport void *DetachBlob(BlobInfo *blob_info)
{
void
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
blob_info->custom_stream=(CustomStreamInfo *) NULL;
return(data);
}
Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43
CWE ID: CWE-416 | MagickExport void *DetachBlob(BlobInfo *blob_info)
{
void
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
blob_info->data=NULL;
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
blob_info->custom_stream=(CustomStreamInfo *) NULL;
return(data);
}
| 170,190 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
OPJ_UINT32 index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
OPJ_UINT32 compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
OPJ_UINT32 dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
OPJ_UINT32 levelno;
OPJ_INT32 trx0, try0;
OPJ_INT32 trx1, try1;
OPJ_UINT32 rpx, rpy;
OPJ_INT32 prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
(OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
- opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
(OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
- opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: Avoid division by zero in opj_pi_next_rpcl, opj_pi_next_pcrl and opj_pi_next_cprl (#938)
Fixes issues with id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 and
id:000019,sig:08,src:001098,op:flip1,pos:49
CWE ID: CWE-369 | static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
OPJ_UINT32 index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
OPJ_UINT32 compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
OPJ_UINT32 dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
OPJ_UINT32 levelno;
OPJ_INT32 trx0, try0;
OPJ_INT32 trx1, try1;
OPJ_UINT32 rpx, rpy;
OPJ_INT32 prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
/* in below tests */
/* Relates to id:000019,sig:08,src:001098,op:flip1,pos:49 */
/* of https://github.com/uclouvain/openjpeg/issues/938 */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
/* See ISO-15441. B.12.1.4 Position-component-resolution level-layer progression */
if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
(OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
- opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
(OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
- opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
| 168,456 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
Commit Message: Always mark content downloaded by devtools delegate as potentially dangerous
Bug: 805445
Change-Id: I7051f519205e178db57e23320ab979f8fa9ce38b
Reviewed-on: https://chromium-review.googlesource.com/894782
Commit-Queue: David Vallet <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533215}
CWE ID: | void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
| 173,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::DispatchUnloadEvents() {
PluginScriptForbiddenScope forbid_plugin_destructor_scripting;
if (parser_)
parser_->StopParsing();
if (load_event_progress_ == kLoadEventNotRun)
return;
if (load_event_progress_ <= kUnloadEventInProgress) {
Element* current_focused_element = FocusedElement();
if (auto* input = ToHTMLInputElementOrNull(current_focused_element))
input->EndEditing();
if (load_event_progress_ < kPageHideInProgress) {
load_event_progress_ = kPageHideInProgress;
if (LocalDOMWindow* window = domWindow()) {
const TimeTicks pagehide_event_start = CurrentTimeTicks();
window->DispatchEvent(
PageTransitionEvent::Create(EventTypeNames::pagehide, false), this);
const TimeTicks pagehide_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, pagehide_histogram,
("DocumentEventTiming.PageHideDuration", 0, 10000000, 50));
pagehide_histogram.Count(
(pagehide_event_end - pagehide_event_start).InMicroseconds());
}
if (!frame_)
return;
mojom::PageVisibilityState visibility_state = GetPageVisibilityState();
load_event_progress_ = kUnloadVisibilityChangeInProgress;
if (visibility_state != mojom::PageVisibilityState::kHidden) {
const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks();
DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange));
const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram,
("DocumentEventTiming.PageVibilityHiddenDuration",
0, 10000000, 50));
pagevisibility_histogram.Count((pagevisibility_hidden_event_end -
pagevisibility_hidden_event_start)
.InMicroseconds());
DispatchEvent(
Event::CreateBubble(EventTypeNames::webkitvisibilitychange));
}
if (!frame_)
return;
frame_->Loader().SaveScrollAnchor();
DocumentLoader* document_loader =
frame_->Loader().GetProvisionalDocumentLoader();
load_event_progress_ = kUnloadEventInProgress;
Event* unload_event(Event::Create(EventTypeNames::unload));
if (document_loader &&
document_loader->GetTiming().UnloadEventStart().is_null() &&
document_loader->GetTiming().UnloadEventEnd().is_null()) {
DocumentLoadTiming& timing = document_loader->GetTiming();
DCHECK(!timing.NavigationStart().is_null());
const TimeTicks unload_event_start = CurrentTimeTicks();
timing.MarkUnloadEventStart(unload_event_start);
frame_->DomWindow()->DispatchEvent(unload_event, this);
const TimeTicks unload_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, unload_histogram,
("DocumentEventTiming.UnloadDuration", 0, 10000000, 50));
unload_histogram.Count(
(unload_event_end - unload_event_start).InMicroseconds());
timing.MarkUnloadEventEnd(unload_event_end);
} else {
frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument());
}
}
load_event_progress_ = kUnloadEventHandled;
}
if (!frame_)
return;
bool keep_event_listeners =
frame_->Loader().GetProvisionalDocumentLoader() &&
frame_->ShouldReuseDefaultView(
frame_->Loader().GetProvisionalDocumentLoader()->Url());
if (!keep_event_listeners)
RemoveAllEventListenersRecursively();
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285 | void Document::DispatchUnloadEvents() {
PluginScriptForbiddenScope forbid_plugin_destructor_scripting;
if (parser_)
parser_->StopParsing();
if (load_event_progress_ == kLoadEventNotRun)
return;
if (load_event_progress_ <= kUnloadEventInProgress) {
Element* current_focused_element = FocusedElement();
if (auto* input = ToHTMLInputElementOrNull(current_focused_element))
input->EndEditing();
if (load_event_progress_ < kPageHideInProgress) {
load_event_progress_ = kPageHideInProgress;
if (LocalDOMWindow* window = domWindow()) {
const TimeTicks pagehide_event_start = CurrentTimeTicks();
window->DispatchEvent(
PageTransitionEvent::Create(EventTypeNames::pagehide, false), this);
const TimeTicks pagehide_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, pagehide_histogram,
("DocumentEventTiming.PageHideDuration", 0, 10000000, 50));
pagehide_histogram.Count(
(pagehide_event_end - pagehide_event_start).InMicroseconds());
}
if (!frame_)
return;
mojom::PageVisibilityState visibility_state = GetPageVisibilityState();
load_event_progress_ = kUnloadVisibilityChangeInProgress;
if (visibility_state != mojom::PageVisibilityState::kHidden) {
const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks();
DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange));
const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram,
("DocumentEventTiming.PageVibilityHiddenDuration",
0, 10000000, 50));
pagevisibility_histogram.Count((pagevisibility_hidden_event_end -
pagevisibility_hidden_event_start)
.InMicroseconds());
DispatchEvent(
Event::CreateBubble(EventTypeNames::webkitvisibilitychange));
}
if (!frame_)
return;
frame_->Loader().SaveScrollAnchor();
DocumentLoader* document_loader =
frame_->Loader().GetProvisionalDocumentLoader();
load_event_progress_ = kUnloadEventInProgress;
Event* unload_event(Event::Create(EventTypeNames::unload));
if (document_loader &&
document_loader->GetTiming().UnloadEventStart().is_null() &&
document_loader->GetTiming().UnloadEventEnd().is_null()) {
DocumentLoadTiming& timing = document_loader->GetTiming();
DCHECK(!timing.NavigationStart().is_null());
const TimeTicks unload_event_start = CurrentTimeTicks();
timing.MarkUnloadEventStart(unload_event_start);
frame_->DomWindow()->DispatchEvent(unload_event, this);
const TimeTicks unload_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, unload_histogram,
("DocumentEventTiming.UnloadDuration", 0, 10000000, 50));
unload_histogram.Count(
(unload_event_end - unload_event_start).InMicroseconds());
timing.MarkUnloadEventEnd(unload_event_end);
} else {
frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument());
}
}
load_event_progress_ = kUnloadEventHandled;
}
if (!frame_)
return;
bool keep_event_listeners =
frame_->Loader().GetProvisionalDocumentLoader() &&
frame_->ShouldReuseDefaultView(
frame_->Loader().GetProvisionalDocumentLoader()->Url(),
frame_->Loader()
.GetProvisionalDocumentLoader()
->GetContentSecurityPolicy());
if (!keep_event_listeners)
RemoveAllEventListenersRecursively();
}
| 173,195 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
Commit Message: make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-200 | static int run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (g_settings_privatereports)
{
struct stat statbuf;
if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
error_msg("Path '%s' isn't directory", dirname);
return 404; /* Not Found */
}
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (!gr)
{
error_msg("Group 'abrt' does not exist");
return 500;
}
if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 403;
}
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
| 170,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct rds_connection *__rds_conn_create(struct net *net,
__be32 laddr, __be32 faddr,
struct rds_transport *trans, gfp_t gfp,
int is_outgoing)
{
struct rds_connection *conn, *parent = NULL;
struct hlist_head *head = rds_conn_bucket(laddr, faddr);
struct rds_transport *loop_trans;
unsigned long flags;
int ret;
rcu_read_lock();
conn = rds_conn_lookup(net, head, laddr, faddr, trans);
if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport &&
laddr == faddr && !is_outgoing) {
/* This is a looped back IB connection, and we're
* called by the code handling the incoming connect.
* We need a second connection object into which we
* can stick the other QP. */
parent = conn;
conn = parent->c_passive;
}
rcu_read_unlock();
if (conn)
goto out;
conn = kmem_cache_zalloc(rds_conn_slab, gfp);
if (!conn) {
conn = ERR_PTR(-ENOMEM);
goto out;
}
INIT_HLIST_NODE(&conn->c_hash_node);
conn->c_laddr = laddr;
conn->c_faddr = faddr;
spin_lock_init(&conn->c_lock);
conn->c_next_tx_seq = 1;
rds_conn_net_set(conn, net);
init_waitqueue_head(&conn->c_waitq);
INIT_LIST_HEAD(&conn->c_send_queue);
INIT_LIST_HEAD(&conn->c_retrans);
ret = rds_cong_get_maps(conn);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
/*
* This is where a connection becomes loopback. If *any* RDS sockets
* can bind to the destination address then we'd rather the messages
* flow through loopback rather than either transport.
*/
loop_trans = rds_trans_get_preferred(net, faddr);
if (loop_trans) {
rds_trans_put(loop_trans);
conn->c_loopback = 1;
if (is_outgoing && trans->t_prefer_loopback) {
/* "outgoing" connection - and the transport
* says it wants the connection handled by the
* loopback transport. This is what TCP does.
*/
trans = &rds_loop_transport;
}
}
if (trans == NULL) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(-ENODEV);
goto out;
}
conn->c_trans = trans;
ret = trans->conn_alloc(conn, gfp);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
atomic_set(&conn->c_state, RDS_CONN_DOWN);
conn->c_send_gen = 0;
conn->c_outgoing = (is_outgoing ? 1 : 0);
conn->c_reconnect_jiffies = 0;
INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker);
INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker);
INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker);
INIT_WORK(&conn->c_down_w, rds_shutdown_worker);
mutex_init(&conn->c_cm_lock);
conn->c_flags = 0;
rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n",
conn, &laddr, &faddr,
trans->t_name ? trans->t_name : "[unknown]",
is_outgoing ? "(outgoing)" : "");
/*
* Since we ran without holding the conn lock, someone could
* have created the same conn (either normal or passive) in the
* interim. We check while holding the lock. If we won, we complete
* init and return our conn. If we lost, we rollback and return the
* other one.
*/
spin_lock_irqsave(&rds_conn_lock, flags);
if (parent) {
/* Creating passive conn */
if (parent->c_passive) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = parent->c_passive;
} else {
parent->c_passive = conn;
rds_cong_add_conn(conn);
rds_conn_count++;
}
} else {
/* Creating normal conn */
struct rds_connection *found;
found = rds_conn_lookup(net, head, laddr, faddr, trans);
if (found) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = found;
} else {
hlist_add_head_rcu(&conn->c_hash_node, head);
rds_cong_add_conn(conn);
rds_conn_count++;
}
}
spin_unlock_irqrestore(&rds_conn_lock, flags);
out:
return conn;
}
Commit Message: RDS: fix race condition when sending a message on unbound socket
Sasha's found a NULL pointer dereference in the RDS connection code when
sending a message to an apparently unbound socket. The problem is caused
by the code checking if the socket is bound in rds_sendmsg(), which checks
the rs_bound_addr field without taking a lock on the socket. This opens a
race where rs_bound_addr is temporarily set but where the transport is not
in rds_bind(), leading to a NULL pointer dereference when trying to
dereference 'trans' in __rds_conn_create().
Vegard wrote a reproducer for this issue, so kindly ask him to share if
you're interested.
I cannot reproduce the NULL pointer dereference using Vegard's reproducer
with this patch, whereas I could without.
Complete earlier incomplete fix to CVE-2015-6937:
74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection")
Cc: David S. Miller <[email protected]>
Cc: [email protected]
Reviewed-by: Vegard Nossum <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static struct rds_connection *__rds_conn_create(struct net *net,
__be32 laddr, __be32 faddr,
struct rds_transport *trans, gfp_t gfp,
int is_outgoing)
{
struct rds_connection *conn, *parent = NULL;
struct hlist_head *head = rds_conn_bucket(laddr, faddr);
struct rds_transport *loop_trans;
unsigned long flags;
int ret;
rcu_read_lock();
conn = rds_conn_lookup(net, head, laddr, faddr, trans);
if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport &&
laddr == faddr && !is_outgoing) {
/* This is a looped back IB connection, and we're
* called by the code handling the incoming connect.
* We need a second connection object into which we
* can stick the other QP. */
parent = conn;
conn = parent->c_passive;
}
rcu_read_unlock();
if (conn)
goto out;
conn = kmem_cache_zalloc(rds_conn_slab, gfp);
if (!conn) {
conn = ERR_PTR(-ENOMEM);
goto out;
}
INIT_HLIST_NODE(&conn->c_hash_node);
conn->c_laddr = laddr;
conn->c_faddr = faddr;
spin_lock_init(&conn->c_lock);
conn->c_next_tx_seq = 1;
rds_conn_net_set(conn, net);
init_waitqueue_head(&conn->c_waitq);
INIT_LIST_HEAD(&conn->c_send_queue);
INIT_LIST_HEAD(&conn->c_retrans);
ret = rds_cong_get_maps(conn);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
/*
* This is where a connection becomes loopback. If *any* RDS sockets
* can bind to the destination address then we'd rather the messages
* flow through loopback rather than either transport.
*/
loop_trans = rds_trans_get_preferred(net, faddr);
if (loop_trans) {
rds_trans_put(loop_trans);
conn->c_loopback = 1;
if (is_outgoing && trans->t_prefer_loopback) {
/* "outgoing" connection - and the transport
* says it wants the connection handled by the
* loopback transport. This is what TCP does.
*/
trans = &rds_loop_transport;
}
}
conn->c_trans = trans;
ret = trans->conn_alloc(conn, gfp);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
atomic_set(&conn->c_state, RDS_CONN_DOWN);
conn->c_send_gen = 0;
conn->c_outgoing = (is_outgoing ? 1 : 0);
conn->c_reconnect_jiffies = 0;
INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker);
INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker);
INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker);
INIT_WORK(&conn->c_down_w, rds_shutdown_worker);
mutex_init(&conn->c_cm_lock);
conn->c_flags = 0;
rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n",
conn, &laddr, &faddr,
trans->t_name ? trans->t_name : "[unknown]",
is_outgoing ? "(outgoing)" : "");
/*
* Since we ran without holding the conn lock, someone could
* have created the same conn (either normal or passive) in the
* interim. We check while holding the lock. If we won, we complete
* init and return our conn. If we lost, we rollback and return the
* other one.
*/
spin_lock_irqsave(&rds_conn_lock, flags);
if (parent) {
/* Creating passive conn */
if (parent->c_passive) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = parent->c_passive;
} else {
parent->c_passive = conn;
rds_cong_add_conn(conn);
rds_conn_count++;
}
} else {
/* Creating normal conn */
struct rds_connection *found;
found = rds_conn_lookup(net, head, laddr, faddr, trans);
if (found) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = found;
} else {
hlist_add_head_rcu(&conn->c_hash_node, head);
rds_cong_add_conn(conn);
rds_conn_count++;
}
}
spin_unlock_irqrestore(&rds_conn_lock, flags);
out:
return conn;
}
| 166,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx,
const unsigned char *ax)
{
#ifdef USE_AMD64_ASM
return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
&dec_tables);
#elif defined(USE_ARM_ASM)
return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
&dec_tables);
#else
return do_decrypt_fn (ctx, bx, ax);
#endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/
}
Commit Message: AES: move look-up tables to .data section and unshare between processes
* cipher/rijndael-internal.h (ATTR_ALIGNED_64): New.
* cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure.
(enc_tables): New structure for encryption table with counters before
and after.
(encT): New macro.
(dec_tables): Add counters before and after encryption table; Move
from .rodata to .data section.
(do_encrypt): Change 'encT' to 'enc_tables.T'.
(do_decrypt): Change '&dec_tables' to 'dec_tables.T'.
* cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input
with length not multiple of 256.
(prefetch_enc, prefetch_dec): Modify pre- and post-table counters
to unshare look-up table pages between processes.
--
GnuPG-bug-id: 4541
Signed-off-by: Jussi Kivilinna <[email protected]>
CWE ID: CWE-310 | do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx,
const unsigned char *ax)
{
#ifdef USE_AMD64_ASM
return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
dec_tables.T);
#elif defined(USE_ARM_ASM)
return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
dec_tables.T);
#else
return do_decrypt_fn (ctx, bx, ax);
#endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/
}
| 170,211 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
| 170,979 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateString( const char *string )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_String;
item->valuestring = cJSON_strdup( string );
}
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateString( const char *string )
| 167,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error)
{
GArray *array;
int i;
int j;
j = 0;
array = (GArray *)g_value_get_boxed (variant);
for (i = 0; i <= 2; i++)
{
j = g_array_index (array, int, i);
if (j != i + 1)
goto error;
}
return TRUE;
error:
*error = g_error_new (MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"Error decoding a variant of type ai (i + 1 = %i, j = %i)",
i, j + 1);
return FALSE;
}
Commit Message:
CWE ID: CWE-264 | my_object_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error)
| 165,115 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t first_block, stop_block;
struct address_space *mapping = inode->i_mapping;
loff_t first_block_offset, last_block_offset;
handle_t *handle;
unsigned int credits;
int ret = 0;
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
trace_ext4_punch_hole(inode, offset, length, 0);
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + length - 1);
if (ret)
return ret;
}
mutex_lock(&inode->i_mutex);
/* No need to punch hole beyond i_size */
if (offset >= inode->i_size)
goto out_mutex;
/*
* If the hole extends beyond i_size, set the hole
* to end after the page that contains i_size
*/
if (offset + length > inode->i_size) {
length = inode->i_size +
PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
offset;
}
if (offset & (sb->s_blocksize - 1) ||
(offset + length) & (sb->s_blocksize - 1)) {
/*
* Attach jinode to inode for jbd2 if we do any zeroing of
* partial block
*/
ret = ext4_inode_attach_jinode(inode);
if (ret < 0)
goto out_mutex;
}
first_block_offset = round_up(offset, sb->s_blocksize);
last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
/* Now release the pages and zero block aligned part of pages*/
if (last_block_offset > first_block_offset)
truncate_pagecache_range(inode, first_block_offset,
last_block_offset);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
credits = ext4_writepage_trans_blocks(inode);
else
credits = ext4_blocks_for_truncate(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(sb, ret);
goto out_dio;
}
ret = ext4_zero_partial_blocks(handle, inode, offset,
length);
if (ret)
goto out_stop;
first_block = (offset + sb->s_blocksize - 1) >>
EXT4_BLOCK_SIZE_BITS(sb);
stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
/* If there are no blocks to remove, return now */
if (first_block >= stop_block)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
ret = ext4_es_remove_extent(inode, first_block,
stop_block - first_block);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
ret = ext4_ext_remove_space(inode, first_block,
stop_block - 1);
else
ret = ext4_ind_remove_space(handle, inode, first_block,
stop_block);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
/* Now release the pages again to reduce race window */
if (last_block_offset > first_block_offset)
truncate_pagecache_range(inode, first_block_offset,
last_block_offset);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
out_stop:
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362 | int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t first_block, stop_block;
struct address_space *mapping = inode->i_mapping;
loff_t first_block_offset, last_block_offset;
handle_t *handle;
unsigned int credits;
int ret = 0;
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
trace_ext4_punch_hole(inode, offset, length, 0);
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + length - 1);
if (ret)
return ret;
}
mutex_lock(&inode->i_mutex);
/* No need to punch hole beyond i_size */
if (offset >= inode->i_size)
goto out_mutex;
/*
* If the hole extends beyond i_size, set the hole
* to end after the page that contains i_size
*/
if (offset + length > inode->i_size) {
length = inode->i_size +
PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
offset;
}
if (offset & (sb->s_blocksize - 1) ||
(offset + length) & (sb->s_blocksize - 1)) {
/*
* Attach jinode to inode for jbd2 if we do any zeroing of
* partial block
*/
ret = ext4_inode_attach_jinode(inode);
if (ret < 0)
goto out_mutex;
}
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
first_block_offset = round_up(offset, sb->s_blocksize);
last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
/* Now release the pages and zero block aligned part of pages*/
if (last_block_offset > first_block_offset)
truncate_pagecache_range(inode, first_block_offset,
last_block_offset);
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
credits = ext4_writepage_trans_blocks(inode);
else
credits = ext4_blocks_for_truncate(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(sb, ret);
goto out_dio;
}
ret = ext4_zero_partial_blocks(handle, inode, offset,
length);
if (ret)
goto out_stop;
first_block = (offset + sb->s_blocksize - 1) >>
EXT4_BLOCK_SIZE_BITS(sb);
stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
/* If there are no blocks to remove, return now */
if (first_block >= stop_block)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
ret = ext4_es_remove_extent(inode, first_block,
stop_block - first_block);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
ret = ext4_ext_remove_space(inode, first_block,
stop_block - 1);
else
ret = ext4_ind_remove_space(handle, inode, first_block,
stop_block);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
out_stop:
ext4_journal_stop(handle);
out_dio:
up_write(&EXT4_I(inode)->i_mmap_sem);
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
| 167,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: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b = NULL;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey = NULL;
size_t keylen, ivlen, maclen;
int r;
if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
(r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
(r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
(r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
(r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
goto out;
if ((r = mac_setup(mac, mac->name)) != 0)
goto out;
if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
(r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
goto out;
if (maclen > mac->key_len) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
mac->key_len = maclen;
}
if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
(r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
goto out;
if (enc->name == NULL ||
cipher_by_name(enc->name) != enc->cipher) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
enc->key_len = keylen;
enc->iv_len = ivlen;
ssh->kex->newkeys[mode] = newkey;
newkey = NULL;
r = 0;
out:
free(newkey);
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b = NULL;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey = NULL;
size_t keylen, ivlen, maclen;
int r;
if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
(r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
(r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
(r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
(r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
goto out;
if ((r = mac_setup(mac, mac->name)) != 0)
goto out;
if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
(r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
goto out;
if (maclen > mac->key_len) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
mac->key_len = maclen;
}
if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
(r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
goto out;
if (enc->name == NULL ||
cipher_by_name(enc->name) != enc->cipher) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
enc->key_len = keylen;
enc->iv_len = ivlen;
ssh->kex->newkeys[mode] = newkey;
newkey = NULL;
r = 0;
out:
free(newkey);
sshbuf_free(b);
return r;
}
| 168,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: iakerb_alloc_context(iakerb_ctx_id_t *pctx)
{
iakerb_ctx_id_t ctx;
krb5_error_code code;
*pctx = NULL;
ctx = k5alloc(sizeof(*ctx), &code);
if (ctx == NULL)
goto cleanup;
ctx->defcred = GSS_C_NO_CREDENTIAL;
ctx->magic = KG_IAKERB_CONTEXT;
ctx->state = IAKERB_AS_REQ;
ctx->count = 0;
code = krb5_gss_init_context(&ctx->k5c);
if (code != 0)
goto cleanup;
*pctx = ctx;
cleanup:
if (code != 0)
iakerb_release_context(ctx);
return code;
}
Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696]
The IAKERB mechanism currently replaces its context handle with the
krb5 mechanism handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the IAKERB context structure after context
establishment and add new IAKERB entry points to refer to it with that
type. Add initiate and established flags to the IAKERB context
structure for use in gss_inquire_context() prior to context
establishment.
CVE-2015-2696:
In MIT krb5 1.9 and later, applications which call
gss_inquire_context() on a partially-established IAKERB context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. Java server applications using the
native JGSS provider are vulnerable to this bug. A carefully crafted
IAKERB packet might allow the gss_inquire_context() call to succeed
with attacker-determined results, but applications should not make
access control decisions based on gss_inquire_context() results prior
to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | iakerb_alloc_context(iakerb_ctx_id_t *pctx)
iakerb_alloc_context(iakerb_ctx_id_t *pctx, int initiate)
{
iakerb_ctx_id_t ctx;
krb5_error_code code;
*pctx = NULL;
ctx = k5alloc(sizeof(*ctx), &code);
if (ctx == NULL)
goto cleanup;
ctx->defcred = GSS_C_NO_CREDENTIAL;
ctx->magic = KG_IAKERB_CONTEXT;
ctx->state = IAKERB_AS_REQ;
ctx->count = 0;
ctx->initiate = initiate;
ctx->established = 0;
code = krb5_gss_init_context(&ctx->k5c);
if (code != 0)
goto cleanup;
*pctx = ctx;
cleanup:
if (code != 0)
iakerb_release_context(ctx);
return code;
}
| 166,643 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaControlsHeaderView::MediaControlsHeaderView() {
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kMediaControlsHeaderInsets,
kMediaControlsHeaderChildSpacing));
auto app_icon_view = std::make_unique<views::ImageView>();
app_icon_view->SetImageSize(gfx::Size(kIconSize, kIconSize));
app_icon_view->SetVerticalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetBorder(views::CreateEmptyBorder(kIconPadding));
app_icon_view->SetBackground(
views::CreateRoundedRectBackground(SK_ColorWHITE, kIconCornerRadius));
app_icon_view_ = AddChildView(std::move(app_icon_view));
gfx::Font default_font;
int font_size_delta = kHeaderTextFontSize - default_font.GetFontSize();
gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL,
gfx::Font::Weight::NORMAL);
gfx::FontList font_list(font);
auto app_name_view = std::make_unique<views::Label>();
app_name_view->SetFontList(font_list);
app_name_view->SetHorizontalAlignment(gfx::ALIGN_LEFT);
app_name_view->SetEnabledColor(SK_ColorWHITE);
app_name_view->SetAutoColorReadabilityEnabled(false);
app_name_view_ = AddChildView(std::move(app_name_view));
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | MediaControlsHeaderView::MediaControlsHeaderView() {
MediaControlsHeaderView::MediaControlsHeaderView(
base::OnceClosure close_button_cb)
: close_button_cb_(std::move(close_button_cb)) {
auto* layout = SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetInteriorMargin(kHeaderViewInsets);
auto app_icon_view = std::make_unique<views::ImageView>();
app_icon_view->SetImageSize(gfx::Size(kIconSize, kIconSize));
app_icon_view->SetVerticalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetBorder(views::CreateEmptyBorder(kIconPadding));
app_icon_view->SetBackground(
views::CreateRoundedRectBackground(SK_ColorWHITE, kIconCornerRadius));
app_icon_view_ = AddChildView(std::move(app_icon_view));
gfx::Font default_font;
int font_size_delta = kHeaderTextFontSize - default_font.GetFontSize();
gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL,
gfx::Font::Weight::NORMAL);
gfx::FontList font_list(font);
auto app_name_view = std::make_unique<views::Label>();
app_name_view->SetFontList(font_list);
app_name_view->SetHorizontalAlignment(gfx::ALIGN_LEFT);
app_name_view->SetEnabledColor(SK_ColorWHITE);
app_name_view->SetAutoColorReadabilityEnabled(false);
app_name_view->SetBorder(views::CreateEmptyBorder(kAppNamePadding));
app_name_view_ = AddChildView(std::move(app_name_view));
// Space between app name and close button.
auto spacer = std::make_unique<NonAccessibleView>();
spacer->SetPreferredSize(kSpacerPreferredSize);
spacer->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification::ForSizeRule(
views::MinimumFlexSizeRule::kScaleToMinimum,
views::MaximumFlexSizeRule::kUnbounded));
AddChildView(std::move(spacer));
auto close_button = CreateVectorImageButton(this);
SetImageFromVectorIcon(close_button.get(), vector_icons::kCloseRoundedIcon,
kCloseButtonIconSize, gfx::kGoogleGrey700);
close_button->SetPreferredSize(kCloseButtonSize);
close_button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
base::string16 close_button_label(
l10n_util::GetStringUTF16(IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_CLOSE));
close_button->SetAccessibleName(close_button_label);
close_button->SetVisible(false);
close_button_ = AddChildView(std::move(close_button));
}
| 172,344 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr;
struct sock *sk = sock->sk;
struct ipv6_pinfo *np = inet6_sk(sk);
struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk);
lsa->l2tp_family = AF_INET6;
lsa->l2tp_flowinfo = 0;
lsa->l2tp_scope_id = 0;
if (peer) {
if (!lsk->peer_conn_id)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr = np->daddr;
if (np->sndflow)
lsa->l2tp_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&np->rcv_saddr))
lsa->l2tp_addr = np->saddr;
else
lsa->l2tp_addr = np->rcv_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
}
if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)
lsa->l2tp_scope_id = sk->sk_bound_dev_if;
*uaddr_len = sizeof(*lsa);
return 0;
}
Commit Message: l2tp: fix info leak via getsockname()
The L2TP code for IPv6 fails to initialize the l2tp_unused member of
struct sockaddr_l2tpip6 and that for leaks two bytes kernel stack via
the getsockname() syscall. Initialize l2tp_unused with 0 to avoid the
info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: James Chapman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr;
struct sock *sk = sock->sk;
struct ipv6_pinfo *np = inet6_sk(sk);
struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk);
lsa->l2tp_family = AF_INET6;
lsa->l2tp_flowinfo = 0;
lsa->l2tp_scope_id = 0;
lsa->l2tp_unused = 0;
if (peer) {
if (!lsk->peer_conn_id)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr = np->daddr;
if (np->sndflow)
lsa->l2tp_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&np->rcv_saddr))
lsa->l2tp_addr = np->saddr;
else
lsa->l2tp_addr = np->rcv_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
}
if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)
lsa->l2tp_scope_id = sk->sk_bound_dev_if;
*uaddr_len = sizeof(*lsa);
return 0;
}
| 166,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: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
| 174,553 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcEstablishConnection(ClientPtr client)
{
const char *reason;
char *auth_proto, *auth_string;
xConnClientPrefix *prefix;
REQUEST(xReq);
prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq);
auth_proto = (char *) prefix + sz_xConnClientPrefix;
auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto);
if ((prefix->majorVersion != X_PROTOCOL) ||
(prefix->minorVersion != X_PROTOCOL_REVISION))
reason = "Protocol version mismatch";
else
return (SendConnSetup(client, reason));
}
Commit Message:
CWE ID: CWE-20 | ProcEstablishConnection(ClientPtr client)
{
const char *reason;
char *auth_proto, *auth_string;
xConnClientPrefix *prefix;
REQUEST(xReq);
prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq);
auth_proto = (char *) prefix + sz_xConnClientPrefix;
auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto);
if ((client->req_len << 2) != sz_xReq + sz_xConnClientPrefix +
pad_to_int32(prefix->nbytesAuthProto) +
pad_to_int32(prefix->nbytesAuthString))
reason = "Bad length";
else if ((prefix->majorVersion != X_PROTOCOL) ||
(prefix->minorVersion != X_PROTOCOL_REVISION))
reason = "Protocol version mismatch";
else
return (SendConnSetup(client, reason));
}
| 165,448 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc,
char **argv)
{
char *filein, *str, *tempfile, *prestring, *outprotos, *protostr;
const char *spacestr = " ";
char buf[L_BUF_SIZE];
l_uint8 *allheaders;
l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret;
size_t nbytes;
L_BYTEA *ba, *ba2;
SARRAY *sa, *safirst;
static char mainName[] = "xtractprotos";
if (argc == 1) {
fprintf(stderr,
"xtractprotos [-prestring=<string>] [-protos=<where>] "
"[list of C files]\n"
"where the prestring is prepended to each prototype, and \n"
"protos can be either 'inline' or the name of an output "
"prototype file\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Parse input flags and find prestring and outprotos, if requested */
/* ---------------------------------------------------------------- */
prestring = outprotos = NULL;
in_line = FALSE;
nflags = 0;
maxindex = L_MIN(3, argc);
for (i = 1; i < maxindex; i++) {
if (argv[i][0] == '-') {
if (!strncmp(argv[i], "-prestring", 10)) {
nflags++;
ret = sscanf(argv[i] + 1, "prestring=%s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for prestring\n");
return 1;
}
if ((len = strlen(buf)) > L_BUF_SIZE - 3) {
L_WARNING("prestring too large; omitting!\n", mainName);
} else {
buf[len] = ' ';
buf[len + 1] = '\0';
prestring = stringNew(buf);
}
} else if (!strncmp(argv[i], "-protos", 7)) {
nflags++;
ret = sscanf(argv[i] + 1, "protos=%s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for protos\n");
return 1;
}
outprotos = stringNew(buf);
if (!strncmp(outprotos, "inline", 7))
in_line = TRUE;
}
}
}
if (argc - nflags < 2) {
fprintf(stderr, "no files specified!\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Generate the prototype string */
/* ---------------------------------------------------------------- */
ba = l_byteaCreate(500);
/* First the extern C head */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"/*", L_COPY);
snprintf(buf, L_BUF_SIZE,
" * These prototypes were autogen'd by xtractprotos, v. %s",
version);
sarrayAddString(sa, buf, L_COPY);
sarrayAddString(sa, (char *)" */", L_COPY);
sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
/* Then the prototypes */
firstfile = 1 + nflags;
protos_added = FALSE;
if ((tempfile = l_makeTempFilename()) == NULL) {
fprintf(stderr, "failure to make a writeable temp file\n");
return 1;
}
for (i = firstfile; i < argc; i++) {
filein = argv[i];
len = strlen(filein);
if (filein[len - 1] == 'h') /* skip .h files */
continue;
snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s",
filein, tempfile);
ret = system(buf); /* cpp */
if (ret) {
fprintf(stderr, "cpp failure for %s; continuing\n", filein);
continue;
}
if ((str = parseForProtos(tempfile, prestring)) == NULL) {
fprintf(stderr, "parse failure for %s; continuing\n", filein);
continue;
}
if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */
l_byteaAppendString(ba, str);
protos_added = TRUE;
}
lept_free(str);
}
lept_rmfile(tempfile);
lept_free(tempfile);
/* Lastly the extern C tail */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"}", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
protostr = (char *)l_byteaCopyData(ba, &nbytes);
l_byteaDestroy(&ba);
/* ---------------------------------------------------------------- */
/* Generate the output */
/* ---------------------------------------------------------------- */
if (!outprotos) { /* just write to stdout */
fprintf(stderr, "%s\n", protostr);
lept_free(protostr);
return 0;
}
/* If no protos were found, do nothing further */
if (!protos_added) {
fprintf(stderr, "No protos found\n");
lept_free(protostr);
return 1;
}
/* Make the output files */
ba = l_byteaInitFromFile("allheaders_top.txt");
if (!in_line) {
snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos);
l_byteaAppendString(ba, buf);
l_binaryWrite(outprotos, "w", protostr, nbytes);
} else {
l_byteaAppendString(ba, protostr);
}
ba2 = l_byteaInitFromFile("allheaders_bot.txt");
l_byteaJoin(ba, &ba2);
l_byteaWrite("allheaders.h", ba, 0, 0);
l_byteaDestroy(&ba);
lept_free(protostr);
return 0;
}
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 | int main(int argc,
char **argv)
{
char *filein, *str, *tempfile, *prestring, *outprotos, *protostr;
const char *spacestr = " ";
char buf[L_BUFSIZE];
l_uint8 *allheaders;
l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret;
size_t nbytes;
L_BYTEA *ba, *ba2;
SARRAY *sa, *safirst;
static char mainName[] = "xtractprotos";
if (argc == 1) {
fprintf(stderr,
"xtractprotos [-prestring=<string>] [-protos=<where>] "
"[list of C files]\n"
"where the prestring is prepended to each prototype, and \n"
"protos can be either 'inline' or the name of an output "
"prototype file\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Parse input flags and find prestring and outprotos, if requested */
/* ---------------------------------------------------------------- */
prestring = outprotos = NULL;
in_line = FALSE;
nflags = 0;
maxindex = L_MIN(3, argc);
for (i = 1; i < maxindex; i++) {
if (argv[i][0] == '-') {
if (!strncmp(argv[i], "-prestring", 10)) {
nflags++;
ret = sscanf(argv[i] + 1, "prestring=%490s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for prestring\n");
return 1;
}
if ((len = strlen(buf)) > L_BUFSIZE - 3) {
L_WARNING("prestring too large; omitting!\n", mainName);
} else {
buf[len] = ' ';
buf[len + 1] = '\0';
prestring = stringNew(buf);
}
} else if (!strncmp(argv[i], "-protos", 7)) {
nflags++;
ret = sscanf(argv[i] + 1, "protos=%490s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for protos\n");
return 1;
}
outprotos = stringNew(buf);
if (!strncmp(outprotos, "inline", 7))
in_line = TRUE;
}
}
}
if (argc - nflags < 2) {
fprintf(stderr, "no files specified!\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Generate the prototype string */
/* ---------------------------------------------------------------- */
ba = l_byteaCreate(500);
/* First the extern C head */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"/*", L_COPY);
snprintf(buf, L_BUFSIZE,
" * These prototypes were autogen'd by xtractprotos, v. %s",
version);
sarrayAddString(sa, buf, L_COPY);
sarrayAddString(sa, (char *)" */", L_COPY);
sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
/* Then the prototypes */
firstfile = 1 + nflags;
protos_added = FALSE;
if ((tempfile = l_makeTempFilename()) == NULL) {
fprintf(stderr, "failure to make a writeable temp file\n");
return 1;
}
for (i = firstfile; i < argc; i++) {
filein = argv[i];
len = strlen(filein);
if (filein[len - 1] == 'h') /* skip .h files */
continue;
snprintf(buf, L_BUFSIZE, "cpp -ansi -DNO_PROTOS %s %s",
filein, tempfile);
ret = system(buf); /* cpp */
if (ret) {
fprintf(stderr, "cpp failure for %s; continuing\n", filein);
continue;
}
if ((str = parseForProtos(tempfile, prestring)) == NULL) {
fprintf(stderr, "parse failure for %s; continuing\n", filein);
continue;
}
if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */
l_byteaAppendString(ba, str);
protos_added = TRUE;
}
lept_free(str);
}
lept_rmfile(tempfile);
lept_free(tempfile);
/* Lastly the extern C tail */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"}", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
protostr = (char *)l_byteaCopyData(ba, &nbytes);
l_byteaDestroy(&ba);
/* ---------------------------------------------------------------- */
/* Generate the output */
/* ---------------------------------------------------------------- */
if (!outprotos) { /* just write to stdout */
fprintf(stderr, "%s\n", protostr);
lept_free(protostr);
return 0;
}
/* If no protos were found, do nothing further */
if (!protos_added) {
fprintf(stderr, "No protos found\n");
lept_free(protostr);
return 1;
}
/* Make the output files */
ba = l_byteaInitFromFile("allheaders_top.txt");
if (!in_line) {
snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos);
l_byteaAppendString(ba, buf);
l_binaryWrite(outprotos, "w", protostr, nbytes);
} else {
l_byteaAppendString(ba, protostr);
}
ba2 = l_byteaInitFromFile("allheaders_bot.txt");
l_byteaJoin(ba, &ba2);
l_byteaWrite("allheaders.h", ba, 0, 0);
l_byteaDestroy(&ba);
lept_free(protostr);
return 0;
}
| 169,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: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 32) ;
psf->header [psf->headindex++] = (x >> 40) ;
psf->header [psf->headindex++] = (x >> 48) ;
psf->header [psf->headindex++] = (x >> 56) ;
} ;
} /* header_put_le_8byte */
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_le_8byte (SF_PRIVATE *psf, sf_count_t x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = (x >> 16) ;
psf->header.ptr [psf->header.indx++] = (x >> 24) ;
psf->header.ptr [psf->header.indx++] = (x >> 32) ;
psf->header.ptr [psf->header.indx++] = (x >> 40) ;
psf->header.ptr [psf->header.indx++] = (x >> 48) ;
psf->header.ptr [psf->header.indx++] = (x >> 56) ;
} /* header_put_le_8byte */
| 170,056 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoundPool::play(int sampleID, float leftVolume, float rightVolume,
int priority, int loop, float rate)
{
ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
sampleID, leftVolume, rightVolume, priority, loop, rate);
sp<Sample> sample;
SoundChannel* channel;
int channelID;
Mutex::Autolock lock(&mLock);
if (mQuit) {
return 0;
}
sample = findSample(sampleID);
if ((sample == 0) || (sample->state() != Sample::READY)) {
ALOGW(" sample %d not READY", sampleID);
return 0;
}
dump();
channel = allocateChannel_l(priority);
if (!channel) {
ALOGV("No channel allocated");
return 0;
}
channelID = ++mNextChannelID;
ALOGV("play channel %p state = %d", channel, channel->state());
channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
return channelID;
}
Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread
Sample decoding still occurs in SoundPoolThread
without holding the SoundPool lock.
Bug: 25781119
Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
CWE ID: CWE-264 | int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
int priority, int loop, float rate)
{
ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
sampleID, leftVolume, rightVolume, priority, loop, rate);
SoundChannel* channel;
int channelID;
Mutex::Autolock lock(&mLock);
if (mQuit) {
return 0;
}
sp<Sample> sample(findSample_l(sampleID));
if ((sample == 0) || (sample->state() != Sample::READY)) {
ALOGW(" sample %d not READY", sampleID);
return 0;
}
dump();
channel = allocateChannel_l(priority);
if (!channel) {
ALOGV("No channel allocated");
return 0;
}
channelID = ++mNextChannelID;
ALOGV("play channel %p state = %d", channel, channel->state());
channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
return channelID;
}
| 173,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XcursorImageCreate (int width, int height)
{
XcursorImage *image;
image = malloc (sizeof (XcursorImage) +
width * height * sizeof (XcursorPixel));
if (!image)
image->height = height;
image->delay = 0;
return image;
}
Commit Message:
CWE ID: CWE-190 | XcursorImageCreate (int width, int height)
{
XcursorImage *image;
if (width < 0 || height < 0)
return NULL;
if (width > XCURSOR_IMAGE_MAX_SIZE || height > XCURSOR_IMAGE_MAX_SIZE)
return NULL;
image = malloc (sizeof (XcursorImage) +
width * height * sizeof (XcursorPixel));
if (!image)
image->height = height;
image->delay = 0;
return image;
}
| 164,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI,
xsltPreComputeFunction precomp,
xsltTransformFunction transform)
{
int ret;
xsltExtElementPtr ext;
if ((name == NULL) || (URI == NULL) || (transform == NULL))
return (-1);
if (xsltElementsHash == NULL)
xsltElementsHash = xmlHashCreate(10);
if (xsltElementsHash == NULL)
return (-1);
xmlMutexLock(xsltExtMutex);
ext = xsltNewExtElement(precomp, transform);
if (ext == NULL) {
ret = -1;
goto done;
}
xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext,
(xmlHashDeallocator) xsltFreeExtElement);
done:
xmlMutexUnlock(xsltExtMutex);
return (0);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI,
xsltPreComputeFunction precomp,
xsltTransformFunction transform)
{
int ret = 0;
xsltExtElementPtr ext;
if ((name == NULL) || (URI == NULL) || (transform == NULL))
return (-1);
if (xsltElementsHash == NULL)
xsltElementsHash = xmlHashCreate(10);
if (xsltElementsHash == NULL)
return (-1);
xmlMutexLock(xsltExtMutex);
ext = xsltNewExtElement(precomp, transform);
if (ext == NULL) {
ret = -1;
goto done;
}
xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext,
(xmlHashDeallocator) xsltFreeExtElement);
done:
xmlMutexUnlock(xsltExtMutex);
return (ret);
}
| 173,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835 | ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4));
if (ntohs(e.len) > 4) {
if (ndo->ndo_vflag > 2) {
ND_PRINT((ndo, " "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " "));
if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep))
goto trunc;
}
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
| 167,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
enabled_bindings_ |= enabled_bindings_flags;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
enabled_bindings_ |= enabled_bindings_flags;
// Keep track of the total bindings accumulated in this process.
RenderProcess::current()->AddBindings(enabled_bindings_flags);
}
| 171,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: OMX_ERRORTYPE omx_vdec::component_deinit(OMX_IN OMX_HANDLETYPE hComp)
{
(void) hComp;
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
delete iDivXDrmDecrypt;
iDivXDrmDecrypt=NULL;
}
#endif //_ANDROID_
unsigned i = 0;
if (OMX_StateLoaded != m_state) {
DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\
m_state);
DEBUG_PRINT_ERROR("Playback Ended - FAILED");
} else {
DEBUG_PRINT_HIGH("Playback Ended - PASSED");
}
/*Check if the output buffers have to be cleaned up*/
if (m_out_mem_ptr) {
DEBUG_PRINT_LOW("Freeing the Output Memory");
for (i = 0; i < drv_ctx.op_buf.actualcount; i++ ) {
free_output_buffer (&m_out_mem_ptr[i]);
}
#ifdef _ANDROID_ICS_
memset(&native_buffer, 0, (sizeof(nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS));
#endif
}
/*Check if the input buffers have to be cleaned up*/
if (m_inp_mem_ptr || m_inp_heap_ptr) {
DEBUG_PRINT_LOW("Freeing the Input Memory");
for (i = 0; i<drv_ctx.ip_buf.actualcount; i++ ) {
if (m_inp_mem_ptr)
free_input_buffer (i,&m_inp_mem_ptr[i]);
else
free_input_buffer (i,NULL);
}
}
free_input_buffer_header();
free_output_buffer_header();
if (h264_scratch.pBuffer) {
free(h264_scratch.pBuffer);
h264_scratch.pBuffer = NULL;
}
if (h264_parser) {
delete h264_parser;
h264_parser = NULL;
}
if (m_frame_parser.mutils) {
DEBUG_PRINT_LOW("Free utils parser");
delete (m_frame_parser.mutils);
m_frame_parser.mutils = NULL;
}
if (m_platform_list) {
free(m_platform_list);
m_platform_list = NULL;
}
if (m_vendor_config.pData) {
free(m_vendor_config.pData);
m_vendor_config.pData = NULL;
}
m_ftb_q.m_size=0;
m_cmd_q.m_size=0;
m_etb_q.m_size=0;
m_ftb_q.m_read = m_ftb_q.m_write =0;
m_cmd_q.m_read = m_cmd_q.m_write =0;
m_etb_q.m_read = m_etb_q.m_write =0;
#ifdef _ANDROID_
if (m_debug_timestamp) {
m_timestamp_list.reset_ts_list();
}
#endif
DEBUG_PRINT_LOW("Calling VDEC_IOCTL_STOP_NEXT_MSG");
DEBUG_PRINT_HIGH("Close the driver instance");
if (m_debug.infile) {
fclose(m_debug.infile);
m_debug.infile = NULL;
}
if (m_debug.outfile) {
fclose(m_debug.outfile);
m_debug.outfile = NULL;
}
#ifdef OUTPUT_EXTRADATA_LOG
if (outputExtradataFile)
fclose (outputExtradataFile);
#endif
DEBUG_PRINT_INFO("omx_vdec::component_deinit() complete");
return OMX_ErrorNone;
}
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 | OMX_ERRORTYPE omx_vdec::component_deinit(OMX_IN OMX_HANDLETYPE hComp)
{
(void) hComp;
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
delete iDivXDrmDecrypt;
iDivXDrmDecrypt=NULL;
}
#endif //_ANDROID_
unsigned i = 0;
if (OMX_StateLoaded != m_state) {
DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\
m_state);
DEBUG_PRINT_ERROR("Playback Ended - FAILED");
} else {
DEBUG_PRINT_HIGH("Playback Ended - PASSED");
}
/*Check if the output buffers have to be cleaned up*/
if (m_out_mem_ptr) {
DEBUG_PRINT_LOW("Freeing the Output Memory");
for (i = 0; i < drv_ctx.op_buf.actualcount; i++ ) {
if (BITMASK_PRESENT(&m_out_bm_count, i)) {
BITMASK_CLEAR(&m_out_bm_count, i);
client_buffers.free_output_buffer (&m_out_mem_ptr[i]);
}
if (release_output_done()) {
break;
}
}
#ifdef _ANDROID_ICS_
memset(&native_buffer, 0, (sizeof(nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS));
#endif
}
/*Check if the input buffers have to be cleaned up*/
if (m_inp_mem_ptr || m_inp_heap_ptr) {
DEBUG_PRINT_LOW("Freeing the Input Memory");
for (i = 0; i<drv_ctx.ip_buf.actualcount; i++ ) {
if (BITMASK_PRESENT(&m_inp_bm_count, i)) {
BITMASK_CLEAR(&m_inp_bm_count, i);
if (m_inp_mem_ptr)
free_input_buffer (i,&m_inp_mem_ptr[i]);
else
free_input_buffer (i,NULL);
}
if (release_input_done()) {
break;
}
}
}
free_input_buffer_header();
free_output_buffer_header();
if (h264_scratch.pBuffer) {
free(h264_scratch.pBuffer);
h264_scratch.pBuffer = NULL;
}
if (h264_parser) {
delete h264_parser;
h264_parser = NULL;
}
if (m_frame_parser.mutils) {
DEBUG_PRINT_LOW("Free utils parser");
delete (m_frame_parser.mutils);
m_frame_parser.mutils = NULL;
}
if (m_platform_list) {
free(m_platform_list);
m_platform_list = NULL;
}
if (m_vendor_config.pData) {
free(m_vendor_config.pData);
m_vendor_config.pData = NULL;
}
m_ftb_q.m_size=0;
m_cmd_q.m_size=0;
m_etb_q.m_size=0;
m_ftb_q.m_read = m_ftb_q.m_write =0;
m_cmd_q.m_read = m_cmd_q.m_write =0;
m_etb_q.m_read = m_etb_q.m_write =0;
#ifdef _ANDROID_
if (m_debug_timestamp) {
m_timestamp_list.reset_ts_list();
}
#endif
DEBUG_PRINT_LOW("Calling VDEC_IOCTL_STOP_NEXT_MSG");
DEBUG_PRINT_HIGH("Close the driver instance");
if (m_debug.infile) {
fclose(m_debug.infile);
m_debug.infile = NULL;
}
if (m_debug.outfile) {
fclose(m_debug.outfile);
m_debug.outfile = NULL;
}
#ifdef OUTPUT_EXTRADATA_LOG
if (outputExtradataFile)
fclose (outputExtradataFile);
#endif
DEBUG_PRINT_INFO("omx_vdec::component_deinit() complete");
return OMX_ErrorNone;
}
| 173,784 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
const char* name;
size_t namelen;
if (node->graft_path) {
name = node->graft_path;
namelen = node->graft_pathlen;
} else if (node->actual_name) {
name = node->actual_name;
namelen = node->namelen;
} else {
name = node->name;
namelen = node->namelen;
}
if (bufsize < namelen + 1) {
return -1;
}
ssize_t pathlen = 0;
if (node->parent && node->graft_path == NULL) {
pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2);
if (pathlen < 0) {
return -1;
}
buf[pathlen++] = '/';
}
memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
return pathlen + namelen;
}
Commit Message: Fix overflow in path building
An incorrect size was causing an unsigned value
to wrap, causing it to write past the end of
the buffer.
Bug: 28085658
Change-Id: Ie9625c729cca024d514ba2880ff97209d435a165
CWE ID: CWE-264 | static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
const char* name;
size_t namelen;
if (node->graft_path) {
name = node->graft_path;
namelen = node->graft_pathlen;
} else if (node->actual_name) {
name = node->actual_name;
namelen = node->namelen;
} else {
name = node->name;
namelen = node->namelen;
}
if (bufsize < namelen + 1) {
return -1;
}
ssize_t pathlen = 0;
if (node->parent && node->graft_path == NULL) {
pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 1);
if (pathlen < 0) {
return -1;
}
buf[pathlen++] = '/';
}
memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
return pathlen + namelen;
}
| 173,774 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
}
Commit Message: KEYS: prevent KEYCTL_READ on negative key
Because keyctl_read_key() looks up the key with no permissions
requested, it may find a negatively instantiated key. If the key is
also possessed, we went ahead and called ->read() on the key. But the
key payload will actually contain the ->reject_error rather than the
normal payload. Thus, the kernel oopses trying to read the
user_key_payload from memory address (int)-ENOKEY = 0x00000000ffffff82.
Fortunately the payload data is stored inline, so it shouldn't be
possible to abuse this as an arbitrary memory read primitive...
Reproducer:
keyctl new_session
keyctl request2 user desc '' @s
keyctl read $(keyctl show | awk '/user: desc/ {print $1}')
It causes a crash like the following:
BUG: unable to handle kernel paging request at 00000000ffffff92
IP: user_read+0x33/0xa0
PGD 36a54067 P4D 36a54067 PUD 0
Oops: 0000 [#1] SMP
CPU: 0 PID: 211 Comm: keyctl Not tainted 4.14.0-rc1 #337
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014
task: ffff90aa3b74c3c0 task.stack: ffff9878c0478000
RIP: 0010:user_read+0x33/0xa0
RSP: 0018:ffff9878c047bee8 EFLAGS: 00010246
RAX: 0000000000000001 RBX: ffff90aa3d7da340 RCX: 0000000000000017
RDX: 0000000000000000 RSI: 00000000ffffff82 RDI: ffff90aa3d7da340
RBP: ffff9878c047bf00 R08: 00000024f95da94f R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000000
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
FS: 00007f58ece69740(0000) GS:ffff90aa3e200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000ffffff92 CR3: 0000000036adc001 CR4: 00000000003606f0
Call Trace:
keyctl_read_key+0xac/0xe0
SyS_keyctl+0x99/0x120
entry_SYSCALL_64_fastpath+0x1f/0xbe
RIP: 0033:0x7f58ec787bb9
RSP: 002b:00007ffc8d401678 EFLAGS: 00000206 ORIG_RAX: 00000000000000fa
RAX: ffffffffffffffda RBX: 00007ffc8d402800 RCX: 00007f58ec787bb9
RDX: 0000000000000000 RSI: 00000000174a63ac RDI: 000000000000000b
RBP: 0000000000000004 R08: 00007ffc8d402809 R09: 0000000000000020
R10: 0000000000000000 R11: 0000000000000206 R12: 00007ffc8d402800
R13: 00007ffc8d4016e0 R14: 0000000000000000 R15: 0000000000000000
Code: e5 41 55 49 89 f5 41 54 49 89 d4 53 48 89 fb e8 a4 b4 ad ff 85 c0 74 09 80 3d b9 4c 96 00 00 74 43 48 8b b3 20 01 00 00 4d 85 ed <0f> b7 5e 10 74 29 4d 85 e4 74 24 4c 39 e3 4c 89 e2 4c 89 ef 48
RIP: user_read+0x33/0xa0 RSP: ffff9878c047bee8
CR2: 00000000ffffff92
Fixes: 61ea0c0ba904 ("KEYS: Skip key state checks when checking for possession")
Cc: <[email protected]> [v3.13+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-476 | long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {
ret = -ENOKEY;
goto error2;
}
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
}
| 167,987 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChangeInputMethod(const char* name) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "ChangeInputMethod: IBus connection is not alive";
return false;
}
if (!name) {
return false;
}
if (!InputMethodIdIsWhitelisted(name)) {
LOG(ERROR) << "Input method '" << name << "' is not supported";
return false;
}
RegisterProperties(NULL);
ibus_bus_set_global_engine_async(ibus_,
name,
-1, // use the default ibus timeout
NULL, // cancellable
NULL, // callback
NULL); // user_data
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ChangeInputMethod(const char* name) {
// IBusController override.
virtual bool ChangeInputMethod(const std::string& name) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "ChangeInputMethod: IBus connection is not alive";
return false;
}
if (name.empty()) {
return false;
}
if (!InputMethodIdIsWhitelisted(name)) {
LOG(ERROR) << "Input method '" << name << "' is not supported";
return false;
}
DoRegisterProperties(NULL);
ibus_bus_set_global_engine_async(ibus_,
name.c_str(),
-1, // use the default ibus timeout
NULL, // cancellable
NULL, // callback
NULL); // user_data
return true;
}
| 170,519 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_policy_2_svc(gpol_arg *arg, struct svc_req *rqstp)
{
static gpol_ret ret;
kadm5_ret_t ret2;
char *prime_arg, *funcname;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_principal_ent_rec caller_ent;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gpol_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_policy";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->name;
ret.code = KADM5_AUTH_GET;
if (!CHANGEPW_SERVICE(rqstp) && kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE, NULL, NULL))
ret.code = KADM5_OK;
else {
ret.code = kadm5_get_principal(handle->lhandle,
handle->current_caller,
&caller_ent,
KADM5_PRINCIPAL_NORMAL_MASK);
if (ret.code == KADM5_OK) {
if (caller_ent.aux_attributes & KADM5_POLICY &&
strcmp(caller_ent.policy, arg->name) == 0) {
ret.code = KADM5_OK;
} else ret.code = KADM5_AUTH_GET;
ret2 = kadm5_free_principal_ent(handle->lhandle,
&caller_ent);
ret.code = ret.code ? ret.code : ret2;
}
}
if (ret.code == KADM5_OK) {
ret.code = kadm5_get_policy(handle, arg->name, &ret.rec);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname,
((prime_arg == NULL) ? "(null)" : prime_arg), errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
} else {
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
}
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_policy_2_svc(gpol_arg *arg, struct svc_req *rqstp)
{
static gpol_ret ret;
kadm5_ret_t ret2;
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_principal_ent_rec caller_ent;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gpol_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_policy";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->name;
ret.code = KADM5_AUTH_GET;
if (!CHANGEPW_SERVICE(rqstp) && kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE, NULL, NULL))
ret.code = KADM5_OK;
else {
ret.code = kadm5_get_principal(handle->lhandle,
handle->current_caller,
&caller_ent,
KADM5_PRINCIPAL_NORMAL_MASK);
if (ret.code == KADM5_OK) {
if (caller_ent.aux_attributes & KADM5_POLICY &&
strcmp(caller_ent.policy, arg->name) == 0) {
ret.code = KADM5_OK;
} else ret.code = KADM5_AUTH_GET;
ret2 = kadm5_free_principal_ent(handle->lhandle,
&caller_ent);
ret.code = ret.code ? ret.code : ret2;
}
}
if (ret.code == KADM5_OK) {
ret.code = kadm5_get_policy(handle, arg->name, &ret.rec);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname,
((prime_arg == NULL) ? "(null)" : prime_arg), errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
} else {
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
}
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,513 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness)
{
notImplemented();
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness)
void GraphicsContext::addInnerRoundedRectClip(const IntRect& r, int thickness)
{
if (paintingDisabled())
return;
FloatRect rect(r);
clip(rect);
Path path;
path.addEllipse(rect);
rect.inflate(-thickness);
path.addEllipse(rect);
clipPath(path, RULE_EVENODD);
}
| 170,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nfs4_return_incompatible_delegation(struct inode *inode, mode_t open_flags)
{
struct nfs_delegation *delegation;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(inode)->delegation);
if (delegation == NULL || (delegation->type & open_flags) == open_flags) {
rcu_read_unlock();
return;
}
rcu_read_unlock();
nfs_inode_return_delegation(inode);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs4_return_incompatible_delegation(struct inode *inode, mode_t open_flags)
static void nfs4_return_incompatible_delegation(struct inode *inode, fmode_t fmode)
{
struct nfs_delegation *delegation;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(inode)->delegation);
if (delegation == NULL || (delegation->type & fmode) == fmode) {
rcu_read_unlock();
return;
}
rcu_read_unlock();
nfs_inode_return_delegation(inode);
}
| 165,703 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
Commit Message: aio: fix kernel memory disclosure in io_getevents() introduced in v3.10
A kernel memory disclosure was introduced in aio_read_events_ring() in v3.10
by commit a31ad380bed817aa25f8830ad23e1a0480fef797. The changes made to
aio_read_events_ring() failed to correctly limit the index into
ctx->ring_pages[], allowing an attacked to cause the subsequent kmap() of
an arbitrary page with a copy_to_user() to copy the contents into userspace.
This vulnerability has been assigned CVE-2014-0206. Thanks to Mateusz and
Petr for disclosing this issue.
This patch applies to v3.12+. A separate backport is needed for 3.10/3.11.
Signed-off-by: Benjamin LaHaise <[email protected]>
Cc: Mateusz Guzik <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Kent Overstreet <[email protected]>
Cc: Jeff Moyer <[email protected]>
Cc: [email protected]
CWE ID: | static long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
head %= ctx->nr_events;
tail %= ctx->nr_events;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
| 166,448 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PixelBufferRasterWorkerPool::OnRasterTasksFinished() {
if (!should_notify_client_if_no_tasks_are_pending_)
return;
CheckForCompletedRasterTasks();
}
Commit Message: cc: Simplify raster task completion notification logic
(Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/)
Previously the pixel buffer raster worker pool used a combination of
polling and explicit notifications from the raster worker pool to decide
when to tell the client about the completion of 1) all tasks or 2) the
subset of tasks required for activation. This patch simplifies the logic
by only triggering the notification based on the OnRasterTasksFinished
and OnRasterTasksRequiredForActivationFinished calls from the worker
pool.
BUG=307841,331534
Review URL: https://codereview.chromium.org/99873007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void PixelBufferRasterWorkerPool::OnRasterTasksFinished() {
if (!should_notify_client_if_no_tasks_are_pending_)
return;
raster_finished_task_pending_ = false;
CheckForCompletedRasterTasks();
}
| 171,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: int rpc_type_of_NPNVariable(int variable)
{
int type;
switch (variable) {
case NPNVjavascriptEnabledBool:
case NPNVasdEnabledBool:
case NPNVisOfflineBool:
case NPNVSupportsXEmbedBool:
case NPNVSupportsWindowless:
type = RPC_TYPE_BOOLEAN;
break;
case NPNVToolkit:
case NPNVnetscapeWindow:
type = RPC_TYPE_UINT32;
break;
case NPNVWindowNPObject:
case NPNVPluginElementNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
Commit Message: Support all the new variables added
CWE ID: CWE-264 | int rpc_type_of_NPNVariable(int variable)
{
int type;
switch (variable) {
case NPNVjavascriptEnabledBool:
case NPNVasdEnabledBool:
case NPNVisOfflineBool:
case NPNVSupportsXEmbedBool:
case NPNVSupportsWindowless:
case NPNVprivateModeBool:
case NPNVsupportsAdvancedKeyHandling:
type = RPC_TYPE_BOOLEAN;
break;
case NPNVToolkit:
case NPNVnetscapeWindow:
type = RPC_TYPE_UINT32;
break;
case NPNVWindowNPObject:
case NPNVPluginElementNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
}
| 165,862 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct inode *isofs_iget(struct super_block *sb,
unsigned long block,
unsigned long offset)
{
unsigned long hashval;
struct inode *inode;
struct isofs_iget5_callback_data data;
long ret;
if (offset >= 1ul << sb->s_blocksize_bits)
return ERR_PTR(-EINVAL);
data.block = block;
data.offset = offset;
hashval = (block << sb->s_blocksize_bits) | offset;
inode = iget5_locked(sb, hashval, &isofs_iget5_test,
&isofs_iget5_set, &data);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
ret = isofs_read_inode(inode);
if (ret < 0) {
iget_failed(inode);
inode = ERR_PTR(ret);
} else {
unlock_new_inode(inode);
}
}
return inode;
}
Commit Message: isofs: Fix unbounded recursion when processing relocated directories
We did not check relocated directory in any way when processing Rock
Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL
entry pointing to another CL entry leading to possibly unbounded
recursion in kernel code and thus stack overflow or deadlocks (if there
is a loop created from CL entries).
Fix the problem by not allowing CL entry to point to a directory entry
with CL entry (such use makes no good sense anyway) and by checking
whether CL entry doesn't point to itself.
CC: [email protected]
Reported-by: Chris Evans <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-20 | struct inode *isofs_iget(struct super_block *sb,
struct inode *__isofs_iget(struct super_block *sb,
unsigned long block,
unsigned long offset,
int relocated)
{
unsigned long hashval;
struct inode *inode;
struct isofs_iget5_callback_data data;
long ret;
if (offset >= 1ul << sb->s_blocksize_bits)
return ERR_PTR(-EINVAL);
data.block = block;
data.offset = offset;
hashval = (block << sb->s_blocksize_bits) | offset;
inode = iget5_locked(sb, hashval, &isofs_iget5_test,
&isofs_iget5_set, &data);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
ret = isofs_read_inode(inode, relocated);
if (ret < 0) {
iget_failed(inode);
inode = ERR_PTR(ret);
} else {
unlock_new_inode(inode);
}
}
return inode;
}
| 166,268 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr3_leaf_list_int(
struct xfs_buf *bp,
struct xfs_attr_list_context *context)
{
struct attrlist_cursor_kern *cursor;
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_entry *entry;
int retval;
int i;
trace_xfs_attr_list_leaf(context);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
cursor = context->cursor;
cursor->initted = 1;
/*
* Re-find our place in the leaf block if this is a new syscall.
*/
if (context->resynch) {
entry = &entries[0];
for (i = 0; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) == cursor->hashval) {
if (cursor->offset == context->dupcnt) {
context->dupcnt = 0;
break;
}
context->dupcnt++;
} else if (be32_to_cpu(entry->hashval) >
cursor->hashval) {
context->dupcnt = 0;
break;
}
}
if (i == ichdr.count) {
trace_xfs_attr_list_notfound(context);
return 0;
}
} else {
entry = &entries[0];
i = 0;
}
context->resynch = 0;
/*
* We have found our place, start copying out the new attributes.
*/
retval = 0;
for (; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) != cursor->hashval) {
cursor->hashval = be32_to_cpu(entry->hashval);
cursor->offset = 0;
}
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* skip incomplete entries */
if (entry->flags & XFS_ATTR_LOCAL) {
xfs_attr_leaf_name_local_t *name_loc =
xfs_attr3_leaf_name_local(leaf, i);
retval = context->put_listent(context,
entry->flags,
name_loc->nameval,
(int)name_loc->namelen,
be16_to_cpu(name_loc->valuelen),
&name_loc->nameval[name_loc->namelen]);
if (retval)
return retval;
} else {
xfs_attr_leaf_name_remote_t *name_rmt =
xfs_attr3_leaf_name_remote(leaf, i);
int valuelen = be32_to_cpu(name_rmt->valuelen);
if (context->put_value) {
xfs_da_args_t args;
memset((char *)&args, 0, sizeof(args));
args.dp = context->dp;
args.whichfork = XFS_ATTR_FORK;
args.valuelen = valuelen;
args.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS);
args.rmtblkno = be32_to_cpu(name_rmt->valueblk);
args.rmtblkcnt = xfs_attr3_rmt_blocks(
args.dp->i_mount, valuelen);
retval = xfs_attr_rmtval_get(&args);
if (retval)
return retval;
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
args.value);
kmem_free(args.value);
} else {
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
NULL);
}
if (retval)
return retval;
}
if (context->seen_enough)
break;
cursor->offset++;
}
trace_xfs_attr_list_leaf_end(context);
return retval;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr3_leaf_list_int(
struct xfs_buf *bp,
struct xfs_attr_list_context *context)
{
struct attrlist_cursor_kern *cursor;
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_entry *entry;
int retval;
int i;
trace_xfs_attr_list_leaf(context);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
cursor = context->cursor;
cursor->initted = 1;
/*
* Re-find our place in the leaf block if this is a new syscall.
*/
if (context->resynch) {
entry = &entries[0];
for (i = 0; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) == cursor->hashval) {
if (cursor->offset == context->dupcnt) {
context->dupcnt = 0;
break;
}
context->dupcnt++;
} else if (be32_to_cpu(entry->hashval) >
cursor->hashval) {
context->dupcnt = 0;
break;
}
}
if (i == ichdr.count) {
trace_xfs_attr_list_notfound(context);
return 0;
}
} else {
entry = &entries[0];
i = 0;
}
context->resynch = 0;
/*
* We have found our place, start copying out the new attributes.
*/
retval = 0;
for (; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) != cursor->hashval) {
cursor->hashval = be32_to_cpu(entry->hashval);
cursor->offset = 0;
}
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* skip incomplete entries */
if (entry->flags & XFS_ATTR_LOCAL) {
xfs_attr_leaf_name_local_t *name_loc =
xfs_attr3_leaf_name_local(leaf, i);
retval = context->put_listent(context,
entry->flags,
name_loc->nameval,
(int)name_loc->namelen,
be16_to_cpu(name_loc->valuelen),
&name_loc->nameval[name_loc->namelen]);
if (retval)
return retval;
} else {
xfs_attr_leaf_name_remote_t *name_rmt =
xfs_attr3_leaf_name_remote(leaf, i);
int valuelen = be32_to_cpu(name_rmt->valuelen);
if (context->put_value) {
xfs_da_args_t args;
memset((char *)&args, 0, sizeof(args));
args.dp = context->dp;
args.whichfork = XFS_ATTR_FORK;
args.valuelen = valuelen;
args.rmtvaluelen = valuelen;
args.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS);
args.rmtblkno = be32_to_cpu(name_rmt->valueblk);
args.rmtblkcnt = xfs_attr3_rmt_blocks(
args.dp->i_mount, valuelen);
retval = xfs_attr_rmtval_get(&args);
if (retval)
return retval;
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
args.value);
kmem_free(args.value);
} else {
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
NULL);
}
if (retval)
return retval;
}
if (context->seen_enough)
break;
cursor->offset++;
}
trace_xfs_attr_list_leaf_end(context);
return retval;
}
| 166,738 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LauncherView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) {
FOR_EACH_OBSERVER(LauncherIconObserver, observers_,
OnLauncherIconPositionsChanged());
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void LauncherView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) {
FOR_EACH_OBSERVER(LauncherIconObserver, observers_,
OnLauncherIconPositionsChanged());
PreferredSizeChanged();
}
| 170,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string ProcessRawBytesWithSeparators(const unsigned char* data,
size_t data_length,
char hex_separator,
char line_separator) {
static const char kHexChars[] = "0123456789ABCDEF";
std::string ret;
size_t kMin = 0U;
ret.reserve(std::max(kMin, data_length * 3 - 1));
for (size_t i = 0; i < data_length; ++i) {
unsigned char b = data[i];
ret.push_back(kHexChars[(b >> 4) & 0xf]);
ret.push_back(kHexChars[b & 0xf]);
if (i + 1 < data_length) {
if ((i + 1) % 16 == 0)
ret.push_back(line_separator);
else
ret.push_back(hex_separator);
}
}
return ret;
}
Commit Message: return early from ProcessRawBytesWithSeperators() when data length is 0
BUG=109717
TEST=N/A
Review URL: http://codereview.chromium.org/9169028
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@117241 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | std::string ProcessRawBytesWithSeparators(const unsigned char* data,
size_t data_length,
char hex_separator,
char line_separator) {
static const char kHexChars[] = "0123456789ABCDEF";
std::string ret;
size_t kMin = 0U;
if (!data_length)
return "";
ret.reserve(std::max(kMin, data_length * 3 - 1));
for (size_t i = 0; i < data_length; ++i) {
unsigned char b = data[i];
ret.push_back(kHexChars[(b >> 4) & 0xf]);
ret.push_back(kHexChars[b & 0xf]);
if (i + 1 < data_length) {
if ((i + 1) % 16 == 0)
ret.push_back(line_separator);
else
ret.push_back(hex_separator);
}
}
return ret;
}
| 170,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: int main(int argc, char *argv[])
{
FILE *fp_rd = stdin;
FILE *fp_wr = stdout;
FILE *fp_al = NULL;
BOOL raw = TRUE;
BOOL alpha = FALSE;
int argi;
for (argi = 1; argi < argc; argi++)
{
if (argv[argi][0] == '-')
{
switch (argv[argi][1])
{
case 'n':
raw = FALSE;
break;
case 'r':
raw = TRUE;
break;
case 'a':
alpha = TRUE;
argi++;
if ((fp_al = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]);
exit (1);
}
break;
case 'h':
case '?':
usage();
exit(0);
break;
default:
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unknown option %s\n", argv[argi]);
usage();
exit(1);
break;
} /* end switch */
}
else if (fp_rd == stdin)
{
if ((fp_rd = fopen (argv[argi], "rb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: file %s does not exist\n", argv[argi]);
exit (1);
}
}
else if (fp_wr == stdout)
{
if ((fp_wr = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: can not create file %s\n", argv[argi]);
exit (1);
}
}
else
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: too many parameters\n");
usage();
exit(1);
}
} /* end for */
#ifdef __TURBOC__
/* set stdin/stdout if required to binary */
if (fp_rd == stdin)
{
setmode (STDIN, O_BINARY);
}
if ((raw) && (fp_wr == stdout))
{
setmode (STDOUT, O_BINARY);
}
#endif
/* call the conversion program itself */
if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n");
exit(1);
}
/* close input file */
fclose (fp_rd);
/* close output file */
fclose (fp_wr);
/* close alpha file */
if (alpha)
fclose (fp_al);
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: | int main(int argc, char *argv[])
{
FILE *fp_rd = stdin;
FILE *fp_wr = stdout;
FILE *fp_al = NULL;
BOOL raw = TRUE;
BOOL alpha = FALSE;
int argi;
for (argi = 1; argi < argc; argi++)
{
if (argv[argi][0] == '-')
{
switch (argv[argi][1])
{
case 'n':
raw = FALSE;
break;
case 'r':
raw = TRUE;
break;
case 'a':
alpha = TRUE;
argi++;
if ((fp_al = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, "Error: can not create alpha-channel file %s\n",
argv[argi]);
exit (1);
}
break;
case 'h':
case '?':
usage();
exit(0);
break;
default:
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unknown option %s\n", argv[argi]);
usage();
exit(1);
break;
} /* end switch */
}
else if (fp_rd == stdin)
{
if ((fp_rd = fopen (argv[argi], "rb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: file %s does not exist\n", argv[argi]);
exit (1);
}
}
else if (fp_wr == stdout)
{
if ((fp_wr = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: can not create file %s\n", argv[argi]);
exit (1);
}
}
else
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: too many parameters\n");
usage();
exit(1);
}
} /* end for */
#ifdef __TURBOC__
/* set stdin/stdout if required to binary */
if (fp_rd == stdin)
{
setmode (STDIN, O_BINARY);
}
if ((raw) && (fp_wr == stdout))
{
setmode (STDOUT, O_BINARY);
}
#endif
/* call the conversion program itself */
if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n");
exit(1);
}
/* close input file */
fclose (fp_rd);
/* close output file */
fclose (fp_wr);
/* close alpha file */
if (alpha)
fclose (fp_al);
return 0;
}
| 173,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pseudo_ulog( ClassAd *ad )
{
ULogEvent *event = instantiateEvent(ad);
int result = 0;
char const *critical_error = NULL;
MyString CriticalErrorBuf;
bool event_already_logged = false;
bool put_job_on_hold = false;
char const *hold_reason = NULL;
char *hold_reason_buf = NULL;
int hold_reason_code = 0;
int hold_reason_sub_code = 0;
if(!event) {
MyString add_str;
ad->sPrint(add_str);
dprintf(
D_ALWAYS,
"invalid event ClassAd in pseudo_ulog: %s\n",
add_str.Value());
return -1;
}
if(ad->LookupInteger(ATTR_HOLD_REASON_CODE,hold_reason_code)) {
put_job_on_hold = true;
ad->LookupInteger(ATTR_HOLD_REASON_SUBCODE,hold_reason_sub_code);
ad->LookupString(ATTR_HOLD_REASON,&hold_reason_buf);
if(hold_reason_buf) {
hold_reason = hold_reason_buf;
}
}
if( event->eventNumber == ULOG_REMOTE_ERROR ) {
RemoteErrorEvent *err = (RemoteErrorEvent *)event;
if(!err->getExecuteHost() || !*err->getExecuteHost()) {
char *execute_host = NULL;
thisRemoteResource->getMachineName(execute_host);
err->setExecuteHost(execute_host);
delete[] execute_host;
}
if(err->isCriticalError()) {
CriticalErrorBuf.sprintf(
"Error from %s: %s",
err->getExecuteHost(),
err->getErrorText());
critical_error = CriticalErrorBuf.Value();
if(!hold_reason) {
hold_reason = critical_error;
}
BaseShadow::log_except(critical_error);
event_already_logged = true;
}
}
if( !event_already_logged && !Shadow->uLog.writeEvent( event, ad ) ) {
MyString add_str;
ad->sPrint(add_str);
dprintf(
D_ALWAYS,
"unable to log event in pseudo_ulog: %s\n",
add_str.Value());
result = -1;
}
if(put_job_on_hold) {
hold_reason = critical_error;
if(!hold_reason) {
hold_reason = "Job put on hold by remote host.";
}
Shadow->holdJobAndExit(hold_reason,hold_reason_code,hold_reason_sub_code);
}
if( critical_error ) {
Shadow->exception_already_logged = true;
EXCEPT(critical_error);
}
delete event;
return result;
}
Commit Message:
CWE ID: CWE-134 | pseudo_ulog( ClassAd *ad )
{
ULogEvent *event = instantiateEvent(ad);
int result = 0;
char const *critical_error = NULL;
MyString CriticalErrorBuf;
bool event_already_logged = false;
bool put_job_on_hold = false;
char const *hold_reason = NULL;
char *hold_reason_buf = NULL;
int hold_reason_code = 0;
int hold_reason_sub_code = 0;
if(!event) {
MyString add_str;
ad->sPrint(add_str);
dprintf(
D_ALWAYS,
"invalid event ClassAd in pseudo_ulog: %s\n",
add_str.Value());
return -1;
}
if(ad->LookupInteger(ATTR_HOLD_REASON_CODE,hold_reason_code)) {
put_job_on_hold = true;
ad->LookupInteger(ATTR_HOLD_REASON_SUBCODE,hold_reason_sub_code);
ad->LookupString(ATTR_HOLD_REASON,&hold_reason_buf);
if(hold_reason_buf) {
hold_reason = hold_reason_buf;
}
}
if( event->eventNumber == ULOG_REMOTE_ERROR ) {
RemoteErrorEvent *err = (RemoteErrorEvent *)event;
if(!err->getExecuteHost() || !*err->getExecuteHost()) {
char *execute_host = NULL;
thisRemoteResource->getMachineName(execute_host);
err->setExecuteHost(execute_host);
delete[] execute_host;
}
if(err->isCriticalError()) {
CriticalErrorBuf.sprintf(
"Error from %s: %s",
err->getExecuteHost(),
err->getErrorText());
critical_error = CriticalErrorBuf.Value();
if(!hold_reason) {
hold_reason = critical_error;
}
BaseShadow::log_except(critical_error);
event_already_logged = true;
}
}
if( !event_already_logged && !Shadow->uLog.writeEvent( event, ad ) ) {
MyString add_str;
ad->sPrint(add_str);
dprintf(
D_ALWAYS,
"unable to log event in pseudo_ulog: %s\n",
add_str.Value());
result = -1;
}
if(put_job_on_hold) {
hold_reason = critical_error;
if(!hold_reason) {
hold_reason = "Job put on hold by remote host.";
}
Shadow->holdJobAndExit(hold_reason,hold_reason_code,hold_reason_sub_code);
}
if( critical_error ) {
Shadow->exception_already_logged = true;
EXCEPT("%s", critical_error);
}
delete event;
return result;
}
| 165,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */
{
va_list va;
char *message = NULL;
va_start(va, format);
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
zend_throw_error(exception_ce, message);
} else {
zend_error(E_ERROR, "%s", message);
}
efree(message);
va_end(va);
}
/* }}} */
Commit Message: Use format string
CWE ID: CWE-134 | static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */
{
va_list va;
char *message = NULL;
va_start(va, format);
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
zend_throw_error(exception_ce, "%s", message);
} else {
zend_error(E_ERROR, "%s", message);
}
efree(message);
va_end(va);
}
/* }}} */
| 167,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: sec_recv(RD_BOOL * is_fastpath)
{
uint8 fastpath_hdr, fastpath_flags;
uint16 sec_flags;
uint16 channel;
STREAM s;
while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)
{
if (*is_fastpath == True)
{
/* If fastpath packet is encrypted, read data
signature and decrypt */
/* FIXME: extracting flags from hdr could be made less obscure */
fastpath_flags = (fastpath_hdr & 0xC0) >> 6;
if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)
{
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
return s;
}
if (g_encryption || (!g_licence_issued && !g_licence_error_result))
{
/* TS_SECURITY_HEADER */
in_uint16_le(s, sec_flags);
in_uint8s(s, 2); /* skip sec_flags_hi */
if (g_encryption)
{
if (sec_flags & SEC_ENCRYPT)
{
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
if (sec_flags & SEC_REDIRECTION_PKT)
{
uint8 swapbyte;
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
/* Check for a redirect packet, starts with 00 04 */
if (s->p[0] == 0 && s->p[1] == 4)
{
/* for some reason the PDU and the length seem to be swapped.
This isn't good, but we're going to do a byte for byte
swap. So the first four value appear as: 00 04 XX YY,
where XX YY is the little endian length. We're going to
use 04 00 as the PDU type, so after our swap this will look
like: XX YY 04 00 */
swapbyte = s->p[0];
s->p[0] = s->p[2];
s->p[2] = swapbyte;
swapbyte = s->p[1];
s->p[1] = s->p[3];
s->p[3] = swapbyte;
swapbyte = s->p[2];
s->p[2] = s->p[3];
s->p[3] = swapbyte;
}
}
}
else
{
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
s->p -= 4;
}
}
if (channel != MCS_GLOBAL_CHANNEL)
{
channel_process(s, channel);
continue;
}
return s;
}
return NULL;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | sec_recv(RD_BOOL * is_fastpath)
{
uint8 fastpath_hdr, fastpath_flags;
uint16 sec_flags;
uint16 channel;
STREAM s;
struct stream packet;
while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)
{
packet = *s;
if (*is_fastpath == True)
{
/* If fastpath packet is encrypted, read data
signature and decrypt */
/* FIXME: extracting flags from hdr could be made less obscure */
fastpath_flags = (fastpath_hdr & 0xC0) >> 6;
if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)
{
if (!s_check_rem(s, 8)) {
rdp_protocol_error("sec_recv(), consume fastpath signature from stream would overrun", &packet);
}
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
return s;
}
if (g_encryption || (!g_licence_issued && !g_licence_error_result))
{
/* TS_SECURITY_HEADER */
in_uint16_le(s, sec_flags);
in_uint8s(s, 2); /* skip sec_flags_hi */
if (g_encryption)
{
if (sec_flags & SEC_ENCRYPT)
{
if (!s_check_rem(s, 8)) {
rdp_protocol_error("sec_recv(), consume encrypt signature from stream would overrun", &packet);
}
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
if (sec_flags & SEC_REDIRECTION_PKT)
{
uint8 swapbyte;
if (!s_check_rem(s, 8)) {
rdp_protocol_error("sec_recv(), consume redirect signature from stream would overrun", &packet);
}
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
/* Check for a redirect packet, starts with 00 04 */
if (s->p[0] == 0 && s->p[1] == 4)
{
/* for some reason the PDU and the length seem to be swapped.
This isn't good, but we're going to do a byte for byte
swap. So the first four value appear as: 00 04 XX YY,
where XX YY is the little endian length. We're going to
use 04 00 as the PDU type, so after our swap this will look
like: XX YY 04 00 */
swapbyte = s->p[0];
s->p[0] = s->p[2];
s->p[2] = swapbyte;
swapbyte = s->p[1];
s->p[1] = s->p[3];
s->p[3] = swapbyte;
swapbyte = s->p[2];
s->p[2] = s->p[3];
s->p[3] = swapbyte;
}
}
}
else
{
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
s->p -= 4;
}
}
if (channel != MCS_GLOBAL_CHANNEL)
{
channel_process(s, channel);
continue;
}
return s;
}
return NULL;
}
| 169,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler->opaque;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
Commit Message: fixed local DoS when UnregisterHandler was called for a not existing handler
Any user with DBUS access could cause a SEGFAULT in tcmu-runner by
running something like this:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123
CWE ID: CWE-20 | on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
| 167,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: static int rock_continue(struct rock_state *rs)
{
int ret = 1;
int blocksize = 1 << rs->inode->i_blkbits;
const int min_de_size = offsetof(struct rock_ridge, u);
kfree(rs->buffer);
rs->buffer = NULL;
if ((unsigned)rs->cont_offset > blocksize - min_de_size ||
(unsigned)rs->cont_size > blocksize ||
(unsigned)(rs->cont_offset + rs->cont_size) > blocksize) {
printk(KERN_NOTICE "rock: corrupted directory entry. "
"extent=%d, offset=%d, size=%d\n",
rs->cont_extent, rs->cont_offset, rs->cont_size);
ret = -EIO;
goto out;
}
if (rs->cont_extent) {
struct buffer_head *bh;
rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL);
if (!rs->buffer) {
ret = -ENOMEM;
goto out;
}
ret = -EIO;
bh = sb_bread(rs->inode->i_sb, rs->cont_extent);
if (bh) {
memcpy(rs->buffer, bh->b_data + rs->cont_offset,
rs->cont_size);
put_bh(bh);
rs->chr = rs->buffer;
rs->len = rs->cont_size;
rs->cont_extent = 0;
rs->cont_size = 0;
rs->cont_offset = 0;
return 0;
}
printk("Unable to read rock-ridge attributes\n");
}
out:
kfree(rs->buffer);
rs->buffer = NULL;
return ret;
}
Commit Message: isofs: Fix infinite looping over CE entries
Rock Ridge extensions define so called Continuation Entries (CE) which
define where is further space with Rock Ridge data. Corrupted isofs
image can contain arbitrarily long chain of these, including a one
containing loop and thus causing kernel to end in an infinite loop when
traversing these entries.
Limit the traversal to 32 entries which should be more than enough space
to store all the Rock Ridge data.
Reported-by: P J P <[email protected]>
CC: [email protected]
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-399 | static int rock_continue(struct rock_state *rs)
{
int ret = 1;
int blocksize = 1 << rs->inode->i_blkbits;
const int min_de_size = offsetof(struct rock_ridge, u);
kfree(rs->buffer);
rs->buffer = NULL;
if ((unsigned)rs->cont_offset > blocksize - min_de_size ||
(unsigned)rs->cont_size > blocksize ||
(unsigned)(rs->cont_offset + rs->cont_size) > blocksize) {
printk(KERN_NOTICE "rock: corrupted directory entry. "
"extent=%d, offset=%d, size=%d\n",
rs->cont_extent, rs->cont_offset, rs->cont_size);
ret = -EIO;
goto out;
}
if (rs->cont_extent) {
struct buffer_head *bh;
rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL);
if (!rs->buffer) {
ret = -ENOMEM;
goto out;
}
ret = -EIO;
if (++rs->cont_loops >= RR_MAX_CE_ENTRIES)
goto out;
bh = sb_bread(rs->inode->i_sb, rs->cont_extent);
if (bh) {
memcpy(rs->buffer, bh->b_data + rs->cont_offset,
rs->cont_size);
put_bh(bh);
rs->chr = rs->buffer;
rs->len = rs->cont_size;
rs->cont_extent = 0;
rs->cont_size = 0;
rs->cont_offset = 0;
return 0;
}
printk("Unable to read rock-ridge attributes\n");
}
out:
kfree(rs->buffer);
rs->buffer = NULL;
return ret;
}
| 166,236 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: V4L2JpegEncodeAccelerator::JobRecord::JobRecord(
scoped_refptr<VideoFrame> input_frame,
scoped_refptr<VideoFrame> output_frame,
int quality,
int32_t task_id,
BitstreamBuffer* exif_buffer)
: input_frame(input_frame),
output_frame(output_frame),
quality(quality),
task_id(task_id),
output_shm(base::SharedMemoryHandle(), 0, true), // dummy
exif_shm(nullptr) {
if (exif_buffer) {
exif_shm.reset(new UnalignedSharedMemory(exif_buffer->TakeRegion(),
exif_buffer->size(), false));
exif_offset = exif_buffer->offset();
}
}
Commit Message: media: remove base::SharedMemoryHandle usage in v4l2 encoder
This replaces a use of the legacy UnalignedSharedMemory ctor
taking a SharedMemoryHandle with the current ctor taking a
PlatformSharedMemoryRegion.
Bug: 849207
Change-Id: Iea24ebdcd941cf2fa97e19cf2aeac1a18f9773d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1697602
Commit-Queue: Matthew Cary (CET) <[email protected]>
Reviewed-by: Ricky Liang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#681740}
CWE ID: CWE-20 | V4L2JpegEncodeAccelerator::JobRecord::JobRecord(
scoped_refptr<VideoFrame> input_frame,
scoped_refptr<VideoFrame> output_frame,
int quality,
int32_t task_id,
BitstreamBuffer* exif_buffer)
: input_frame(input_frame),
output_frame(output_frame),
quality(quality),
task_id(task_id),
output_shm(base::subtle::PlatformSharedMemoryRegion(), 0, true), // dummy
exif_shm(nullptr) {
if (exif_buffer) {
exif_shm.reset(new UnalignedSharedMemory(exif_buffer->TakeRegion(),
exif_buffer->size(), false));
exif_offset = exif_buffer->offset();
}
}
| 172,318 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 schedule_debug(struct task_struct *prev)
{
#ifdef CONFIG_SCHED_STACK_END_CHECK
BUG_ON(task_stack_end_corrupted(prev));
#endif
if (unlikely(in_atomic_preempt_off())) {
__schedule_bug(prev);
preempt_count_set(PREEMPT_DISABLED);
}
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119 | static inline void schedule_debug(struct task_struct *prev)
{
#ifdef CONFIG_SCHED_STACK_END_CHECK
if (task_stack_end_corrupted(prev))
panic("corrupted stack end detected inside scheduler\n");
#endif
if (unlikely(in_atomic_preempt_off())) {
__schedule_bug(prev);
preempt_count_set(PREEMPT_DISABLED);
}
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
| 167,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
unsigned long tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas Bellinger <[email protected]>
CWE ID: CWE-119 | vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
u16 tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtou16(name + 5, 10, &tpgt) || tpgt >= VHOST_SCSI_MAX_TARGET)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
| 166,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: valid_host(cupsd_client_t *con) /* I - Client connection */
{
cupsd_alias_t *a; /* Current alias */
cupsd_netif_t *netif; /* Current network interface */
const char *end; /* End character */
char *ptr; /* Pointer into host value */
/*
* Copy the Host: header for later use...
*/
strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
sizeof(con->clientname));
if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
{
*ptr++ = '\0';
con->clientport = atoi(ptr);
}
else
con->clientport = con->serverport;
/*
* Then validate...
*/
if (httpAddrLocalhost(httpGetAddress(con->http)))
{
/*
* Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
* addresses when accessing CUPS via the loopback interface...
*/
return (!_cups_strcasecmp(con->clientname, "localhost") ||
!_cups_strcasecmp(con->clientname, "localhost.") ||
#ifdef __linux
!_cups_strcasecmp(con->clientname, "localhost.localdomain") ||
#endif /* __linux */
!strcmp(con->clientname, "127.0.0.1") ||
!strcmp(con->clientname, "[::1]"));
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
/*
* Check if the hostname is something.local (Bonjour); if so, allow it.
*/
if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
!end[1])
{
/*
* "." on end, work back to second-to-last "."...
*/
for (end --; end > con->clientname && *end != '.'; end --);
}
if (end && (!_cups_strcasecmp(end, ".local") ||
!_cups_strcasecmp(end, ".local.")))
return (1);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check if the hostname is an IP address...
*/
if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
{
/*
* Possible IPv4/IPv6 address...
*/
http_addrlist_t *addrlist; /* List of addresses */
if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
{
/*
* Good IPv4/IPv6 address...
*/
httpAddrFreeList(addrlist);
return (1);
}
}
/*
* Check for (alias) name matches...
*/
for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check for interface hostname matches...
*/
for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
netif;
netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
{
if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + netif->hostlen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
return (0);
}
Commit Message: Don't treat "localhost.localdomain" as an allowed replacement for localhost, since it isn't.
CWE ID: CWE-290 | valid_host(cupsd_client_t *con) /* I - Client connection */
{
cupsd_alias_t *a; /* Current alias */
cupsd_netif_t *netif; /* Current network interface */
const char *end; /* End character */
char *ptr; /* Pointer into host value */
/*
* Copy the Host: header for later use...
*/
strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
sizeof(con->clientname));
if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
{
*ptr++ = '\0';
con->clientport = atoi(ptr);
}
else
con->clientport = con->serverport;
/*
* Then validate...
*/
if (httpAddrLocalhost(httpGetAddress(con->http)))
{
/*
* Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
* addresses when accessing CUPS via the loopback interface...
*/
return (!_cups_strcasecmp(con->clientname, "localhost") ||
!_cups_strcasecmp(con->clientname, "localhost.") ||
!strcmp(con->clientname, "127.0.0.1") ||
!strcmp(con->clientname, "[::1]"));
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
/*
* Check if the hostname is something.local (Bonjour); if so, allow it.
*/
if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
!end[1])
{
/*
* "." on end, work back to second-to-last "."...
*/
for (end --; end > con->clientname && *end != '.'; end --);
}
if (end && (!_cups_strcasecmp(end, ".local") ||
!_cups_strcasecmp(end, ".local.")))
return (1);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check if the hostname is an IP address...
*/
if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
{
/*
* Possible IPv4/IPv6 address...
*/
http_addrlist_t *addrlist; /* List of addresses */
if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
{
/*
* Good IPv4/IPv6 address...
*/
httpAddrFreeList(addrlist);
return (1);
}
}
/*
* Check for (alias) name matches...
*/
for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check for interface hostname matches...
*/
for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
netif;
netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
{
if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + netif->hostlen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
return (0);
}
| 169,417 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
Commit Message: KVM: x86: Reload pit counters for all channels when restoring state
Currently if userspace restores the pit counters with a count of 0
on channels 1 or 2 and the guest attempts to read the count on those
channels, then KVM will perform a mod of 0 and crash. This will ensure
that 0 values are converted to 65536 as per the spec.
This is CVE-2015-7513.
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: | static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int i;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
for (i = 0; i < 3; i++)
kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
| 167,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb->sk = sk;
llc_sap_state_process(sap, skb);
}
Commit Message: net/llc: avoid BUG_ON() in skb_orphan()
It seems nobody used LLC since linux-3.12.
Fortunately fuzzers like syzkaller still know how to run this code,
otherwise it would be no fun.
Setting skb->sk without skb->destructor leads to all kinds of
bugs, we now prefer to be very strict about it.
Ideally here we would use skb_set_owner() but this helper does not exist yet,
only CAN seems to have a private helper for that.
Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb_orphan(skb);
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_efree;
llc_sap_state_process(sap, skb);
}
| 168,349 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mcf_fec_do_tx(mcf_fec_state *s)
{
uint32_t addr;
uint32_t addr;
mcf_fec_bd bd;
int frame_size;
int len;
uint8_t frame[FEC_MAX_FRAME_SIZE];
uint8_t *ptr;
ptr = frame;
ptr = frame;
frame_size = 0;
addr = s->tx_descriptor;
while (1) {
mcf_fec_read_bd(&bd, addr);
DPRINTF("tx_bd %x flags %04x len %d data %08x\n",
addr, bd.flags, bd.length, bd.data);
/* Run out of descriptors to transmit. */
break;
}
len = bd.length;
if (frame_size + len > FEC_MAX_FRAME_SIZE) {
len = FEC_MAX_FRAME_SIZE - frame_size;
s->eir |= FEC_INT_BABT;
}
cpu_physical_memory_read(bd.data, ptr, len);
ptr += len;
frame_size += len;
if (bd.flags & FEC_BD_L) {
/* Last buffer in frame. */
DPRINTF("Sending packet\n");
qemu_send_packet(qemu_get_queue(s->nic), frame, len);
ptr = frame;
frame_size = 0;
s->eir |= FEC_INT_TXF;
}
s->eir |= FEC_INT_TXB;
bd.flags &= ~FEC_BD_R;
/* Write back the modified descriptor. */
mcf_fec_write_bd(&bd, addr);
/* Advance to the next descriptor. */
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->etdsr;
} else {
addr += 8;
}
}
Commit Message:
CWE ID: CWE-399 | static void mcf_fec_do_tx(mcf_fec_state *s)
{
uint32_t addr;
uint32_t addr;
mcf_fec_bd bd;
int frame_size;
int len, descnt = 0;
uint8_t frame[FEC_MAX_FRAME_SIZE];
uint8_t *ptr;
ptr = frame;
ptr = frame;
frame_size = 0;
addr = s->tx_descriptor;
while (descnt++ < FEC_MAX_DESC) {
mcf_fec_read_bd(&bd, addr);
DPRINTF("tx_bd %x flags %04x len %d data %08x\n",
addr, bd.flags, bd.length, bd.data);
/* Run out of descriptors to transmit. */
break;
}
len = bd.length;
if (frame_size + len > FEC_MAX_FRAME_SIZE) {
len = FEC_MAX_FRAME_SIZE - frame_size;
s->eir |= FEC_INT_BABT;
}
cpu_physical_memory_read(bd.data, ptr, len);
ptr += len;
frame_size += len;
if (bd.flags & FEC_BD_L) {
/* Last buffer in frame. */
DPRINTF("Sending packet\n");
qemu_send_packet(qemu_get_queue(s->nic), frame, len);
ptr = frame;
frame_size = 0;
s->eir |= FEC_INT_TXF;
}
s->eir |= FEC_INT_TXB;
bd.flags &= ~FEC_BD_R;
/* Write back the modified descriptor. */
mcf_fec_write_bd(&bd, addr);
/* Advance to the next descriptor. */
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->etdsr;
} else {
addr += 8;
}
}
| 164,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 btif_av_event_free_data(btif_sm_event_t event, void* p_data) {
switch (event) {
case BTA_AV_META_MSG_EVT: {
tBTA_AV* av = (tBTA_AV*)p_data;
osi_free_and_reset((void**)&av->meta_msg.p_data);
if (av->meta_msg.p_msg) {
if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) {
osi_free(av->meta_msg.p_msg->vendor.p_vendor_data);
}
osi_free_and_reset((void**)&av->meta_msg.p_msg);
}
} break;
default:
break;
}
}
Commit Message: DO NOT MERGE AVRC: Copy browse.p_browse_data in btif_av_event_deep_copy
p_msg_src->browse.p_browse_data is not copied, but used after the
original pointer is freed
Bug: 109699112
Test: manual
Change-Id: I1d014eb9a8911da6913173a9b11218bf1c89e16e
(cherry picked from commit 1d9a58768e6573899c7e80c2b3f52e22f2d8f58b)
CWE ID: CWE-416 | static void btif_av_event_free_data(btif_sm_event_t event, void* p_data) {
switch (event) {
case BTA_AV_META_MSG_EVT: {
tBTA_AV* av = (tBTA_AV*)p_data;
osi_free_and_reset((void**)&av->meta_msg.p_data);
if (av->meta_msg.p_msg) {
if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) {
osi_free(av->meta_msg.p_msg->vendor.p_vendor_data);
}
if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_BROWSE) {
osi_free(av->meta_msg.p_msg->browse.p_browse_data);
}
osi_free_and_reset((void**)&av->meta_msg.p_msg);
}
} break;
default:
break;
}
}
| 174,101 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gplotAddPlot(GPLOT *gplot,
NUMA *nax,
NUMA *nay,
l_int32 plotstyle,
const char *plottitle)
{
char buf[L_BUF_SIZE];
char emptystring[] = "";
char *datastr, *title;
l_int32 n, i;
l_float32 valx, valy, startx, delx;
SARRAY *sa;
PROCNAME("gplotAddPlot");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
if (!nay)
return ERROR_INT("nay not defined", procName, 1);
if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES)
return ERROR_INT("invalid plotstyle", procName, 1);
if ((n = numaGetCount(nay)) == 0)
return ERROR_INT("no points to plot", procName, 1);
if (nax && (n != numaGetCount(nax)))
return ERROR_INT("nax and nay sizes differ", procName, 1);
if (n == 1 && plotstyle == GPLOT_LINES) {
L_INFO("only 1 pt; changing style to points\n", procName);
plotstyle = GPLOT_POINTS;
}
/* Save plotstyle and plottitle */
numaGetParameters(nay, &startx, &delx);
numaAddNumber(gplot->plotstyles, plotstyle);
if (plottitle) {
title = stringNew(plottitle);
sarrayAddString(gplot->plottitles, title, L_INSERT);
} else {
sarrayAddString(gplot->plottitles, emptystring, L_COPY);
}
/* Generate and save data filename */
gplot->nplots++;
snprintf(buf, L_BUF_SIZE, "%s.data.%d", gplot->rootname, gplot->nplots);
sarrayAddString(gplot->datanames, buf, L_COPY);
/* Generate data and save as a string */
sa = sarrayCreate(n);
for (i = 0; i < n; i++) {
if (nax)
numaGetFValue(nax, i, &valx);
else
valx = startx + i * delx;
numaGetFValue(nay, i, &valy);
snprintf(buf, L_BUF_SIZE, "%f %f\n", valx, valy);
sarrayAddString(sa, buf, L_COPY);
}
datastr = sarrayToString(sa, 0);
sarrayAddString(gplot->plotdata, datastr, L_INSERT);
sarrayDestroy(&sa);
return 0;
}
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 | gplotAddPlot(GPLOT *gplot,
NUMA *nax,
NUMA *nay,
l_int32 plotstyle,
const char *plottitle)
{
char buf[L_BUFSIZE];
char emptystring[] = "";
char *datastr, *title;
l_int32 n, i;
l_float32 valx, valy, startx, delx;
SARRAY *sa;
PROCNAME("gplotAddPlot");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
if (!nay)
return ERROR_INT("nay not defined", procName, 1);
if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES)
return ERROR_INT("invalid plotstyle", procName, 1);
if ((n = numaGetCount(nay)) == 0)
return ERROR_INT("no points to plot", procName, 1);
if (nax && (n != numaGetCount(nax)))
return ERROR_INT("nax and nay sizes differ", procName, 1);
if (n == 1 && plotstyle == GPLOT_LINES) {
L_INFO("only 1 pt; changing style to points\n", procName);
plotstyle = GPLOT_POINTS;
}
/* Save plotstyle and plottitle */
numaGetParameters(nay, &startx, &delx);
numaAddNumber(gplot->plotstyles, plotstyle);
if (plottitle) {
title = stringNew(plottitle);
sarrayAddString(gplot->plottitles, title, L_INSERT);
} else {
sarrayAddString(gplot->plottitles, emptystring, L_COPY);
}
/* Generate and save data filename */
gplot->nplots++;
snprintf(buf, L_BUFSIZE, "%s.data.%d", gplot->rootname, gplot->nplots);
sarrayAddString(gplot->datanames, buf, L_COPY);
/* Generate data and save as a string */
sa = sarrayCreate(n);
for (i = 0; i < n; i++) {
if (nax)
numaGetFValue(nax, i, &valx);
else
valx = startx + i * delx;
numaGetFValue(nay, i, &valy);
snprintf(buf, L_BUFSIZE, "%f %f\n", valx, valy);
sarrayAddString(sa, buf, L_COPY);
}
datastr = sarrayToString(sa, 0);
sarrayAddString(gplot->plotdata, datastr, L_INSERT);
sarrayDestroy(&sa);
return 0;
}
| 169,323 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaStreamDispatcherHost::StopStreamDevice(const std::string& device_id,
int32_t session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->StopStreamDevice(render_process_id_, render_frame_id_,
device_id, session_id);
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamDispatcherHost::StopStreamDevice(const std::string& device_id,
int32_t session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->StopStreamDevice(render_process_id_, render_frame_id_,
requester_id_, device_id, session_id);
}
| 173,097 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
{
ASSERT(refCount() || parentOrHostNode());
RefPtr<Node> protect(this);
ec = 0;
if (oldChild == newChild) // nothing to do
return true;
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
if (!oldChild || oldChild->parentNode() != this) {
ec = NOT_FOUND_ERR;
return false;
}
#if ENABLE(MUTATION_OBSERVERS)
ChildListMutationScope mutation(this);
#endif
RefPtr<Node> next = oldChild->nextSibling();
RefPtr<Node> removedChild = oldChild;
removeChild(oldChild, ec);
if (ec)
return false;
if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do
return true;
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
NodeVector targets;
collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec);
if (ec)
return false;
InspectorInstrumentation::willInsertDOMNode(document(), this);
for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
Node* child = it->get();
if (next && next->parentNode() != this)
break;
if (child->parentNode())
break;
treeScope()->adoptIfNeeded(child);
forbidEventDispatch();
if (next)
insertBeforeCommon(next.get(), child);
else
appendChildToContainer(child, this);
allowEventDispatch();
updateTreeAfterInsertion(this, child, shouldLazyAttach);
}
dispatchSubtreeModifiedEvent();
return true;
}
Commit Message: https://bugs.webkit.org/show_bug.cgi?id=93587
Node::replaceChild() can create bad DOM topology with MutationEvent, Part 2
Reviewed by Kent Tamura.
Source/WebCore:
This is a followup of r124156. replaceChild() has yet another hidden
MutationEvent trigger. This change added a guard for it.
Test: fast/events/mutation-during-replace-child-2.html
* dom/ContainerNode.cpp:
(WebCore::ContainerNode::replaceChild):
LayoutTests:
* fast/events/mutation-during-replace-child-2-expected.txt: Added.
* fast/events/mutation-during-replace-child-2.html: Added.
git-svn-id: svn://svn.chromium.org/blink/trunk@125237 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
{
ASSERT(refCount() || parentOrHostNode());
RefPtr<Node> protect(this);
ec = 0;
if (oldChild == newChild) // nothing to do
return true;
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
if (!oldChild || oldChild->parentNode() != this) {
ec = NOT_FOUND_ERR;
return false;
}
#if ENABLE(MUTATION_OBSERVERS)
ChildListMutationScope mutation(this);
#endif
RefPtr<Node> next = oldChild->nextSibling();
RefPtr<Node> removedChild = oldChild;
removeChild(oldChild, ec);
if (ec)
return false;
if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do
return true;
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
NodeVector targets;
collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec);
if (ec)
return false;
// Does this yet another check because collectChildrenAndRemoveFromOldParent() fires a MutationEvent.
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
InspectorInstrumentation::willInsertDOMNode(document(), this);
for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
Node* child = it->get();
if (next && next->parentNode() != this)
break;
if (child->parentNode())
break;
treeScope()->adoptIfNeeded(child);
forbidEventDispatch();
if (next)
insertBeforeCommon(next.get(), child);
else
appendChildToContainer(child, this);
allowEventDispatch();
updateTreeAfterInsertion(this, child, shouldLazyAttach);
}
dispatchSubtreeModifiedEvent();
return true;
}
| 170,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
client->auth_user = client->db->auth_user;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
Commit Message: Remove too early set of auth_user
When query returns 0 rows (user not found),
this user stays as login user...
Should fix #69.
CWE ID: CWE-287 | static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
| 168,871 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Map U+10DE to 3 when checking for confusables
Georgian letter U+10DE (პ) looks similar to the number 3. This cl adds
U+10DE to the mapping to 3 when determining whether to fall back to
punycode when displaying URLs.
Bug: 895207
Change-Id: I49713d7772428f8d364f371850a42913669acc4b
Reviewed-on: https://chromium-review.googlesource.com/c/1284396
Commit-Queue: Livvie Lin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#600193}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0437 (з), U+0499 (ҙ), U+04E1 (ӡ), U+1012 (ဒ), U+10D5 (ვ),
// U+10DE (პ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,639 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
handle.parent_client_id = context_->GetChannelID();
handle.parent_context_id = context_->GetContextID();
handle.parent_texture_id[0] = context_->createTexture();
handle.parent_texture_id[1] = context_->createTexture();
handle.sync_point = context_->insertSyncPoint();
context_->flush();
return handle;
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
context_->flush();
return handle;
}
| 171,363 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned int oom_badness(struct task_struct *p, struct mem_cgroup *mem,
const nodemask_t *nodemask, unsigned long totalpages)
{
int points;
if (oom_unkillable_task(p, mem, nodemask))
return 0;
p = find_lock_task_mm(p);
if (!p)
return 0;
/*
* Shortcut check for a thread sharing p->mm that is OOM_SCORE_ADJ_MIN
* so the entire heuristic doesn't need to be executed for something
* that cannot be killed.
*/
if (atomic_read(&p->mm->oom_disable_count)) {
task_unlock(p);
return 0;
}
/*
* The memory controller may have a limit of 0 bytes, so avoid a divide
* by zero, if necessary.
*/
if (!totalpages)
totalpages = 1;
/*
* The baseline for the badness score is the proportion of RAM that each
* task's rss, pagetable and swap space use.
*/
points = get_mm_rss(p->mm) + p->mm->nr_ptes;
points += get_mm_counter(p->mm, MM_SWAPENTS);
points *= 1000;
points /= totalpages;
task_unlock(p);
/*
* Root processes get 3% bonus, just like the __vm_enough_memory()
* implementation used by LSMs.
*/
if (has_capability_noaudit(p, CAP_SYS_ADMIN))
points -= 30;
/*
* /proc/pid/oom_score_adj ranges from -1000 to +1000 such that it may
* either completely disable oom killing or always prefer a certain
* task.
*/
points += p->signal->oom_score_adj;
/*
* Never return 0 for an eligible task that may be killed since it's
* possible that no single user task uses more than 0.1% of memory and
* no single admin tasks uses more than 3.0%.
*/
if (points <= 0)
return 1;
return (points < 1000) ? points : 1000;
}
Commit Message: oom: fix integer overflow of points in oom_badness
commit ff05b6f7ae762b6eb464183eec994b28ea09f6dd upstream.
An integer overflow will happen on 64bit archs if task's sum of rss,
swapents and nr_ptes exceeds (2^31)/1000 value. This was introduced by
commit
f755a04 oom: use pte pages in OOM score
where the oom score computation was divided into several steps and it's no
longer computed as one expression in unsigned long(rss, swapents, nr_pte
are unsigned long), where the result value assigned to points(int) is in
range(1..1000). So there could be an int overflow while computing
176 points *= 1000;
and points may have negative value. Meaning the oom score for a mem hog task
will be one.
196 if (points <= 0)
197 return 1;
For example:
[ 3366] 0 3366 35390480 24303939 5 0 0 oom01
Out of memory: Kill process 3366 (oom01) score 1 or sacrifice child
Here the oom1 process consumes more than 24303939(rss)*4096~=92GB physical
memory, but it's oom score is one.
In this situation the mem hog task is skipped and oom killer kills another and
most probably innocent task with oom score greater than one.
The points variable should be of type long instead of int to prevent the
int overflow.
Signed-off-by: Frantisek Hrbata <[email protected]>
Acked-by: KOSAKI Motohiro <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Acked-by: David Rientjes <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-189 | unsigned int oom_badness(struct task_struct *p, struct mem_cgroup *mem,
const nodemask_t *nodemask, unsigned long totalpages)
{
long points;
if (oom_unkillable_task(p, mem, nodemask))
return 0;
p = find_lock_task_mm(p);
if (!p)
return 0;
/*
* Shortcut check for a thread sharing p->mm that is OOM_SCORE_ADJ_MIN
* so the entire heuristic doesn't need to be executed for something
* that cannot be killed.
*/
if (atomic_read(&p->mm->oom_disable_count)) {
task_unlock(p);
return 0;
}
/*
* The memory controller may have a limit of 0 bytes, so avoid a divide
* by zero, if necessary.
*/
if (!totalpages)
totalpages = 1;
/*
* The baseline for the badness score is the proportion of RAM that each
* task's rss, pagetable and swap space use.
*/
points = get_mm_rss(p->mm) + p->mm->nr_ptes;
points += get_mm_counter(p->mm, MM_SWAPENTS);
points *= 1000;
points /= totalpages;
task_unlock(p);
/*
* Root processes get 3% bonus, just like the __vm_enough_memory()
* implementation used by LSMs.
*/
if (has_capability_noaudit(p, CAP_SYS_ADMIN))
points -= 30;
/*
* /proc/pid/oom_score_adj ranges from -1000 to +1000 such that it may
* either completely disable oom killing or always prefer a certain
* task.
*/
points += p->signal->oom_score_adj;
/*
* Never return 0 for an eligible task that may be killed since it's
* possible that no single user task uses more than 0.1% of memory and
* no single admin tasks uses more than 3.0%.
*/
if (points <= 0)
return 1;
return (points < 1000) ? points : 1000;
}
| 165,740 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateBool( int b )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = b ? cJSON_True : cJSON_False;
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateBool( int b )
| 167,270 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.
{
if (ms)
{
int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
if (size + 2 <= nestsize) return GPMF_OK;
}
return GPMF_ERROR_BAD_STRUCTURE;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.
{
if (ms)
{
uint32_t nestsize = (uint32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
if (size + 2 <= nestsize) return GPMF_OK;
}
return GPMF_ERROR_BAD_STRUCTURE;
}
| 169,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: xmalloc (size_t size)
{
void *ptr = malloc (size);
if (!ptr
&& (size != 0)) /* some libc don't like size == 0 */
{
perror ("xmalloc: Memory allocation failure");
abort();
}
return ptr;
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190 | xmalloc (size_t size)
xmalloc (size_t num, size_t size)
{
size_t res;
if (check_mul_overflow(num, size, &res))
abort();
void *ptr = malloc (res);
if (!ptr
&& (size != 0)) /* some libc don't like size == 0 */
{
perror ("xmalloc: Memory allocation failure");
abort();
}
return ptr;
}
| 168,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: void BluetoothOptionsHandler::RequestPasskey(
chromeos::BluetoothDevice* device) {
}
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::RequestPasskey(
chromeos::BluetoothDevice* device) {
DictionaryValue params;
params.SetString("pairing", "bluetoothEnterPasskey");
SendDeviceNotification(device, ¶ms);
}
| 170,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IsAllowed(const scoped_refptr<const Extension>& extension,
const GURL& url,
PermittedFeature feature,
int tab_id) {
const PermissionsData* permissions_data = extension->permissions_data();
bool script = permissions_data->CanAccessPage(extension.get(), url, tab_id,
nullptr) &&
permissions_data->CanRunContentScriptOnPage(
extension.get(), url, tab_id, nullptr);
bool capture = HasTabsPermission(extension, tab_id) &&
permissions_data->CanCaptureVisiblePage(tab_id, NULL);
switch (feature) {
case PERMITTED_SCRIPT_ONLY:
return script && !capture;
case PERMITTED_CAPTURE_ONLY:
return capture && !script;
case PERMITTED_BOTH:
return script && capture;
case PERMITTED_NONE:
return !script && !capture;
}
NOTREACHED();
return false;
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20 | bool IsAllowed(const scoped_refptr<const Extension>& extension,
const GURL& url,
PermittedFeature feature,
int tab_id) {
const PermissionsData* permissions_data = extension->permissions_data();
bool script = permissions_data->CanAccessPage(extension.get(), url, tab_id,
nullptr) &&
permissions_data->CanRunContentScriptOnPage(
extension.get(), url, tab_id, nullptr);
bool capture = permissions_data->CanCaptureVisiblePage(url, extension.get(),
tab_id, NULL);
switch (feature) {
case PERMITTED_SCRIPT_ONLY:
return script && !capture;
case PERMITTED_CAPTURE_ONLY:
return capture && !script;
case PERMITTED_BOTH:
return script && capture;
case PERMITTED_NONE:
return !script && !capture;
}
NOTREACHED();
return false;
}
| 173,228 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PeopleHandler::HandlePauseSync(const base::ListValue* args) {
DCHECK(AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_));
SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
DCHECK(signin_manager->IsAuthenticated());
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials(
signin_manager->GetAuthenticatedAccountId(),
OAuth2TokenServiceDelegate::kInvalidRefreshToken);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void PeopleHandler::HandlePauseSync(const base::ListValue* args) {
DCHECK(AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_));
SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
DCHECK(signin_manager->IsAuthenticated());
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials(
signin_manager->GetAuthenticatedAccountId(),
OAuth2TokenServiceDelegate::kInvalidRefreshToken,
signin_metrics::SourceForRefreshTokenOperation::kSettings_PauseSync);
}
| 172,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 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 | horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
return 1;
}
| 166,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DownloadCoreServiceImpl::GetDownloadManagerDelegate() {
DownloadManager* manager = BrowserContext::GetDownloadManager(profile_);
if (download_manager_created_) {
DCHECK(static_cast<DownloadManagerDelegate*>(manager_delegate_.get()) ==
manager->GetDelegate());
return manager_delegate_.get();
}
download_manager_created_ = true;
if (!manager_delegate_.get())
manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_));
manager_delegate_->SetDownloadManager(manager);
#if BUILDFLAG(ENABLE_EXTENSIONS)
extension_event_router_.reset(
new extensions::ExtensionDownloadsEventRouter(profile_, manager));
#endif
if (!profile_->IsOffTheRecord()) {
history::HistoryService* history = HistoryServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
history->GetNextDownloadId(
manager_delegate_->GetDownloadIdReceiverCallback());
download_history_.reset(new DownloadHistory(
manager, std::unique_ptr<DownloadHistory::HistoryAdapter>(
new DownloadHistory::HistoryAdapter(history))));
}
download_ui_.reset(new DownloadUIController(
manager, std::unique_ptr<DownloadUIController::Delegate>()));
g_browser_process->download_status_updater()->AddManager(manager);
return manager_delegate_.get();
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125 | DownloadCoreServiceImpl::GetDownloadManagerDelegate() {
DownloadManager* manager = BrowserContext::GetDownloadManager(profile_);
if (download_manager_created_)
return manager_delegate_.get();
download_manager_created_ = true;
if (!manager_delegate_.get())
manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_));
manager_delegate_->SetDownloadManager(manager);
#if BUILDFLAG(ENABLE_EXTENSIONS)
extension_event_router_.reset(
new extensions::ExtensionDownloadsEventRouter(profile_, manager));
#endif
if (!profile_->IsOffTheRecord()) {
history::HistoryService* history = HistoryServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
history->GetNextDownloadId(
manager_delegate_->GetDownloadIdReceiverCallback());
download_history_.reset(new DownloadHistory(
manager, std::unique_ptr<DownloadHistory::HistoryAdapter>(
new DownloadHistory::HistoryAdapter(history))));
}
download_ui_.reset(new DownloadUIController(
manager, std::unique_ptr<DownloadUIController::Delegate>()));
DCHECK(g_browser_process->download_status_updater());
g_browser_process->download_status_updater()->AddManager(manager);
return manager_delegate_.get();
}
| 173,168 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state)
{
vpx_codec_err_t res = VPX_CODEC_OK;
if(data + data_sz <= data)
{
res = VPX_CODEC_INVALID_PARAM;
}
else
{
/* Parse uncompresssed part of key frame header.
* 3 bytes:- including version, frame type and an offset
* 3 bytes:- sync code (0x9d, 0x01, 0x2a)
* 4 bytes:- including image width and height in the lowest 14 bits
* of each 2-byte value.
*/
uint8_t clear_buffer[10];
const uint8_t *clear = data;
if (decrypt_cb)
{
int n = MIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, n);
clear = clear_buffer;
}
si->is_kf = 0;
if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */
{
si->is_kf = 1;
/* vet via sync code */
if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a)
return VPX_CODEC_UNSUP_BITSTREAM;
si->w = (clear[6] | (clear[7] << 8)) & 0x3fff;
si->h = (clear[8] | (clear[9] << 8)) & 0x3fff;
/*printf("w=%d, h=%d\n", si->w, si->h);*/
if (!(si->h | si->w))
res = VPX_CODEC_UNSUP_BITSTREAM;
}
else
{
res = VPX_CODEC_UNSUP_BITSTREAM;
}
}
return res;
}
Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream
Description from upstream:
vp8: fix decoder crash with invalid leading keyframes
decoding the same invalid keyframe twice would result in a crash as the
second time through the decoder would be assumed to have been
initialized as there was no resolution change. in this case the
resolution was itself invalid (0x6), but vp8_peek_si() was only failing
in the case of 0x0.
invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by
duplicating the first keyframe and additionally adds a valid one to
ensure decoding can resume without error.
Bug: 30593765
Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507
(cherry picked from commit fc0466b695dce03e10390101844caa374848d903)
(cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136)
CWE ID: CWE-20 | static vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state)
{
vpx_codec_err_t res = VPX_CODEC_OK;
if(data + data_sz <= data)
{
res = VPX_CODEC_INVALID_PARAM;
}
else
{
/* Parse uncompresssed part of key frame header.
* 3 bytes:- including version, frame type and an offset
* 3 bytes:- sync code (0x9d, 0x01, 0x2a)
* 4 bytes:- including image width and height in the lowest 14 bits
* of each 2-byte value.
*/
uint8_t clear_buffer[10];
const uint8_t *clear = data;
if (decrypt_cb)
{
int n = MIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, n);
clear = clear_buffer;
}
si->is_kf = 0;
if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */
{
si->is_kf = 1;
/* vet via sync code */
if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a)
return VPX_CODEC_UNSUP_BITSTREAM;
si->w = (clear[6] | (clear[7] << 8)) & 0x3fff;
si->h = (clear[8] | (clear[9] << 8)) & 0x3fff;
/*printf("w=%d, h=%d\n", si->w, si->h);*/
if (!(si->h && si->w))
res = VPX_CODEC_CORRUPT_FRAME;
}
else
{
res = VPX_CODEC_UNSUP_BITSTREAM;
}
}
return res;
}
| 173,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.amrnb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAMR)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (amrParams->nChannels != 1
|| amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff
|| amrParams->eAMRFrameFormat
!= OMX_AUDIO_AMRFrameFormatFSF
|| amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0
|| amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) {
return OMX_ErrorUndefined;
}
mBitRate = amrParams->nBitRate;
mMode = amrParams->eAMRBandMode - 1;
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels != 1
|| pcmParams->nSamplingRate != (OMX_U32)kSampleRate) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.amrnb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAMR)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (!isValidOMXParam(amrParams)) {
return OMX_ErrorBadParameter;
}
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (amrParams->nChannels != 1
|| amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff
|| amrParams->eAMRFrameFormat
!= OMX_AUDIO_AMRFrameFormatFSF
|| amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0
|| amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) {
return OMX_ErrorUndefined;
}
mBitRate = amrParams->nBitRate;
mMode = amrParams->eAMRBandMode - 1;
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels != 1
|| pcmParams->nSamplingRate != (OMX_U32)kSampleRate) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,195 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserContextDestroyer::DestroyContext(BrowserContext* context) {
CHECK(context->IsOffTheRecord() || !context->HasOffTheRecordContext());
content::BrowserContext::NotifyWillBeDestroyed(context);
std::set<content::RenderProcessHost*> hosts;
for (content::RenderProcessHost::iterator it =
content::RenderProcessHost::AllHostsIterator();
!it.IsAtEnd(); it.Advance()) {
content::RenderProcessHost* host = it.GetCurrentValue();
if (host->GetBrowserContext() != context) {
continue;
}
hosts.insert(host);
//// static
}
if (hosts.empty()) {
delete context;
} else {
new BrowserContextDestroyer(context, hosts);
}
}
Commit Message:
CWE ID: CWE-20 | void BrowserContextDestroyer::DestroyContext(BrowserContext* context) {
void BrowserContextDestroyer::Shutdown() {
auto destroy_all_unused_contexts = []() {
auto it = g_contexts_pending_deletion.Get().begin();
while (it != g_contexts_pending_deletion.Get().end()) {
BrowserContextDestroyer* destroyer = *it;
++it;
if (!destroyer->finish_destroy_scheduled_) {
continue;
}
destroyer->FinishDestroyContext();
// |destroyer| is invalid now
}
};
// We make 2 passes over the list because the first pass can destroy an
// incognito BrowserContext that subsequently schedules its owner context for
// deletion
destroy_all_unused_contexts();
destroy_all_unused_contexts();
}
//// static
void BrowserContextDestroyer::RenderProcessHostAssignedToSiteInstance(
content::RenderProcessHost* host) {
BrowserContextDestroyer* destroyer = GetForContext(host->GetBrowserContext());
if (!destroyer) {
return;
}
CHECK(!destroyer->finish_destroy_scheduled_);
if (destroyer->pending_host_ids_.find(host->GetID()) !=
destroyer->pending_host_ids_.end()) {
return;
}
destroyer->ObserveHost(host);
}
| 165,419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.