instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
{
uint8_t byte;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
/* nreslevels = number of resolution levels
= number of decomposition level +1 */
c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
return AVERROR_INVALIDDATA;
}
/* compute number of resolution levels to decode */
if (c->nreslevels < s->reduction_factor)
c->nreslevels2decode = 1;
else
c->nreslevels2decode = c->nreslevels - s->reduction_factor;
c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
c->log2_cblk_width + c->log2_cblk_height > 12) {
av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
return AVERROR_INVALIDDATA;
}
c->cblk_style = bytestream2_get_byteu(&s->g);
if (c->cblk_style != 0) { // cblk style
av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
}
c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
/* set integer 9/7 DWT in case of BITEXACT flag */
if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
c->transform = FF_DWT97_INT;
if (c->csty & JPEG2000_CSTY_PREC) {
int i;
for (i = 0; i < c->nreslevels; i++) {
byte = bytestream2_get_byte(&s->g);
c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
}
} else {
memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
}
return 0;
}
Commit Message: jpeg2000: check log2_cblk dimensions
Fixes out of array access
Fixes Ticket2895
Found-by: Piotr Bandurski <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
{
uint8_t byte;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
/* nreslevels = number of resolution levels
= number of decomposition level +1 */
c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
return AVERROR_INVALIDDATA;
}
/* compute number of resolution levels to decode */
if (c->nreslevels < s->reduction_factor)
c->nreslevels2decode = 1;
else
c->nreslevels2decode = c->nreslevels - s->reduction_factor;
c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
c->log2_cblk_width + c->log2_cblk_height > 12) {
av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
return AVERROR_INVALIDDATA;
}
if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) {
avpriv_request_sample(s->avctx, "cblk size > 64");
return AVERROR_PATCHWELCOME;
}
c->cblk_style = bytestream2_get_byteu(&s->g);
if (c->cblk_style != 0) { // cblk style
av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
}
c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
/* set integer 9/7 DWT in case of BITEXACT flag */
if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
c->transform = FF_DWT97_INT;
if (c->csty & JPEG2000_CSTY_PREC) {
int i;
for (i = 0; i < c->nreslevels; i++) {
byte = bytestream2_get_byte(&s->g);
c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
}
} else {
memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
}
return 0;
}
| 165,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, rewind)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::eof()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, rewind)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::eof()
| 167,051 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
VpxVideoReader *reader = NULL;
const VpxInterface *decoder = NULL;
const VpxVideoInfo *info = NULL;
exec_name = argv[0];
if (argc != 3)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing.", argv[2]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->interface()));
if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0))
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
die_codec(&codec, "Failed to decode frame.");
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) {
vpx_img_write(img, outfile);
++frame_cnt;
}
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
VpxVideoReader *reader = NULL;
const VpxInterface *decoder = NULL;
const VpxVideoInfo *info = NULL;
exec_name = argv[0];
if (argc != 3)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing.", argv[2]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface()));
if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0))
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
die_codec(&codec, "Failed to decode frame.");
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) {
vpx_img_write(img, outfile);
++frame_cnt;
}
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
| 174,487 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int attach_recursive_mnt(struct mount *source_mnt,
struct mount *dest_mnt,
struct mountpoint *dest_mp,
struct path *parent_path)
{
HLIST_HEAD(tree_list);
struct mount *child, *p;
struct hlist_node *n;
int err;
if (IS_MNT_SHARED(dest_mnt)) {
err = invent_group_ids(source_mnt, true);
if (err)
goto out;
err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list);
lock_mount_hash();
if (err)
goto out_cleanup_ids;
for (p = source_mnt; p; p = next_mnt(p, source_mnt))
set_mnt_shared(p);
} else {
lock_mount_hash();
}
if (parent_path) {
detach_mnt(source_mnt, parent_path);
attach_mnt(source_mnt, dest_mnt, dest_mp);
touch_mnt_namespace(source_mnt->mnt_ns);
} else {
mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt);
commit_tree(source_mnt, NULL);
}
hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
struct mount *q;
hlist_del_init(&child->mnt_hash);
q = __lookup_mnt_last(&child->mnt_parent->mnt,
child->mnt_mountpoint);
commit_tree(child, q);
}
unlock_mount_hash();
return 0;
out_cleanup_ids:
while (!hlist_empty(&tree_list)) {
child = hlist_entry(tree_list.first, struct mount, mnt_hash);
umount_tree(child, UMOUNT_SYNC);
}
unlock_mount_hash();
cleanup_group_ids(source_mnt, NULL);
out:
return err;
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static int attach_recursive_mnt(struct mount *source_mnt,
struct mount *dest_mnt,
struct mountpoint *dest_mp,
struct path *parent_path)
{
HLIST_HEAD(tree_list);
struct mnt_namespace *ns = dest_mnt->mnt_ns;
struct mount *child, *p;
struct hlist_node *n;
int err;
/* Is there space to add these mounts to the mount namespace? */
if (!parent_path) {
err = count_mounts(ns, source_mnt);
if (err)
goto out;
}
if (IS_MNT_SHARED(dest_mnt)) {
err = invent_group_ids(source_mnt, true);
if (err)
goto out;
err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list);
lock_mount_hash();
if (err)
goto out_cleanup_ids;
for (p = source_mnt; p; p = next_mnt(p, source_mnt))
set_mnt_shared(p);
} else {
lock_mount_hash();
}
if (parent_path) {
detach_mnt(source_mnt, parent_path);
attach_mnt(source_mnt, dest_mnt, dest_mp);
touch_mnt_namespace(source_mnt->mnt_ns);
} else {
mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt);
commit_tree(source_mnt, NULL);
}
hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
struct mount *q;
hlist_del_init(&child->mnt_hash);
q = __lookup_mnt_last(&child->mnt_parent->mnt,
child->mnt_mountpoint);
commit_tree(child, q);
}
unlock_mount_hash();
return 0;
out_cleanup_ids:
while (!hlist_empty(&tree_list)) {
child = hlist_entry(tree_list.first, struct mount, mnt_hash);
child->mnt_parent->mnt_ns->pending_mounts = 0;
umount_tree(child, UMOUNT_SYNC);
}
unlock_mount_hash();
cleanup_group_ids(source_mnt, NULL);
out:
ns->pending_mounts = 0;
return err;
}
| 167,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cisco_autorp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int type;
int numrps;
int hold;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " auto-rp "));
type = bp[0];
switch (type) {
case 0x11:
ND_PRINT((ndo, "candidate-advert"));
break;
case 0x12:
ND_PRINT((ndo, "mapping"));
break;
default:
ND_PRINT((ndo, "type-0x%02x", type));
break;
}
ND_TCHECK(bp[1]);
numrps = bp[1];
ND_TCHECK2(bp[2], 2);
ND_PRINT((ndo, " Hold "));
hold = EXTRACT_16BITS(&bp[2]);
if (hold)
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
else
ND_PRINT((ndo, "FOREVER"));
/* Next 4 bytes are reserved. */
bp += 8; len -= 8;
/*XXX skip unless -v? */
/*
* Rest of packet:
* numrps entries of the form:
* 32 bits: RP
* 6 bits: reserved
* 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2".
* 8 bits: # of entries for this RP
* each entry: 7 bits: reserved, 1 bit: negative,
* 8 bits: mask 32 bits: source
* lather, rinse, repeat.
*/
while (numrps--) {
int nentries;
char s;
ND_TCHECK2(bp[0], 4);
ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp)));
ND_TCHECK(bp[4]);
switch (bp[4] & 0x3) {
case 0: ND_PRINT((ndo, " PIMv?"));
break;
case 1: ND_PRINT((ndo, " PIMv1"));
break;
case 2: ND_PRINT((ndo, " PIMv2"));
break;
case 3: ND_PRINT((ndo, " PIMv1+2"));
break;
}
if (bp[4] & 0xfc)
ND_PRINT((ndo, " [rsvd=0x%02x]", bp[4] & 0xfc));
ND_TCHECK(bp[5]);
nentries = bp[5];
bp += 6; len -= 6;
s = ' ';
for (; nentries; nentries--) {
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "",
ipaddr_string(ndo, &bp[2]), bp[1]));
if (bp[0] & 0x02) {
ND_PRINT((ndo, " bidir"));
}
if (bp[0] & 0xfc) {
ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc));
}
s = ',';
bp += 6; len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|autorp]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | cisco_autorp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int type;
int numrps;
int hold;
if (len < 8)
goto trunc;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " auto-rp "));
type = bp[0];
switch (type) {
case 0x11:
ND_PRINT((ndo, "candidate-advert"));
break;
case 0x12:
ND_PRINT((ndo, "mapping"));
break;
default:
ND_PRINT((ndo, "type-0x%02x", type));
break;
}
ND_TCHECK(bp[1]);
numrps = bp[1];
ND_TCHECK2(bp[2], 2);
ND_PRINT((ndo, " Hold "));
hold = EXTRACT_16BITS(&bp[2]);
if (hold)
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
else
ND_PRINT((ndo, "FOREVER"));
/* Next 4 bytes are reserved. */
bp += 8; len -= 8;
/*XXX skip unless -v? */
/*
* Rest of packet:
* numrps entries of the form:
* 32 bits: RP
* 6 bits: reserved
* 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2".
* 8 bits: # of entries for this RP
* each entry: 7 bits: reserved, 1 bit: negative,
* 8 bits: mask 32 bits: source
* lather, rinse, repeat.
*/
while (numrps--) {
int nentries;
char s;
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], 4);
ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp)));
bp += 4;
len -= 4;
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
switch (bp[0] & 0x3) {
case 0: ND_PRINT((ndo, " PIMv?"));
break;
case 1: ND_PRINT((ndo, " PIMv1"));
break;
case 2: ND_PRINT((ndo, " PIMv2"));
break;
case 3: ND_PRINT((ndo, " PIMv1+2"));
break;
}
if (bp[0] & 0xfc)
ND_PRINT((ndo, " [rsvd=0x%02x]", bp[0] & 0xfc));
bp += 1;
len -= 1;
if (len < 1)
goto trunc;
ND_TCHECK(bp[0]);
nentries = bp[0];
bp += 1;
len -= 1;
s = ' ';
for (; nentries; nentries--) {
if (len < 6)
goto trunc;
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "",
ipaddr_string(ndo, &bp[2]), bp[1]));
if (bp[0] & 0x02) {
ND_PRINT((ndo, " bidir"));
}
if (bp[0] & 0xfc) {
ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc));
}
s = ',';
bp += 6; len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|autorp]"));
return;
}
| 167,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str());
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
CWE ID: CWE-89 | void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%d", atol(idx.c_str()));
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
| 169,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
Commit Message: bpf: fix integer overflows
There were various issues related to the limited size of integers used in
the verifier:
- `off + size` overflow in __check_map_access()
- `off + reg->off` overflow in check_mem_access()
- `off + reg->var_off.value` overflow or 32-bit truncation of
`reg->var_off.value` in check_mem_access()
- 32-bit truncation in check_stack_boundary()
Make sure that any integer math cannot overflow by not allowing
pointer math with large values.
Also reduce the scope of "scalar op scalar" tracking.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-190 | static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
!check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
return -EINVAL;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
return -EINVAL;
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
| 167,643 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void xacct_add_tsk(struct taskstats *stats, struct task_struct *p)
{
/* convert pages-jiffies to Mbyte-usec */
stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB;
stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB;
if (p->mm) {
/* adjust to KB unit */
stats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB;
stats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB;
}
stats->read_char = p->rchar;
stats->write_char = p->wchar;
stats->read_syscalls = p->syscr;
stats->write_syscalls = p->syscw;
}
Commit Message: [PATCH] xacct_add_tsk: fix pure theoretical ->mm use-after-free
Paranoid fix. The task can free its ->mm after the 'if (p->mm)' check.
Signed-off-by: Oleg Nesterov <[email protected]>
Cc: Shailabh Nagar <[email protected]>
Cc: Balbir Singh <[email protected]>
Cc: Jay Lan <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | void xacct_add_tsk(struct taskstats *stats, struct task_struct *p)
{
struct mm_struct *mm;
/* convert pages-jiffies to Mbyte-usec */
stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB;
stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB;
mm = get_task_mm(p);
if (mm) {
/* adjust to KB unit */
stats->hiwater_rss = mm->hiwater_rss * PAGE_SIZE / KB;
stats->hiwater_vm = mm->hiwater_vm * PAGE_SIZE / KB;
mmput(mm);
}
stats->read_char = p->rchar;
stats->write_char = p->wchar;
stats->read_syscalls = p->syscr;
stats->write_syscalls = p->syscw;
}
| 165,582 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
BoxBlurContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
int plane;
int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub);
int w[4] = { inlink->w, cw, cw, inlink->w };
int h[4] = { in->height, ch, ch, in->height };
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
for (plane = 0; in->data[plane] && plane < 4; plane++)
hblur(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
for (plane = 0; in->data[plane] && plane < 4; plane++)
vblur(out->data[plane], out->linesize[plane],
out->data[plane], out->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
BoxBlurContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
int plane;
int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub);
int w[4] = { inlink->w, cw, cw, inlink->w };
int h[4] = { in->height, ch, ch, in->height };
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++)
hblur(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++)
vblur(out->data[plane], out->linesize[plane],
out->data[plane], out->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
| 165,997 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = check_memory_region_flags(mem);
if (r)
goto out;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
if (npages && !old.npages) {
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
if (kvm_arch_create_memslot(&new, npages))
goto out_free;
}
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
if (!npages) {
struct kvm_memory_slot *slot;
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
update_memslots(slots, NULL);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow_memslot(kvm, slot);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map/unmap the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
} else
kvm_iommu_unmap_pages(kvm, &old);
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.dirty_bitmap = NULL;
memset(&new.arch, 0, sizeof(new.arch));
}
update_memslots(slots, &new);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
/*
* If the new memory slot is created, we need to clear all
* mmio sptes.
*/
if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT)
kvm_arch_flush_shadow_all(kvm);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
Commit Message: KVM: perform an invalid memslot step for gpa base change
PPC must flush all translations before the new memory slot
is visible.
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
CWE ID: CWE-399 | int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = check_memory_region_flags(mem);
if (r)
goto out;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
if (npages && !old.npages) {
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
if (kvm_arch_create_memslot(&new, npages))
goto out_free;
}
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
if (!npages || base_gfn != old.base_gfn) {
struct kvm_memory_slot *slot;
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
update_memslots(slots, NULL);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted,
* or moved, memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow_memslot(kvm, slot);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map/unmap the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
} else
kvm_iommu_unmap_pages(kvm, &old);
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.dirty_bitmap = NULL;
memset(&new.arch, 0, sizeof(new.arch));
}
update_memslots(slots, &new);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
/*
* If the new memory slot is created, we need to clear all
* mmio sptes.
*/
if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT)
kvm_arch_flush_shadow_all(kvm);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
| 165,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void * calloc(size_t n, size_t lb)
{
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
Commit Message: Fix calloc() overflow
* malloc.c (calloc): Check multiplication overflow in calloc(),
assuming REDIRECT_MALLOC.
CWE ID: CWE-189 | void * calloc(size_t n, size_t lb)
{
if (lb && n > SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
| 165,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void close_uinput (void)
{
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
if (uinput_fd > 0) {
ioctl(uinput_fd, UI_DEV_DESTROY);
close(uinput_fd);
uinput_fd = -1;
}
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void close_uinput (void)
{
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
if (uinput_fd > 0) {
TEMP_FAILURE_RETRY(ioctl(uinput_fd, UI_DEV_DESTROY));
close(uinput_fd);
uinput_fd = -1;
}
}
| 173,450 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 i;
WORD32 max_dpb_size;
WORD32 mv_bank_size_allocated;
WORD32 pic_mv_bank_size;
sps_t *ps_sps;
UWORD8 *pu1_buf;
mv_buf_t *ps_mv_buf;
/* Initialize MV Bank buffer manager */
ps_sps = ps_codec->s_parse.ps_sps;
/* Compute the number of MV Bank buffers needed */
max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1];
/* Allocate one extra MV Bank to handle current frame
* In case of asynchronous parsing and processing, number of buffers should increase here
* based on when parsing and processing threads are synchronized
*/
max_dpb_size++;
pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base;
ps_mv_buf = (mv_buf_t *)pu1_buf;
pu1_buf += max_dpb_size * sizeof(mv_buf_t);
ps_codec->ps_mv_buf = ps_mv_buf;
mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t);
/* Compute MV bank size per picture */
pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples));
for(i = 0; i < max_dpb_size; i++)
{
WORD32 buf_ret;
WORD32 num_pu;
WORD32 num_ctb;
WORD32 pic_size;
pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples);
num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE);
num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE);
mv_bank_size_allocated -= pic_mv_bank_size;
if(mv_bank_size_allocated < 0)
{
ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK;
return IHEVCD_INSUFFICIENT_MEM_MVBANK;
}
ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf;
pu1_buf += (num_ctb + 1) * sizeof(WORD32);
ps_mv_buf->pu1_pic_pu_map = pu1_buf;
pu1_buf += num_pu;
ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf;
pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16));
ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf;
pu1_buf += num_pu * sizeof(pu_t);
buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i);
if(0 != buf_ret)
{
ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR;
return IHEVCD_BUF_MGR_ERROR;
}
ps_mv_buf++;
}
return ret;
}
Commit Message: Check only allocated mv bufs for releasing from reference
When checking mv bufs for releasing from reference, unallocated
mv bufs were also checked. This issue was fixed by restricting
the loop count to allocated number of mv bufs.
Bug: 34896906
Bug: 34819017
Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb
(cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2)
CWE ID: | IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 i;
WORD32 max_dpb_size;
WORD32 mv_bank_size_allocated;
WORD32 pic_mv_bank_size;
sps_t *ps_sps;
UWORD8 *pu1_buf;
mv_buf_t *ps_mv_buf;
/* Initialize MV Bank buffer manager */
ps_sps = ps_codec->s_parse.ps_sps;
/* Compute the number of MV Bank buffers needed */
max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1];
/* Allocate one extra MV Bank to handle current frame
* In case of asynchronous parsing and processing, number of buffers should increase here
* based on when parsing and processing threads are synchronized
*/
max_dpb_size++;
ps_codec->i4_max_dpb_size = max_dpb_size;
pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base;
ps_mv_buf = (mv_buf_t *)pu1_buf;
pu1_buf += max_dpb_size * sizeof(mv_buf_t);
ps_codec->ps_mv_buf = ps_mv_buf;
mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t);
/* Compute MV bank size per picture */
pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples));
for(i = 0; i < max_dpb_size; i++)
{
WORD32 buf_ret;
WORD32 num_pu;
WORD32 num_ctb;
WORD32 pic_size;
pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples);
num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE);
num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE);
mv_bank_size_allocated -= pic_mv_bank_size;
if(mv_bank_size_allocated < 0)
{
ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK;
return IHEVCD_INSUFFICIENT_MEM_MVBANK;
}
ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf;
pu1_buf += (num_ctb + 1) * sizeof(WORD32);
ps_mv_buf->pu1_pic_pu_map = pu1_buf;
pu1_buf += num_pu;
ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf;
pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16));
ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf;
pu1_buf += num_pu * sizeof(pu_t);
buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i);
if(0 != buf_ret)
{
ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR;
return IHEVCD_BUF_MGR_ERROR;
}
ps_mv_buf++;
}
return ret;
}
| 173,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
Commit Message: Fix a buffer overflow
Fixes #635
Thanks to HongxuChen for reporting it
CWE ID: CWE-125 | matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2;
((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));
k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
| 169,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data)
{
struct l2cap_conf_req *req = (struct l2cap_conf_req *) data;
u16 dcid, flags;
u8 rsp[64];
struct sock *sk;
int len;
dcid = __le16_to_cpu(req->dcid);
flags = __le16_to_cpu(req->flags);
BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags);
sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid);
if (!sk)
return -ENOENT;
if (sk->sk_state == BT_DISCONN)
goto unlock;
/* Reject if config buffer is too small. */
len = cmd_len - sizeof(*req);
if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) {
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_REJECT, flags), rsp);
goto unlock;
}
/* Store config. */
memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len);
l2cap_pi(sk)->conf_len += len;
if (flags & 0x0001) {
/* Incomplete config. Send empty response. */
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_SUCCESS, 0x0001), rsp);
goto unlock;
}
/* Complete config. */
len = l2cap_parse_conf_req(sk, rsp);
if (len < 0)
goto unlock;
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);
/* Reset config buffer. */
l2cap_pi(sk)->conf_len = 0;
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE))
goto unlock;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
goto unlock;
}
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) {
u8 buf[64];
l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
l2cap_build_conf_req(sk, buf), buf);
}
unlock:
bh_unlock_sock(sk);
return 0;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data)
{
struct l2cap_conf_req *req = (struct l2cap_conf_req *) data;
u16 dcid, flags;
u8 rsp[64];
struct sock *sk;
int len;
dcid = __le16_to_cpu(req->dcid);
flags = __le16_to_cpu(req->flags);
BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags);
sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid);
if (!sk)
return -ENOENT;
if (sk->sk_state == BT_DISCONN)
goto unlock;
/* Reject if config buffer is too small. */
len = cmd_len - sizeof(*req);
if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) {
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_REJECT, flags), rsp);
goto unlock;
}
/* Store config. */
memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len);
l2cap_pi(sk)->conf_len += len;
if (flags & 0x0001) {
/* Incomplete config. Send empty response. */
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_SUCCESS, 0x0001), rsp);
goto unlock;
}
/* Complete config. */
len = l2cap_parse_conf_req(sk, rsp);
if (len < 0) {
struct l2cap_disconn_req req;
req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);
req.scid = cpu_to_le16(l2cap_pi(sk)->scid);
l2cap_send_cmd(conn, l2cap_get_ident(conn),
L2CAP_DISCONN_REQ, sizeof(req), &req);
goto unlock;
}
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);
l2cap_pi(sk)->num_conf_rsp++;
/* Reset config buffer. */
l2cap_pi(sk)->conf_len = 0;
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE))
goto unlock;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
goto unlock;
}
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) {
u8 buf[64];
l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
l2cap_build_conf_req(sk, buf), buf);
l2cap_pi(sk)->num_conf_req++;
}
unlock:
bh_unlock_sock(sk);
return 0;
}
| 167,622 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_default_ini(PNG_CONST image_transform *this,
transform_display *that)
{
this->next->ini(this->next, that);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_default_ini(PNG_CONST image_transform *this,
extern void image_transform_default_ini(const image_transform *this,
transform_display *that); /* silence GCC warnings */
void /* private, but almost always needed */
image_transform_default_ini(const image_transform *this,
transform_display *that)
{
this->next->ini(this->next, that);
}
| 173,621 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a)
{
BN_ULONG t1,t2;
BN_ULONG c1,c2,c3;
c1=0;
c2=0;
c3=0;
sqr_add_c(a,0,c1,c2,c3);
r[0]=c1;
c1=0;
sqr_add_c2(a,1,0,c2,c3,c1);
r[1]=c2;
c2=0;
sqr_add_c(a,1,c3,c1,c2);
sqr_add_c2(a,2,0,c3,c1,c2);
r[2]=c3;
c3=0;
sqr_add_c2(a,3,0,c1,c2,c3);
sqr_add_c2(a,2,1,c1,c2,c3);
r[3]=c1;
c1=0;
sqr_add_c(a,2,c2,c3,c1);
sqr_add_c2(a,3,1,c2,c3,c1);
sqr_add_c2(a,4,0,c2,c3,c1);
r[4]=c2;
c2=0;
sqr_add_c2(a,5,0,c3,c1,c2);
sqr_add_c2(a,4,1,c3,c1,c2);
sqr_add_c2(a,3,2,c3,c1,c2);
r[5]=c3;
c3=0;
sqr_add_c(a,3,c1,c2,c3);
sqr_add_c2(a,4,2,c1,c2,c3);
sqr_add_c2(a,5,1,c1,c2,c3);
sqr_add_c2(a,6,0,c1,c2,c3);
r[6]=c1;
c1=0;
sqr_add_c2(a,7,0,c2,c3,c1);
sqr_add_c2(a,6,1,c2,c3,c1);
sqr_add_c2(a,5,2,c2,c3,c1);
sqr_add_c2(a,4,3,c2,c3,c1);
r[7]=c2;
c2=0;
sqr_add_c(a,4,c3,c1,c2);
sqr_add_c2(a,5,3,c3,c1,c2);
sqr_add_c2(a,6,2,c3,c1,c2);
sqr_add_c2(a,7,1,c3,c1,c2);
r[8]=c3;
c3=0;
sqr_add_c2(a,7,2,c1,c2,c3);
sqr_add_c2(a,6,3,c1,c2,c3);
sqr_add_c2(a,5,4,c1,c2,c3);
r[9]=c1;
c1=0;
sqr_add_c(a,5,c2,c3,c1);
sqr_add_c2(a,6,4,c2,c3,c1);
sqr_add_c2(a,7,3,c2,c3,c1);
r[10]=c2;
c2=0;
sqr_add_c2(a,7,4,c3,c1,c2);
sqr_add_c2(a,6,5,c3,c1,c2);
r[11]=c3;
c3=0;
sqr_add_c(a,6,c1,c2,c3);
sqr_add_c2(a,7,5,c1,c2,c3);
r[12]=c1;
c1=0;
sqr_add_c2(a,7,6,c2,c3,c1);
r[13]=c2;
c2=0;
sqr_add_c(a,7,c3,c1,c2);
r[14]=c3;
r[15]=c1;
}
Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp).
Reviewed-by: Emilia Kasper <[email protected]>
CWE ID: CWE-310 | void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a)
{
BN_ULONG c1,c2,c3;
c1=0;
c2=0;
c3=0;
sqr_add_c(a,0,c1,c2,c3);
r[0]=c1;
c1=0;
sqr_add_c2(a,1,0,c2,c3,c1);
r[1]=c2;
c2=0;
sqr_add_c(a,1,c3,c1,c2);
sqr_add_c2(a,2,0,c3,c1,c2);
r[2]=c3;
c3=0;
sqr_add_c2(a,3,0,c1,c2,c3);
sqr_add_c2(a,2,1,c1,c2,c3);
r[3]=c1;
c1=0;
sqr_add_c(a,2,c2,c3,c1);
sqr_add_c2(a,3,1,c2,c3,c1);
sqr_add_c2(a,4,0,c2,c3,c1);
r[4]=c2;
c2=0;
sqr_add_c2(a,5,0,c3,c1,c2);
sqr_add_c2(a,4,1,c3,c1,c2);
sqr_add_c2(a,3,2,c3,c1,c2);
r[5]=c3;
c3=0;
sqr_add_c(a,3,c1,c2,c3);
sqr_add_c2(a,4,2,c1,c2,c3);
sqr_add_c2(a,5,1,c1,c2,c3);
sqr_add_c2(a,6,0,c1,c2,c3);
r[6]=c1;
c1=0;
sqr_add_c2(a,7,0,c2,c3,c1);
sqr_add_c2(a,6,1,c2,c3,c1);
sqr_add_c2(a,5,2,c2,c3,c1);
sqr_add_c2(a,4,3,c2,c3,c1);
r[7]=c2;
c2=0;
sqr_add_c(a,4,c3,c1,c2);
sqr_add_c2(a,5,3,c3,c1,c2);
sqr_add_c2(a,6,2,c3,c1,c2);
sqr_add_c2(a,7,1,c3,c1,c2);
r[8]=c3;
c3=0;
sqr_add_c2(a,7,2,c1,c2,c3);
sqr_add_c2(a,6,3,c1,c2,c3);
sqr_add_c2(a,5,4,c1,c2,c3);
r[9]=c1;
c1=0;
sqr_add_c(a,5,c2,c3,c1);
sqr_add_c2(a,6,4,c2,c3,c1);
sqr_add_c2(a,7,3,c2,c3,c1);
r[10]=c2;
c2=0;
sqr_add_c2(a,7,4,c3,c1,c2);
sqr_add_c2(a,6,5,c3,c1,c2);
r[11]=c3;
c3=0;
sqr_add_c(a,6,c1,c2,c3);
sqr_add_c2(a,7,5,c1,c2,c3);
r[12]=c1;
c1=0;
sqr_add_c2(a,7,6,c2,c3,c1);
r[13]=c2;
c2=0;
sqr_add_c(a,7,c3,c1,c2);
r[14]=c3;
r[15]=c1;
}
| 166,831 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static OPJ_BOOL opj_pi_next_cprl(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 {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
OPJ_UINT32 resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
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->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_cprl(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 {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
OPJ_UINT32 resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
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->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 */
/* Fixes reading 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.5 Component-position-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,455 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadManagerImpl::DownloadUrl(
std::unique_ptr<download::DownloadUrlParameters> params,
std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
if (params->post_id() >= 0) {
DCHECK(params->prefer_cache());
DCHECK_EQ("POST", params->method());
}
download::RecordDownloadCountWithSource(
download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT,
params->download_source());
auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(),
params->render_frame_host_routing_id());
BeginDownloadInternal(std::move(params), std::move(blob_data_handle),
std::move(blob_url_loader_factory), true,
rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL());
}
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 | void DownloadManagerImpl::DownloadUrl(
std::unique_ptr<download::DownloadUrlParameters> params,
std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
if (params->post_id() >= 0) {
DCHECK(params->prefer_cache());
DCHECK_EQ("POST", params->method());
}
download::RecordDownloadCountWithSource(
download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT,
params->download_source());
auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(),
params->render_frame_host_routing_id());
if (rfh)
params->set_frame_tree_node_id(rfh->GetFrameTreeNodeId());
BeginDownloadInternal(std::move(params), std::move(blob_data_handle),
std::move(blob_url_loader_factory), true,
rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL());
}
| 173,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MessageLoop::RunTask(PendingTask* pending_task) {
DCHECK(nestable_tasks_allowed_);
current_pending_task_ = pending_task;
#if defined(OS_WIN)
DecrementHighResTaskCountIfNeeded(*pending_task);
#endif
nestable_tasks_allowed_ = false;
TRACE_TASK_EXECUTION("MessageLoop::RunTask", *pending_task);
for (auto& observer : task_observers_)
observer.WillProcessTask(*pending_task);
task_annotator_.RunTask("MessageLoop::PostTask", pending_task);
for (auto& observer : task_observers_)
observer.DidProcessTask(*pending_task);
nestable_tasks_allowed_ = true;
current_pending_task_ = nullptr;
}
Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower.
(as well as MessageLoop::SetNestableTasksAllowed())
Surveying usage: the scoped object is always instantiated right before
RunLoop().Run(). The intent is really to allow nestable tasks in that
RunLoop so it's better to explicitly label that RunLoop as such and it
allows us to break the last dependency that forced some RunLoop users
to use MessageLoop APIs.
There's also the odd case of allowing nestable tasks for loops that are
reentrant from a native task (without going through RunLoop), these
are the minority but will have to be handled (after cleaning up the
majority of cases that are RunLoop induced).
As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517
(which was merged in this CL).
[email protected]
Bug: 750779
Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448
Reviewed-on: https://chromium-review.googlesource.com/594713
Commit-Queue: Gabriel Charette <[email protected]>
Reviewed-by: Robert Liao <[email protected]>
Reviewed-by: danakj <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492263}
CWE ID: | void MessageLoop::RunTask(PendingTask* pending_task) {
DCHECK(NestableTasksAllowed());
current_pending_task_ = pending_task;
#if defined(OS_WIN)
DecrementHighResTaskCountIfNeeded(*pending_task);
#endif
nestable_tasks_allowed_ = false;
TRACE_TASK_EXECUTION("MessageLoop::RunTask", *pending_task);
for (auto& observer : task_observers_)
observer.WillProcessTask(*pending_task);
task_annotator_.RunTask("MessageLoop::PostTask", pending_task);
for (auto& observer : task_observers_)
observer.DidProcessTask(*pending_task);
nestable_tasks_allowed_ = true;
current_pending_task_ = nullptr;
}
| 171,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void VRDisplay::OnFocus() {
display_blurred_ = false;
ConnectVSyncProvider();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayfocus, true, false, this, ""));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::OnFocus() {
DVLOG(1) << __FUNCTION__;
display_blurred_ = false;
ConnectVSyncProvider();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayfocus, true, false, this, ""));
}
| 171,995 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaInterfaceProxy::CreateCdm(
media::mojom::ContentDecryptionModuleRequest request) {
DCHECK(thread_checker_.CalledOnValidThread());
GetMediaInterfaceFactory()->CreateCdm(std::move(request));
}
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947}
CWE ID: CWE-119 | void MediaInterfaceProxy::CreateCdm(
media::mojom::ContentDecryptionModuleRequest request) {
DCHECK(thread_checker_.CalledOnValidThread());
GetCdmInterfaceFactory()->CreateCdm(std::move(request));
}
| 171,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const unsigned char* Track::GetCodecPrivate(size_t& size) const
{
size = m_info.codecPrivateSize;
return m_info.codecPrivate;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const unsigned char* Track::GetCodecPrivate(size_t& size) const
| 174,295 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DebuggerDetachFunction::RunAsync() {
std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitClientHost())
return false;
client_host_->Close();
SendResponse(true);
return true;
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | bool DebuggerDetachFunction::RunAsync() {
std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitClientHost())
return false;
client_host_->RespondDetachedToPendingRequests();
client_host_->Close();
SendResponse(true);
return true;
}
| 173,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadSCRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char zxscr[6144];
char zxattr[768];
int octetnr;
int octetline;
int zoneline;
int zonenr;
int octet_val;
int attr_nr;
int pix;
int piy;
int binar[8];
int attrbin[8];
int *pbin;
int *abin;
int z;
int one_nr;
int ink;
int paper;
int bright;
unsigned char colour_palette[] = {
0, 0, 0,
0, 0,192,
192, 0, 0,
192, 0,192,
0,192, 0,
0,192,192,
192,192, 0,
192,192,192,
0, 0, 0,
0, 0,255,
255, 0, 0,
255, 0,255,
0,255, 0,
0,255,255,
255,255, 0,
255,255,255
};
Image
*image;
MagickBooleanType
status;
register PixelPacket
*q;
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->columns = 256;
image->rows = 192;
count=ReadBlob(image,6144,(unsigned char *) zxscr);
(void) count;
count=ReadBlob(image,768,(unsigned char *) zxattr);
for(zonenr=0;zonenr<3;zonenr++)
{
for(zoneline=0;zoneline<8;zoneline++)
{
for(octetline=0;octetline<8;octetline++)
{
for(octetnr=(zoneline*32);octetnr<((zoneline*32)+32);octetnr++)
{
octet_val = zxscr[octetnr+(256*octetline)+(zonenr*2048)];
attr_nr = zxattr[octetnr+(256*zonenr)];
pix = (((8*octetnr)-(256*zoneline)));
piy = ((octetline+(8*zoneline)+(zonenr*64)));
pbin = binar;
abin = attrbin;
one_nr=1;
for(z=0;z<8;z++)
{
if(octet_val&one_nr)
{
*pbin = 1;
} else {
*pbin = 0;
}
one_nr=one_nr*2;
pbin++;
}
one_nr = 1;
for(z=0;z<8;z++)
{
if(attr_nr&one_nr)
{
*abin = 1;
} else {
*abin = 0;
}
one_nr=one_nr*2;
abin++;
}
ink = (attrbin[0]+(2*attrbin[1])+(4*attrbin[2]));
paper = (attrbin[3]+(2*attrbin[4])+(4*attrbin[5]));
bright = attrbin[6];
if(bright) { ink=ink+8; paper=paper+8; }
for(z=7;z>-1;z--)
{
q=QueueAuthenticPixels(image,pix,piy,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
if(binar[z])
{
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*ink]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*ink)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*ink)]));
} else {
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*paper]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*paper)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*paper)]));
}
pix++;
}
}
}
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadSCRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char zxscr[6144];
char zxattr[768];
int octetnr;
int octetline;
int zoneline;
int zonenr;
int octet_val;
int attr_nr;
int pix;
int piy;
int binar[8];
int attrbin[8];
int *pbin;
int *abin;
int z;
int one_nr;
int ink;
int paper;
int bright;
unsigned char colour_palette[] = {
0, 0, 0,
0, 0,192,
192, 0, 0,
192, 0,192,
0,192, 0,
0,192,192,
192,192, 0,
192,192,192,
0, 0, 0,
0, 0,255,
255, 0, 0,
255, 0,255,
0,255, 0,
0,255,255,
255,255, 0,
255,255,255
};
Image
*image;
MagickBooleanType
status;
register PixelPacket
*q;
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->columns = 256;
image->rows = 192;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
count=ReadBlob(image,6144,(unsigned char *) zxscr);
(void) count;
count=ReadBlob(image,768,(unsigned char *) zxattr);
for(zonenr=0;zonenr<3;zonenr++)
{
for(zoneline=0;zoneline<8;zoneline++)
{
for(octetline=0;octetline<8;octetline++)
{
for(octetnr=(zoneline*32);octetnr<((zoneline*32)+32);octetnr++)
{
octet_val = zxscr[octetnr+(256*octetline)+(zonenr*2048)];
attr_nr = zxattr[octetnr+(256*zonenr)];
pix = (((8*octetnr)-(256*zoneline)));
piy = ((octetline+(8*zoneline)+(zonenr*64)));
pbin = binar;
abin = attrbin;
one_nr=1;
for(z=0;z<8;z++)
{
if(octet_val&one_nr)
{
*pbin = 1;
} else {
*pbin = 0;
}
one_nr=one_nr*2;
pbin++;
}
one_nr = 1;
for(z=0;z<8;z++)
{
if(attr_nr&one_nr)
{
*abin = 1;
} else {
*abin = 0;
}
one_nr=one_nr*2;
abin++;
}
ink = (attrbin[0]+(2*attrbin[1])+(4*attrbin[2]));
paper = (attrbin[3]+(2*attrbin[4])+(4*attrbin[5]));
bright = attrbin[6];
if(bright) { ink=ink+8; paper=paper+8; }
for(z=7;z>-1;z--)
{
q=QueueAuthenticPixels(image,pix,piy,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
if(binar[z])
{
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*ink]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*ink)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*ink)]));
} else {
SetPixelRed(q,ScaleCharToQuantum(
colour_palette[3*paper]));
SetPixelGreen(q,ScaleCharToQuantum(
colour_palette[1+(3*paper)]));
SetPixelBlue(q,ScaleCharToQuantum(
colour_palette[2+(3*paper)]));
}
pix++;
}
}
}
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int SpdyProxyClientSocket::DoReadReplyComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
switch (response_.headers->response_code()) {
case 200: // OK
next_state_ = STATE_OPEN;
return OK;
case 302: // Found / Moved Temporarily
if (SanitizeProxyRedirect(&response_, request_.url)) {
redirect_has_load_timing_info_ =
spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_);
spdy_stream_->DetachDelegate();
next_state_ = STATE_DISCONNECTED;
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
} else {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
case 407: // Proxy Authentication Required
next_state_ = STATE_OPEN;
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
CWE ID: CWE-19 | int SpdyProxyClientSocket::DoReadReplyComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
switch (response_.headers->response_code()) {
case 200: // OK
next_state_ = STATE_OPEN;
return OK;
case 302: // Found / Moved Temporarily
if (!SanitizeProxyRedirect(&response_)) {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
redirect_has_load_timing_info_ =
spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_);
// Note that this triggers a RST_STREAM_CANCEL.
spdy_stream_->DetachDelegate();
next_state_ = STATE_DISCONNECTED;
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
case 407: // Proxy Authentication Required
next_state_ = STATE_OPEN;
if (!SanitizeProxyAuth(&response_)) {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
| 172,041 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
if (!g_teredo_enabled)
return TM_ECODE_FAILED;
uint8_t *start = pkt;
/* Is this packet to short to contain an IPv6 packet ? */
if (len < IPV6_HEADER_LEN)
return TM_ECODE_FAILED;
/* Teredo encapsulate IPv6 in UDP and can add some custom message
* part before the IPv6 packet. In our case, we just want to get
* over an ORIGIN indication. So we just make one offset if needed. */
if (start[0] == 0x0) {
switch (start[1]) {
/* origin indication: compatible with tunnel */
case 0x0:
/* offset is coherent with len and presence of an IPv6 header */
if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN)
start += TEREDO_ORIG_INDICATION_LENGTH;
else
return TM_ECODE_FAILED;
break;
/* authentication: negotiation not real tunnel */
case 0x1:
return TM_ECODE_FAILED;
/* this case is not possible in Teredo: not that protocol */
default:
return TM_ECODE_FAILED;
}
}
/* There is no specific field that we can check to prove that the packet
* is a Teredo packet. We've zapped here all the possible Teredo header
* and we should have an IPv6 packet at the start pointer.
* We then can only do two checks before sending the encapsulated packets
* to decoding:
* - The packet has a protocol version which is IPv6.
* - The IPv6 length of the packet matches what remains in buffer.
*/
if (IP_GET_RAW_VER(start) == 6) {
IPV6Hdr *thdr = (IPV6Hdr *)start;
if (len == IPV6_HEADER_LEN +
IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) {
if (pq != NULL) {
int blen = len - (start - pkt);
/* spawn off tunnel packet */
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen,
DECODE_TUNNEL_IPV6, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO);
/* add the tp to the packet queue. */
PacketEnqueue(pq,tp);
StatsIncr(tv, dtv->counter_teredo);
return TM_ECODE_OK;
}
}
}
return TM_ECODE_FAILED;
}
return TM_ECODE_FAILED;
}
Commit Message: teredo: be stricter on what to consider valid teredo
Invalid Teredo can lead to valid DNS traffic (or other UDP traffic)
being misdetected as Teredo. This leads to false negatives in the
UDP payload inspection.
Make the teredo code only consider a packet teredo if the encapsulated
data was decoded without any 'invalid' events being set.
Bug #2736.
CWE ID: CWE-20 | int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
if (!g_teredo_enabled)
return TM_ECODE_FAILED;
uint8_t *start = pkt;
/* Is this packet to short to contain an IPv6 packet ? */
if (len < IPV6_HEADER_LEN)
return TM_ECODE_FAILED;
/* Teredo encapsulate IPv6 in UDP and can add some custom message
* part before the IPv6 packet. In our case, we just want to get
* over an ORIGIN indication. So we just make one offset if needed. */
if (start[0] == 0x0) {
switch (start[1]) {
/* origin indication: compatible with tunnel */
case 0x0:
/* offset is coherent with len and presence of an IPv6 header */
if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN)
start += TEREDO_ORIG_INDICATION_LENGTH;
else
return TM_ECODE_FAILED;
break;
/* authentication: negotiation not real tunnel */
case 0x1:
return TM_ECODE_FAILED;
/* this case is not possible in Teredo: not that protocol */
default:
return TM_ECODE_FAILED;
}
}
/* There is no specific field that we can check to prove that the packet
* is a Teredo packet. We've zapped here all the possible Teredo header
* and we should have an IPv6 packet at the start pointer.
* We then can only do a few checks before sending the encapsulated packets
* to decoding:
* - The packet has a protocol version which is IPv6.
* - The IPv6 length of the packet matches what remains in buffer.
* - HLIM is 0. This would technically be valid, but still weird.
* - NH 0 (HOP) and not enough data.
*
* If all these conditions are met, the tunnel decoder will be called.
* If the packet gets an invalid event set, it will still be rejected.
*/
if (IP_GET_RAW_VER(start) == 6) {
IPV6Hdr *thdr = (IPV6Hdr *)start;
/* ignore hoplimit 0 packets, most likely an artifact of bad detection */
if (IPV6_GET_RAW_HLIM(thdr) == 0)
return TM_ECODE_FAILED;
/* if nh is 0 (HOP) with little data we have a bogus packet */
if (IPV6_GET_RAW_NH(thdr) == 0 && IPV6_GET_RAW_PLEN(thdr) < 8)
return TM_ECODE_FAILED;
if (len == IPV6_HEADER_LEN +
IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) {
if (pq != NULL) {
int blen = len - (start - pkt);
/* spawn off tunnel packet */
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen,
DECODE_TUNNEL_IPV6_TEREDO, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO);
/* add the tp to the packet queue. */
PacketEnqueue(pq,tp);
StatsIncr(tv, dtv->counter_teredo);
return TM_ECODE_OK;
}
}
}
return TM_ECODE_FAILED;
}
return TM_ECODE_FAILED;
}
| 169,477 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
Buffer* buf, int *err, gchar **err_info)
{
guint8 *pd;
gchar line[COSINE_LINE_LENGTH];
int i, hex_lines, n, caplen = 0;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12395
Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2
Reviewed-on: https://code.wireshark.org/review/15172
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-119 | parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
| 169,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FidoCableHandshakeHandler::ValidateAuthenticatorHandshakeMessage(
base::span<const uint8_t> response) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(handshake_key_))
return false;
if (response.size() != kCableAuthenticatorHandshakeMessageSize) {
return false;
}
const auto authenticator_hello = response.first(
kCableAuthenticatorHandshakeMessageSize - kCableHandshakeMacMessageSize);
if (!hmac.VerifyTruncated(
fido_parsing_utils::ConvertToStringPiece(authenticator_hello),
fido_parsing_utils::ConvertToStringPiece(
response.subspan(authenticator_hello.size())))) {
return false;
}
const auto authenticator_hello_cbor =
cbor::CBORReader::Read(authenticator_hello);
if (!authenticator_hello_cbor || !authenticator_hello_cbor->is_map() ||
authenticator_hello_cbor->GetMap().size() != 2) {
return false;
}
const auto authenticator_hello_msg =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(0));
if (authenticator_hello_msg == authenticator_hello_cbor->GetMap().end() ||
!authenticator_hello_msg->second.is_string() ||
authenticator_hello_msg->second.GetString() !=
kCableAuthenticatorHelloMessage) {
return false;
}
const auto authenticator_random_nonce =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(1));
if (authenticator_random_nonce == authenticator_hello_cbor->GetMap().end() ||
!authenticator_random_nonce->second.is_bytestring() ||
authenticator_random_nonce->second.GetBytestring().size() != 16) {
return false;
}
cable_device_->SetEncryptionData(
GetEncryptionKeyAfterSuccessfulHandshake(
authenticator_random_nonce->second.GetBytestring()),
nonce_);
return true;
}
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586657}
CWE ID: CWE-22 | bool FidoCableHandshakeHandler::ValidateAuthenticatorHandshakeMessage(
base::span<const uint8_t> response) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(handshake_key_))
return false;
if (response.size() != kCableAuthenticatorHandshakeMessageSize) {
return false;
}
const auto authenticator_hello = response.first(
kCableAuthenticatorHandshakeMessageSize - kCableHandshakeMacMessageSize);
if (!hmac.VerifyTruncated(
fido_parsing_utils::ConvertToStringPiece(authenticator_hello),
fido_parsing_utils::ConvertToStringPiece(
response.subspan(authenticator_hello.size())))) {
return false;
}
const auto authenticator_hello_cbor =
cbor::CBORReader::Read(authenticator_hello);
if (!authenticator_hello_cbor || !authenticator_hello_cbor->is_map() ||
authenticator_hello_cbor->GetMap().size() != 2) {
return false;
}
const auto authenticator_hello_msg =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(0));
if (authenticator_hello_msg == authenticator_hello_cbor->GetMap().end() ||
!authenticator_hello_msg->second.is_string() ||
authenticator_hello_msg->second.GetString() !=
kCableAuthenticatorHelloMessage) {
return false;
}
const auto authenticator_random_nonce =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(1));
if (authenticator_random_nonce == authenticator_hello_cbor->GetMap().end() ||
!authenticator_random_nonce->second.is_bytestring() ||
authenticator_random_nonce->second.GetBytestring().size() != 16) {
return false;
}
cable_device_->SetEncryptionData(
GetEncryptionKeyAfterSuccessfulHandshake(base::make_span<16>(
authenticator_random_nonce->second.GetBytestring())),
nonce_);
return true;
}
| 172,274 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void registerBlobURLFromTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static void registerBlobURLFromTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
if (WebBlobRegistry* registry = blobRegistry())
registry->registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
}
| 170,686 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_strip_alpha_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_strip_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_MASK_ALPHA) != 0;
}
| 173,651 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner)
: context_(base::MakeUnique<Context>(task_runner)) {}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner)
| 173,262 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void buffer_slow_realign(struct buffer *buf)
{
/* two possible cases :
* - the buffer is in one contiguous block, we move it in-place
* - the buffer is in two blocks, we move it via the swap_buffer
*/
if (buf->i) {
int block1 = buf->i;
int block2 = 0;
if (buf->p + buf->i > buf->data + buf->size) {
/* non-contiguous block */
block1 = buf->data + buf->size - buf->p;
block2 = buf->p + buf->i - (buf->data + buf->size);
}
if (block2)
memcpy(swap_buffer, buf->data, block2);
memmove(buf->data, buf->p, block1);
if (block2)
memcpy(buf->data + block1, swap_buffer, block2);
}
buf->p = buf->data;
}
Commit Message:
CWE ID: CWE-119 | void buffer_slow_realign(struct buffer *buf)
{
int block1 = buf->o;
int block2 = 0;
/* process output data in two steps to cover wrapping */
if (block1 > buf->p - buf->data) {
block2 = buf->p - buf->data;
block1 -= block2;
}
memcpy(swap_buffer + buf->size - buf->o, bo_ptr(buf), block1);
memcpy(swap_buffer + buf->size - block2, buf->data, block2);
/* process input data in two steps to cover wrapping */
block1 = buf->i;
block2 = 0;
if (block1 > buf->data + buf->size - buf->p) {
block1 = buf->data + buf->size - buf->p;
block2 = buf->i - block1;
}
memcpy(swap_buffer, bi_ptr(buf), block1);
memcpy(swap_buffer + block1, buf->data, block2);
/* reinject changes into the buffer */
memcpy(buf->data, swap_buffer, buf->i);
memcpy(buf->data + buf->size - buf->o, swap_buffer + buf->size - buf->o, buf->o);
buf->p = buf->data;
}
| 164,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
int i, err = 0;
int free = -1;
mutex_lock(&table->mutex);
for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) {
if (free < 0 && (table->refs[i] == 0)) {
free = i;
continue;
}
if (table->refs[i] &&
(vlan == (MLX4_VLAN_MASK &
be32_to_cpu(table->entries[i])))) {
/* Vlan already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (table->total == table->max) {
/* No free vlan entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID);
err = mlx4_set_port_vlan_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_warn(dev, "Failed adding vlan: %u\n", vlan);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
Commit Message: mlx4_en: Fix out of bounds array access
When searching for a free entry in either mlx4_register_vlan() or
mlx4_register_mac(), and there is no free entry, the loop terminates without
updating the local variable free thus causing out of array bounds access. Fix
this by adding a proper check outside the loop.
Signed-off-by: Eli Cohen <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
int i, err = 0;
int free = -1;
mutex_lock(&table->mutex);
for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) {
if (free < 0 && (table->refs[i] == 0)) {
free = i;
continue;
}
if (table->refs[i] &&
(vlan == (MLX4_VLAN_MASK &
be32_to_cpu(table->entries[i])))) {
/* Vlan already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (free < 0) {
err = -ENOMEM;
goto out;
}
if (table->total == table->max) {
/* No free vlan entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID);
err = mlx4_set_port_vlan_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_warn(dev, "Failed adding vlan: %u\n", vlan);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
| 169,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ResourceDispatcherHostImpl::BeginRequest(
int request_id,
const ResourceHostMsg_Request& request_data,
IPC::Message* sync_result, // only valid for sync
int route_id) {
int process_type = filter_->process_type();
int child_id = filter_->child_id();
if (IsBrowserSideNavigationEnabled() &&
IsResourceTypeFrame(request_data.resource_type) &&
!request_data.url.SchemeIs(url::kBlobScheme)) {
bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_URL);
return;
}
if (request_data.priority < net::MINIMUM_PRIORITY ||
request_data.priority > net::MAXIMUM_PRIORITY) {
bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_PRIORITY);
return;
}
char url_buf[128];
base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf));
base::debug::Alias(url_buf);
LoaderMap::iterator it = pending_loaders_.find(
GlobalRequestID(request_data.transferred_request_child_id,
request_data.transferred_request_request_id));
if (it != pending_loaders_.end()) {
if (it->second->is_transferring()) {
ResourceLoader* deferred_loader = it->second.get();
UpdateRequestForTransfer(child_id, route_id, request_id,
request_data, it);
deferred_loader->CompleteTransfer();
} else {
bad_message::ReceivedBadMessage(
filter_, bad_message::RDH_REQUEST_NOT_TRANSFERRING);
}
return;
}
ResourceContext* resource_context = NULL;
net::URLRequestContext* request_context = NULL;
filter_->GetContexts(request_data.resource_type, request_data.origin_pid,
&resource_context, &request_context);
CHECK(ContainsKey(active_resource_contexts_, resource_context));
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(request_data.headers);
if (is_shutdown_ ||
!ShouldServiceRequest(process_type, child_id, request_data, headers,
filter_, resource_context)) {
AbortRequestBeforeItStarts(filter_, sync_result, request_id);
return;
}
if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method,
request_data.url,
request_data.resource_type,
resource_context)) {
AbortRequestBeforeItStarts(filter_, sync_result, request_id);
return;
}
scoped_ptr<net::URLRequest> new_request = request_context->CreateRequest(
request_data.url, request_data.priority, NULL);
new_request->set_method(request_data.method);
new_request->set_first_party_for_cookies(
request_data.first_party_for_cookies);
new_request->set_initiator(request_data.request_initiator);
if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
new_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
}
const Referrer referrer(request_data.referrer, request_data.referrer_policy);
SetReferrerForRequest(new_request.get(), referrer);
new_request->SetExtraRequestHeaders(headers);
storage::BlobStorageContext* blob_context =
GetBlobStorageContext(filter_->blob_storage_context());
if (request_data.request_body.get()) {
if (blob_context) {
AttachRequestBodyBlobDataHandles(
request_data.request_body.get(),
blob_context);
}
new_request->set_upload(UploadDataStreamBuilder::Build(
request_data.request_body.get(),
blob_context,
filter_->file_system_context(),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
.get()));
}
bool allow_download = request_data.allow_download &&
IsResourceTypeFrame(request_data.resource_type);
bool do_not_prompt_for_login = request_data.do_not_prompt_for_login;
bool is_sync_load = sync_result != NULL;
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
bool report_raw_headers = request_data.report_raw_headers;
if (report_raw_headers && !policy->CanReadRawCookies(child_id)) {
VLOG(1) << "Denied unauthorized request for raw headers";
report_raw_headers = false;
}
int load_flags =
BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
if (request_data.resource_type == RESOURCE_TYPE_PREFETCH ||
request_data.resource_type == RESOURCE_TYPE_FAVICON) {
do_not_prompt_for_login = true;
}
if (request_data.resource_type == RESOURCE_TYPE_IMAGE &&
HTTP_AUTH_RELATION_BLOCKED_CROSS ==
HttpAuthRelationTypeOf(request_data.url,
request_data.first_party_for_cookies)) {
do_not_prompt_for_login = true;
load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
}
bool support_async_revalidation =
!is_sync_load && async_revalidation_manager_ &&
AsyncRevalidationManager::QualifiesForAsyncRevalidation(request_data);
if (support_async_revalidation)
load_flags |= net::LOAD_SUPPORT_ASYNC_REVALIDATION;
if (is_sync_load) {
DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
} else {
DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
}
new_request->SetLoadFlags(load_flags);
ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
process_type, child_id, route_id,
-1, // frame_tree_node_id
request_data.origin_pid, request_id, request_data.render_frame_id,
request_data.is_main_frame, request_data.parent_is_main_frame,
request_data.resource_type, request_data.transition_type,
request_data.should_replace_current_entry,
false, // is download
false, // is stream
allow_download, request_data.has_user_gesture,
request_data.enable_load_timing, request_data.enable_upload_progress,
do_not_prompt_for_login, request_data.referrer_policy,
request_data.visiblity_state, resource_context, filter_->GetWeakPtr(),
report_raw_headers, !is_sync_load,
IsUsingLoFi(request_data.lofi_state, delegate_, *new_request,
resource_context,
request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME),
support_async_revalidation ? request_data.headers : std::string());
extra_info->AssociateWithRequest(new_request.get());
if (new_request->url().SchemeIs(url::kBlobScheme)) {
storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
new_request.get(),
filter_->blob_storage_context()->context()->GetBlobDataFromPublicURL(
new_request->url()));
}
const bool should_skip_service_worker =
request_data.skip_service_worker || is_sync_load;
ServiceWorkerRequestHandler::InitializeHandler(
new_request.get(), filter_->service_worker_context(), blob_context,
child_id, request_data.service_worker_provider_id,
should_skip_service_worker,
request_data.fetch_request_mode, request_data.fetch_credentials_mode,
request_data.fetch_redirect_mode, request_data.resource_type,
request_data.fetch_request_context_type, request_data.fetch_frame_type,
request_data.request_body);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
ForeignFetchRequestHandler::InitializeHandler(
new_request.get(), filter_->service_worker_context(), blob_context,
child_id, request_data.service_worker_provider_id,
should_skip_service_worker,
request_data.fetch_request_mode, request_data.fetch_credentials_mode,
request_data.fetch_redirect_mode, request_data.resource_type,
request_data.fetch_request_context_type, request_data.fetch_frame_type,
request_data.request_body);
}
AppCacheInterceptor::SetExtraRequestInfo(
new_request.get(), filter_->appcache_service(), child_id,
request_data.appcache_host_id, request_data.resource_type,
request_data.should_reset_appcache);
scoped_ptr<ResourceHandler> handler(
CreateResourceHandler(
new_request.get(),
request_data, sync_result, route_id, process_type, child_id,
resource_context));
if (handler)
BeginRequestInternal(std::move(new_request), std::move(handler));
}
Commit Message: Block a compromised renderer from reusing request ids.
BUG=578882
Review URL: https://codereview.chromium.org/1608573002
Cr-Commit-Position: refs/heads/master@{#372547}
CWE ID: CWE-362 | void ResourceDispatcherHostImpl::BeginRequest(
int request_id,
const ResourceHostMsg_Request& request_data,
IPC::Message* sync_result, // only valid for sync
int route_id) {
int process_type = filter_->process_type();
int child_id = filter_->child_id();
// Reject request id that's currently in use.
if (IsRequestIDInUse(GlobalRequestID(child_id, request_id))) {
bad_message::ReceivedBadMessage(filter_,
bad_message::RDH_INVALID_REQUEST_ID);
return;
}
if (IsBrowserSideNavigationEnabled() &&
IsResourceTypeFrame(request_data.resource_type) &&
!request_data.url.SchemeIs(url::kBlobScheme)) {
bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_URL);
return;
}
if (request_data.priority < net::MINIMUM_PRIORITY ||
request_data.priority > net::MAXIMUM_PRIORITY) {
bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_PRIORITY);
return;
}
char url_buf[128];
base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf));
base::debug::Alias(url_buf);
LoaderMap::iterator it = pending_loaders_.find(
GlobalRequestID(request_data.transferred_request_child_id,
request_data.transferred_request_request_id));
if (it != pending_loaders_.end()) {
if (it->second->is_transferring()) {
ResourceLoader* deferred_loader = it->second.get();
UpdateRequestForTransfer(child_id, route_id, request_id,
request_data, it);
deferred_loader->CompleteTransfer();
} else {
bad_message::ReceivedBadMessage(
filter_, bad_message::RDH_REQUEST_NOT_TRANSFERRING);
}
return;
}
ResourceContext* resource_context = NULL;
net::URLRequestContext* request_context = NULL;
filter_->GetContexts(request_data.resource_type, request_data.origin_pid,
&resource_context, &request_context);
CHECK(ContainsKey(active_resource_contexts_, resource_context));
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(request_data.headers);
if (is_shutdown_ ||
!ShouldServiceRequest(process_type, child_id, request_data, headers,
filter_, resource_context)) {
AbortRequestBeforeItStarts(filter_, sync_result, request_id);
return;
}
if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method,
request_data.url,
request_data.resource_type,
resource_context)) {
AbortRequestBeforeItStarts(filter_, sync_result, request_id);
return;
}
scoped_ptr<net::URLRequest> new_request = request_context->CreateRequest(
request_data.url, request_data.priority, NULL);
new_request->set_method(request_data.method);
new_request->set_first_party_for_cookies(
request_data.first_party_for_cookies);
new_request->set_initiator(request_data.request_initiator);
if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
new_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
}
const Referrer referrer(request_data.referrer, request_data.referrer_policy);
SetReferrerForRequest(new_request.get(), referrer);
new_request->SetExtraRequestHeaders(headers);
storage::BlobStorageContext* blob_context =
GetBlobStorageContext(filter_->blob_storage_context());
if (request_data.request_body.get()) {
if (blob_context) {
AttachRequestBodyBlobDataHandles(
request_data.request_body.get(),
blob_context);
}
new_request->set_upload(UploadDataStreamBuilder::Build(
request_data.request_body.get(),
blob_context,
filter_->file_system_context(),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
.get()));
}
bool allow_download = request_data.allow_download &&
IsResourceTypeFrame(request_data.resource_type);
bool do_not_prompt_for_login = request_data.do_not_prompt_for_login;
bool is_sync_load = sync_result != NULL;
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
bool report_raw_headers = request_data.report_raw_headers;
if (report_raw_headers && !policy->CanReadRawCookies(child_id)) {
VLOG(1) << "Denied unauthorized request for raw headers";
report_raw_headers = false;
}
int load_flags =
BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
if (request_data.resource_type == RESOURCE_TYPE_PREFETCH ||
request_data.resource_type == RESOURCE_TYPE_FAVICON) {
do_not_prompt_for_login = true;
}
if (request_data.resource_type == RESOURCE_TYPE_IMAGE &&
HTTP_AUTH_RELATION_BLOCKED_CROSS ==
HttpAuthRelationTypeOf(request_data.url,
request_data.first_party_for_cookies)) {
do_not_prompt_for_login = true;
load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
}
bool support_async_revalidation =
!is_sync_load && async_revalidation_manager_ &&
AsyncRevalidationManager::QualifiesForAsyncRevalidation(request_data);
if (support_async_revalidation)
load_flags |= net::LOAD_SUPPORT_ASYNC_REVALIDATION;
if (is_sync_load) {
DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
} else {
DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
}
new_request->SetLoadFlags(load_flags);
ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
process_type, child_id, route_id,
-1, // frame_tree_node_id
request_data.origin_pid, request_id, request_data.render_frame_id,
request_data.is_main_frame, request_data.parent_is_main_frame,
request_data.resource_type, request_data.transition_type,
request_data.should_replace_current_entry,
false, // is download
false, // is stream
allow_download, request_data.has_user_gesture,
request_data.enable_load_timing, request_data.enable_upload_progress,
do_not_prompt_for_login, request_data.referrer_policy,
request_data.visiblity_state, resource_context, filter_->GetWeakPtr(),
report_raw_headers, !is_sync_load,
IsUsingLoFi(request_data.lofi_state, delegate_, *new_request,
resource_context,
request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME),
support_async_revalidation ? request_data.headers : std::string());
extra_info->AssociateWithRequest(new_request.get());
if (new_request->url().SchemeIs(url::kBlobScheme)) {
storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
new_request.get(),
filter_->blob_storage_context()->context()->GetBlobDataFromPublicURL(
new_request->url()));
}
const bool should_skip_service_worker =
request_data.skip_service_worker || is_sync_load;
ServiceWorkerRequestHandler::InitializeHandler(
new_request.get(), filter_->service_worker_context(), blob_context,
child_id, request_data.service_worker_provider_id,
should_skip_service_worker,
request_data.fetch_request_mode, request_data.fetch_credentials_mode,
request_data.fetch_redirect_mode, request_data.resource_type,
request_data.fetch_request_context_type, request_data.fetch_frame_type,
request_data.request_body);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
ForeignFetchRequestHandler::InitializeHandler(
new_request.get(), filter_->service_worker_context(), blob_context,
child_id, request_data.service_worker_provider_id,
should_skip_service_worker,
request_data.fetch_request_mode, request_data.fetch_credentials_mode,
request_data.fetch_redirect_mode, request_data.resource_type,
request_data.fetch_request_context_type, request_data.fetch_frame_type,
request_data.request_body);
}
AppCacheInterceptor::SetExtraRequestInfo(
new_request.get(), filter_->appcache_service(), child_id,
request_data.appcache_host_id, request_data.resource_type,
request_data.should_reset_appcache);
scoped_ptr<ResourceHandler> handler(
CreateResourceHandler(
new_request.get(),
request_data, sync_result, route_id, process_type, child_id,
resource_context));
if (handler)
BeginRequestInternal(std::move(new_request), std::move(handler));
}
| 172,271 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_next_file(FILE *VFile, char *ptr)
{
char *ret;
ret = fgets(ptr, PATH_MAX, VFile);
if (!ret)
return NULL;
if (ptr[strlen(ptr) - 1] == '\n')
ptr[strlen(ptr) - 1] = '\0';
return ret;
}
Commit Message: (for 4.9.3) CVE-2018-14879/fix -V to fail invalid input safely
get_next_file() did not check the return value of strlen() and
underflowed an array index if the line read by fgets() from the file
started with \0. This caused an out-of-bounds read and could cause a
write. Add the missing check.
This vulnerability was discovered by Brian Carpenter & Geeknik Labs.
CWE ID: CWE-120 | get_next_file(FILE *VFile, char *ptr)
{
char *ret;
size_t len;
ret = fgets(ptr, PATH_MAX, VFile);
if (!ret)
return NULL;
len = strlen (ptr);
if (len > 0 && ptr[len - 1] == '\n')
ptr[len - 1] = '\0';
return ret;
}
| 169,835 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return 0.0;
GPMF_stream metadata_stream, *ms = &metadata_stream;
uint32_t teststart = 0;
uint32_t testend = mp4->indexcount;
double rate = 0.0;
if (mp4->indexcount < 1)
return 0.0;
if (mp4->indexcount > 3) // samples after first and before last are statistically the best, avoiding camera start up or shutdown anomollies.
{
teststart++;
testend--;
}
uint32_t *payload = GetPayload(handle, NULL, teststart); // second payload
uint32_t payloadsize = GetPayloadSize(handle, teststart);
int32_t ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
{
uint32_t startsamples = 0;
uint32_t endsamples = 0;
uint32_t missing_samples = 0;
while (ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))
{
missing_samples = 1;
teststart++;
payload = GetPayload(handle, payload, teststart); // second last payload
payloadsize = GetPayloadSize(handle, teststart);
ret = GPMF_Init(ms, payload, payloadsize);
}
if (missing_samples)
{
teststart++; //samples after sensor start are statistically the best
payload = GetPayload(handle, payload, teststart);
payloadsize = GetPayloadSize(handle, teststart);
ret = GPMF_Init(ms, payload, payloadsize);
}
if (ret == GPMF_OK)
{
uint32_t samples = GPMF_Repeat(ms);
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (!(flags & GPMF_SAMPLE_RATE_PRECISE) && GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
{
startsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples;
payload = GetPayload(handle, payload, testend); // second last payload
payloadsize = GetPayloadSize(handle, testend);
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))
{
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
{
endsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));
rate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
goto cleanup;
}
}
rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
}
else // for increased precision, for older GPMF streams sometimes missing the total sample count
{
uint32_t payloadpos = 0, payloadcount = 0;
double slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0;
uint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4);
memset(repeatarray, 0, mp4->indexcount * 4 + 4);
samples = 0;
for (payloadpos = teststart; payloadpos < testend; payloadcount++, payloadpos++)
{
payload = GetPayload(handle, payload, payloadpos); // second last payload
payloadsize = GetPayloadSize(handle, payloadpos);
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))
{
GPMF_stream find_stream2;
GPMF_CopyState(ms, &find_stream2);
if (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats
{
if (repeatarray)
{
float in, out;
do
{
samples++;
} while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL));
repeatarray[payloadpos] = samples;
meanY += (double)samples;
GetPayloadTime(handle, payloadpos, &in, &out);
meanX += out;
}
}
else
{
uint32_t repeat = GPMF_Repeat(ms);
samples += repeat;
if (repeatarray)
{
float in, out;
repeatarray[payloadpos] = samples;
meanY += (double)samples;
GetPayloadTime(handle, payloadpos, &in, &out);
meanX += out;
}
}
}
}
if (repeatarray)
{
meanY /= (double)payloadcount;
meanX /= (double)payloadcount;
for (payloadpos = teststart; payloadpos < testend; payloadpos++)
{
float in, out;
GetPayloadTime(handle, payloadpos, &in, &out);
top += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY);
bot += ((double)out - meanX)*((double)out - meanX);
}
slope = top / bot;
#if 0
{
double intercept;
intercept = meanY - slope*meanX;
printf("%c%c%c%c start offset = %f (%.3fms)\n", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope);
}
#endif
rate = slope;
}
else
{
rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
}
free(repeatarray);
goto cleanup;
}
}
}
cleanup:
if (payload)
{
FreePayload(payload);
payload = NULL;
}
return rate;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags)
double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags, double *firstsampletime, double *lastsampletime)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return 0.0;
GPMF_stream metadata_stream, *ms = &metadata_stream;
uint32_t teststart = 0;
uint32_t testend = mp4->indexcount;
double rate = 0.0;
uint32_t *payload;
uint32_t payloadsize;
int32_t ret;
if (mp4->indexcount < 1)
return 0.0;
payload = GetPayload(handle, NULL, teststart);
payloadsize = GetPayloadSize(handle, teststart);
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
{
uint64_t minimumtimestamp = 0;
uint64_t starttimestamp = 0;
uint64_t endtimestamp = 0;
uint32_t startsamples = 0;
uint32_t endsamples = 0;
double intercept = 0.0;
while (teststart < mp4->indexcount && ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))
{
teststart++;
payload = GetPayload(handle, payload, teststart); // second last payload
payloadsize = GetPayloadSize(handle, teststart);
ret = GPMF_Init(ms, payload, payloadsize);
}
if (ret == GPMF_OK && payload)
{
uint32_t samples = GPMF_PayloadSampleCount(ms);
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
startsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL))
starttimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream));
if (starttimestamp) // is this earliest in the payload, examine the other streams in this early payload.
{
GPMF_stream any_stream;
GPMF_Init(&any_stream, payload, payloadsize);
minimumtimestamp = starttimestamp;
while (GPMF_OK == GPMF_FindNext(&any_stream, GPMF_KEY_TIME_STAMP, GPMF_RECURSE_LEVELS))
{
uint64_t timestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&any_stream));
if (timestamp < minimumtimestamp)
minimumtimestamp = timestamp;
}
}
testend = mp4->indexcount;
do
{
testend--;// last payload with the fourcc needed
payload = GetPayload(handle, payload, testend);
payloadsize = GetPayloadSize(handle, testend);
ret = GPMF_Init(ms, payload, payloadsize);
} while (testend > 0 && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS));
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
endsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));
else // If there is no TSMP we have to count the samples.
{
uint32_t i;
for (i = teststart; i <= testend; i++)
{
payload = GetPayload(handle,payload, i); // second last payload
payloadsize = GetPayloadSize(handle, i);
if (GPMF_OK == GPMF_Init(ms, payload, payloadsize))
if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))
endsamples += GPMF_PayloadSampleCount(ms);
}
}
if (starttimestamp != 0)
{
uint32_t last_samples = GPMF_PayloadSampleCount(ms);
uint32_t totaltimestamped_samples = endsamples - last_samples - startsamples;
double time_stamp_scale = 1000000000.0; // scan for nanoseconds, microseconds to seconds, all base 10.
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL))
endtimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream));
if (endtimestamp)
{
double approxrate = 0.0;
if (endsamples > startsamples)
approxrate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
if (approxrate == 0.0)
approxrate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
while (time_stamp_scale >= 1)
{
rate = (double)(totaltimestamped_samples) / ((double)(endtimestamp - starttimestamp) / time_stamp_scale);
if (rate*0.9 < approxrate && approxrate < rate*1.1)
break;
time_stamp_scale *= 0.1;
}
if (time_stamp_scale < 1.0) rate = 0.0;
intercept = (((double)minimumtimestamp - (double)starttimestamp) / time_stamp_scale) * rate;
}
}
if (rate == 0.0) //Timestamps didn't help weren't available
{
if (!(flags & GPMF_SAMPLE_RATE_PRECISE))
{
if (endsamples > startsamples)
rate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
if (rate == 0.0)
rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
double in, out;
if (GPMF_OK == GetPayloadTime(handle, teststart, &in, &out))
intercept = (double)-in * rate;
}
else // for increased precision, for older GPMF streams sometimes missing the total sample count
{
uint32_t payloadpos = 0, payloadcount = 0;
double slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0;
uint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4);
memset(repeatarray, 0, mp4->indexcount * 4 + 4);
samples = 0;
for (payloadpos = teststart; payloadpos <= testend; payloadpos++)
{
payload = GetPayload(handle, payload, payloadpos); // second last payload
payloadsize = GetPayloadSize(handle, payloadpos);
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))
{
GPMF_stream find_stream2;
GPMF_CopyState(ms, &find_stream2);
payloadcount++;
if (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats
{
if (repeatarray)
{
double in, out;
do
{
samples++;
} while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL));
repeatarray[payloadpos] = samples;
meanY += (double)samples;
if (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out))
meanX += out;
}
}
else
{
uint32_t repeat = GPMF_PayloadSampleCount(ms);
samples += repeat;
if (repeatarray)
{
double in, out;
repeatarray[payloadpos] = samples;
meanY += (double)samples;
if (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out))
meanX += out;
}
}
}
else
{
repeatarray[payloadpos] = 0;
}
}
// Compute the line of best fit for a jitter removed sample rate.
// This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes.
// TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift.
if (repeatarray)
{
meanY /= (double)payloadcount;
meanX /= (double)payloadcount;
for (payloadpos = teststart; payloadpos <= testend; payloadpos++)
{
double in, out;
if (repeatarray[payloadpos] && GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out))
{
top += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY);
bot += ((double)out - meanX)*((double)out - meanX);
}
}
slope = top / bot;
rate = slope;
// This sample code might be useful for compare data latency between channels.
intercept = meanY - slope * meanX;
#if 0
printf("%c%c%c%c start offset = %f (%.3fms) rate = %f\n", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope, rate);
printf("%c%c%c%c first sample at time %.3fms\n", PRINTF_4CC(fourcc), -1000.0 * intercept / slope);
#endif
}
else
{
rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);
}
free(repeatarray);
}
}
| 169,546 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr)
{
/* This function is copied verbatim from plfont.c */
int table_length;
int table_offset;
ulong format;
uint numGlyphs;
uint glyph_name_index;
const byte *postp; /* post table pointer */
/* guess if the font type is not truetype */
if ( pfont->FontType != ft_TrueType )
{
pstr->size = strlen((char*)pstr->data);
return 0;
}
else
{
return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph);
}
}
Commit Message:
CWE ID: CWE-119 | xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr)
{
/* This function is copied verbatim from plfont.c */
int table_length;
int table_offset;
ulong format;
int numGlyphs;
uint glyph_name_index;
const byte *postp; /* post table pointer */
if (glyph >= GS_MIN_GLYPH_INDEX) {
glyph -= GS_MIN_GLYPH_INDEX;
}
/* guess if the font type is not truetype */
if ( pfont->FontType != ft_TrueType )
{
pstr->size = strlen((char*)pstr->data);
return 0;
}
else
{
return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph);
}
}
| 164,784 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GestureProviderAura::OnTouchEventAck(bool event_consumed) {
DCHECK(pending_gestures_.empty());
DCHECK(!handling_event_);
base::AutoReset<bool> handling_event(&handling_event_, true);
filtered_gesture_provider_.OnTouchEventAck(event_consumed);
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GestureProviderAura::OnTouchEventAck(bool event_consumed) {
DCHECK(pending_gestures_.empty());
DCHECK(!handling_event_);
base::AutoReset<bool> handling_event(&handling_event_, true);
filtered_gesture_provider_.OnTouchEventAck(event_consumed);
last_touch_event_latency_info_.Clear();
}
| 171,206 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
down_write(&card->controls_rwsem);
_kctl = snd_ctl_find_id(card, &info->id);
err = 0;
if (_kctl) {
if (replace)
err = snd_ctl_remove(card, _kctl);
else
err = -EBUSY;
} else {
if (replace)
err = -ENOENT;
}
up_write(&card->controls_rwsem);
if (err < 0)
return err;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->card = card;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
Commit Message: ALSA: control: Fix replacing user controls
There are two issues with the current implementation for replacing user
controls. The first is that the code does not check if the control is actually a
user control and neither does it check if the control is owned by the process
that tries to remove it. That allows userspace applications to remove arbitrary
controls, which can cause a user after free if a for example a driver does not
expect a control to be removed from under its feed.
The second issue is that on one hand when a control is replaced the
user_ctl_count limit is not checked and on the other hand the user_ctl_count is
increased (even though the number of user controls does not change). This allows
userspace, once the user_ctl_count limit as been reached, to repeatedly replace
a control until user_ctl_count overflows. Once that happens new controls can be
added effectively bypassing the user_ctl_count limit.
Both issues can be fixed by instead of open-coding the removal of the control
that is to be replaced to use snd_ctl_remove_user_ctl(). This function does
proper permission checks as well as decrements user_ctl_count after the control
has been removed.
Note that by using snd_ctl_remove_user_ctl() the check which returns -EBUSY at
beginning of the function if the control already exists is removed. This is not
a problem though since the check is quite useless, because the lock that is
protecting the control list is released between the check and before adding the
new control to the list, which means that it is possible that a different
control with the same settings is added to the list after the check. Luckily
there is another check that is done while holding the lock in snd_ctl_add(), so
we'll rely on that to make sure that the same control is not added twice.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189 | static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
if (replace) {
err = snd_ctl_remove_user_ctl(file, &info->id);
if (err)
return err;
}
if (card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->card = card;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
| 166,291 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput();
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get( "cl_motd", "1", 0 );
#endif
cl_timeout = Cvar_Get( "cl_timeout", "200", 0 );
cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get( "timedemo", "0", 0 );
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 );
cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 );
rconAddress = Cvar_Get( "rconAddress", "", 0 );
cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE );
cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE );
cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 );
cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE );
cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE );
cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE );
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 );
cl_allowDownload = Cvar_Get( "cl_allowDownload", "0", CVAR_ARCHIVE );
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE);
#endif
Cvar_Get( "cg_autoswitch", "2", CVAR_ARCHIVE );
Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE );
cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 );
cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 );
cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM );
m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE );
m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE );
m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE );
m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE );
m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE );
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000
Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "model", "bj2", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "password", "", CVAR_USERINFO );
Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cg_emptyswitch", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE );
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM );
cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM );
cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE );
cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 );
Cmd_AddCommand( "cmd", CL_ForwardToServer_f );
Cmd_AddCommand( "configstrings", CL_Configstrings_f );
Cmd_AddCommand( "clientinfo", CL_Clientinfo_f );
Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f );
Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f );
Cmd_AddCommand( "disconnect", CL_Disconnect_f );
Cmd_AddCommand( "record", CL_Record_f );
Cmd_AddCommand( "demo", CL_PlayDemo_f );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand( "cinematic", CL_PlayCinematic_f );
Cmd_AddCommand( "stoprecord", CL_StopRecord_f );
Cmd_AddCommand( "connect", CL_Connect_f );
Cmd_AddCommand( "reconnect", CL_Reconnect_f );
Cmd_AddCommand( "localservers", CL_LocalServers_f );
Cmd_AddCommand( "globalservers", CL_GlobalServers_f );
Cmd_AddCommand( "rcon", CL_Rcon_f );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand( "ping", CL_Ping_f );
Cmd_AddCommand( "serverstatus", CL_ServerStatus_f );
Cmd_AddCommand( "showip", CL_ShowIP_f );
Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f );
Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f );
Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f );
Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f );
Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f );
Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage );
Cmd_AddCommand( "updatescreen", SCR_UpdateScreen );
Cmd_AddCommand( "cld", CL_ClientDamageCommand );
Cmd_AddCommand( "startMultiplayer", CL_startMultiplayer_f ); // NERVE - SMF
Cmd_AddCommand( "shellExecute", CL_ShellExecute_URL_f );
Cmd_AddCommand( "map_restart", CL_MapRestart_f );
Cmd_AddCommand( "setRecommended", CL_SetRecommended_f );
CL_InitRef();
SCR_Init();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269 | void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput();
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get( "cl_motd", "1", 0 );
#endif
cl_timeout = Cvar_Get( "cl_timeout", "200", 0 );
cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get( "timedemo", "0", 0 );
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 );
cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 );
rconAddress = Cvar_Get( "rconAddress", "", 0 );
cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE );
cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE );
cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 );
cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE );
cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE );
cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE );
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 );
cl_allowDownload = Cvar_Get( "cl_allowDownload", "0", CVAR_ARCHIVE );
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);
#endif
Cvar_Get( "cg_autoswitch", "2", CVAR_ARCHIVE );
Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE );
cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 );
cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 );
cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM );
m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE );
m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE );
m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE );
m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE );
m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE );
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000
Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "model", "bj2", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "password", "", CVAR_USERINFO );
Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cg_emptyswitch", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE );
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM );
cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM );
cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE );
cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 );
Cmd_AddCommand( "cmd", CL_ForwardToServer_f );
Cmd_AddCommand( "configstrings", CL_Configstrings_f );
Cmd_AddCommand( "clientinfo", CL_Clientinfo_f );
Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f );
Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f );
Cmd_AddCommand( "disconnect", CL_Disconnect_f );
Cmd_AddCommand( "record", CL_Record_f );
Cmd_AddCommand( "demo", CL_PlayDemo_f );
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand( "cinematic", CL_PlayCinematic_f );
Cmd_AddCommand( "stoprecord", CL_StopRecord_f );
Cmd_AddCommand( "connect", CL_Connect_f );
Cmd_AddCommand( "reconnect", CL_Reconnect_f );
Cmd_AddCommand( "localservers", CL_LocalServers_f );
Cmd_AddCommand( "globalservers", CL_GlobalServers_f );
Cmd_AddCommand( "rcon", CL_Rcon_f );
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand( "ping", CL_Ping_f );
Cmd_AddCommand( "serverstatus", CL_ServerStatus_f );
Cmd_AddCommand( "showip", CL_ShowIP_f );
Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f );
Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f );
Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f );
Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f );
Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f );
Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage );
Cmd_AddCommand( "updatescreen", SCR_UpdateScreen );
Cmd_AddCommand( "cld", CL_ClientDamageCommand );
Cmd_AddCommand( "startMultiplayer", CL_startMultiplayer_f ); // NERVE - SMF
Cmd_AddCommand( "shellExecute", CL_ShellExecute_URL_f );
Cmd_AddCommand( "map_restart", CL_MapRestart_f );
Cmd_AddCommand( "setRecommended", CL_SetRecommended_f );
CL_InitRef();
SCR_Init();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
| 170,085 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font)
{
int code = 0;
font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42");
if (!font->font)
return gs_throw(gs_error_VMerror, "out of memory");
/* no shortage of things to initialize */
{
gs_font_type42 *p42 = (gs_font_type42*) font->font;
/* Common to all fonts: */
p42->next = 0;
p42->prev = 0;
p42->memory = ctx->memory;
p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */
p42->base = font->font; /* NB also set by gs_definefont later */
p42->is_resource = false;
gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory));
p42->id = gs_next_ids(ctx->memory, 1);
p42->client_data = font; /* that's us */
/* this is overwritten in grid_fit() */
gs_make_identity(&p42->FontMatrix);
gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */
p42->FontType = ft_TrueType;
p42->BitmapWidths = false;
p42->ExactSize = fbit_use_outlines;
p42->InBetweenSize = fbit_use_outlines;
p42->TransformedChar = fbit_use_outlines;
p42->WMode = 0;
p42->PaintType = 0;
p42->StrokeWidth = 0;
p42->is_cached = 0;
p42->procs.define_font = gs_no_define_font;
p42->procs.make_font = gs_no_make_font;
p42->procs.font_info = gs_type42_font_info;
p42->procs.same_font = gs_default_same_font;
p42->procs.encode_char = xps_true_callback_encode_char;
p42->procs.decode_glyph = xps_true_callback_decode_glyph;
p42->procs.enumerate_glyph = gs_type42_enumerate_glyph;
p42->procs.glyph_info = gs_type42_glyph_info;
p42->procs.glyph_outline = gs_type42_glyph_outline;
p42->procs.glyph_name = xps_true_callback_glyph_name;
p42->procs.init_fstack = gs_default_init_fstack;
p42->procs.next_char_glyph = gs_default_next_char_glyph;
p42->procs.build_char = xps_true_callback_build_char;
memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars));
xps_load_sfnt_name(font, (char*)p42->font_name.chars);
p42->font_name.size = strlen((char*)p42->font_name.chars);
memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars));
strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars);
p42->key_name.size = strlen((char*)p42->key_name.chars);
/* Base font specific: */
p42->FontBBox.p.x = 0;
p42->FontBBox.p.y = 0;
p42->FontBBox.q.x = 0;
p42->FontBBox.q.y = 0;
uid_set_UniqueID(&p42->UID, p42->id);
p42->encoding_index = ENCODING_INDEX_UNKNOWN;
p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1;
p42->FAPI = 0;
p42->FAPI_font_data = 0;
/* Type 42 specific: */
p42->data.string_proc = xps_true_callback_string_proc;
p42->data.proc_data = font;
gs_type42_font_init(p42, font->subfontid);
p42->data.get_glyph_index = xps_true_get_glyph_index;
}
if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) {
return(code);
}
code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length);
return code;
}
Commit Message:
CWE ID: CWE-119 | xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font)
{
int code = 0;
font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42");
if (!font->font)
return gs_throw(gs_error_VMerror, "out of memory");
/* no shortage of things to initialize */
{
gs_font_type42 *p42 = (gs_font_type42*) font->font;
/* Common to all fonts: */
p42->next = 0;
p42->prev = 0;
p42->memory = ctx->memory;
p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */
p42->base = font->font; /* NB also set by gs_definefont later */
p42->is_resource = false;
gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory));
p42->id = gs_next_ids(ctx->memory, 1);
p42->client_data = font; /* that's us */
/* this is overwritten in grid_fit() */
gs_make_identity(&p42->FontMatrix);
gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */
p42->FontType = ft_TrueType;
p42->BitmapWidths = false;
p42->ExactSize = fbit_use_outlines;
p42->InBetweenSize = fbit_use_outlines;
p42->TransformedChar = fbit_use_outlines;
p42->WMode = 0;
p42->PaintType = 0;
p42->StrokeWidth = 0;
p42->is_cached = 0;
p42->procs.define_font = gs_no_define_font;
p42->procs.make_font = gs_no_make_font;
p42->procs.font_info = gs_type42_font_info;
p42->procs.same_font = gs_default_same_font;
p42->procs.encode_char = xps_true_callback_encode_char;
p42->procs.decode_glyph = xps_true_callback_decode_glyph;
p42->procs.enumerate_glyph = gs_type42_enumerate_glyph;
p42->procs.glyph_info = gs_type42_glyph_info;
p42->procs.glyph_outline = gs_type42_glyph_outline;
p42->procs.glyph_name = xps_true_callback_glyph_name;
p42->procs.init_fstack = gs_default_init_fstack;
p42->procs.next_char_glyph = gs_default_next_char_glyph;
p42->procs.build_char = xps_true_callback_build_char;
memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars));
xps_load_sfnt_name(font, (char*)p42->font_name.chars, sizeof(p42->font_name.chars));
p42->font_name.size = strlen((char*)p42->font_name.chars);
memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars));
strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars);
p42->key_name.size = strlen((char*)p42->key_name.chars);
/* Base font specific: */
p42->FontBBox.p.x = 0;
p42->FontBBox.p.y = 0;
p42->FontBBox.q.x = 0;
p42->FontBBox.q.y = 0;
uid_set_UniqueID(&p42->UID, p42->id);
p42->encoding_index = ENCODING_INDEX_UNKNOWN;
p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1;
p42->FAPI = 0;
p42->FAPI_font_data = 0;
/* Type 42 specific: */
p42->data.string_proc = xps_true_callback_string_proc;
p42->data.proc_data = font;
gs_type42_font_init(p42, font->subfontid);
p42->data.get_glyph_index = xps_true_get_glyph_index;
}
if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) {
return(code);
}
code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length);
return code;
}
| 164,786 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
char *line, int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec;
guint pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
guint8 *pd;
int i, hex_lines, n, caplen = 0;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return FALSE;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return FALSE;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
Commit Message: Don't treat the packet length as unsigned.
The scanf family of functions are as annoyingly bad at handling unsigned
numbers as strtoul() is - both of them are perfectly willing to accept a
value beginning with a negative sign as an unsigned value. When using
strtoul(), you can compensate for this by explicitly checking for a '-'
as the first character of the string, but you can't do that with
sscanf().
So revert to having pkt_len be signed, and scanning it with %d, but
check for a negative value and fail if we see a negative value.
Bug: 12395
Change-Id: I43b458a73b0934e9a5c2c89d34eac5a8f21a7455
Reviewed-on: https://code.wireshark.org/review/15223
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-119 | parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
char *line, int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec, pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
guint8 *pd;
int i, hex_lines, n, caplen = 0;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return FALSE;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return FALSE;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
if (pkt_len < 0) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: packet header has a negative packet length");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
| 167,150 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t map_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos,
int cap_setid,
struct uid_gid_map *map,
struct uid_gid_map *parent_map)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct uid_gid_map new_map;
unsigned idx;
struct uid_gid_extent extent;
char *kbuf = NULL, *pos, *next_line;
ssize_t ret;
/* Only allow < page size writes at the beginning of the file */
if ((*ppos != 0) || (count >= PAGE_SIZE))
return -EINVAL;
/* Slurp in the user data */
kbuf = memdup_user_nul(buf, count);
if (IS_ERR(kbuf))
return PTR_ERR(kbuf);
/*
* The userns_state_mutex serializes all writes to any given map.
*
* Any map is only ever written once.
*
* An id map fits within 1 cache line on most architectures.
*
* On read nothing needs to be done unless you are on an
* architecture with a crazy cache coherency model like alpha.
*
* There is a one time data dependency between reading the
* count of the extents and the values of the extents. The
* desired behavior is to see the values of the extents that
* were written before the count of the extents.
*
* To achieve this smp_wmb() is used on guarantee the write
* order and smp_rmb() is guaranteed that we don't have crazy
* architectures returning stale data.
*/
mutex_lock(&userns_state_mutex);
memset(&new_map, 0, sizeof(struct uid_gid_map));
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
goto out;
/*
* Adjusting namespace settings requires capabilities on the target.
*/
if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN))
goto out;
/* Parse the user data */
ret = -EINVAL;
pos = kbuf;
for (; pos; pos = next_line) {
/* Find the end of line and ensure I don't look past it */
next_line = strchr(pos, '\n');
if (next_line) {
*next_line = '\0';
next_line++;
if (*next_line == '\0')
next_line = NULL;
}
pos = skip_spaces(pos);
extent.first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent.lower_first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent.count = simple_strtoul(pos, &pos, 10);
if (*pos && !isspace(*pos))
goto out;
/* Verify there is not trailing junk on the line */
pos = skip_spaces(pos);
if (*pos != '\0')
goto out;
/* Verify we have been given valid starting values */
if ((extent.first == (u32) -1) ||
(extent.lower_first == (u32) -1))
goto out;
/* Verify count is not zero and does not cause the
* extent to wrap
*/
if ((extent.first + extent.count) <= extent.first)
goto out;
if ((extent.lower_first + extent.count) <=
extent.lower_first)
goto out;
/* Do the ranges in extent overlap any previous extents? */
if (mappings_overlap(&new_map, &extent))
goto out;
if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
(next_line != NULL))
goto out;
ret = insert_extent(&new_map, &extent);
if (ret < 0)
goto out;
ret = -EINVAL;
}
/* Be very certaint the new map actually exists */
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
/* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
goto out;
ret = sort_idmaps(&new_map);
if (ret < 0)
goto out;
ret = -EPERM;
/* Map the lower ids from the parent user namespace to the
* kernel global id space.
*/
for (idx = 0; idx < new_map.nr_extents; idx++) {
struct uid_gid_extent *e;
u32 lower_first;
if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
e = &new_map.extent[idx];
else
e = &new_map.forward[idx];
lower_first = map_id_range_down(parent_map,
e->lower_first,
e->count);
/* Fail if we can not map the specified extent to
* the kernel global id space.
*/
if (lower_first == (u32) -1)
goto out;
e->lower_first = lower_first;
}
/* Install the map */
if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
memcpy(map->extent, new_map.extent,
new_map.nr_extents * sizeof(new_map.extent[0]));
} else {
map->forward = new_map.forward;
map->reverse = new_map.reverse;
}
smp_wmb();
map->nr_extents = new_map.nr_extents;
*ppos = count;
ret = count;
out:
if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
kfree(new_map.forward);
kfree(new_map.reverse);
map->forward = NULL;
map->reverse = NULL;
map->nr_extents = 0;
}
mutex_unlock(&userns_state_mutex);
kfree(kbuf);
return ret;
}
Commit Message: userns: also map extents in the reverse map to kernel IDs
The current logic first clones the extent array and sorts both copies, then
maps the lower IDs of the forward mapping into the lower namespace, but
doesn't map the lower IDs of the reverse mapping.
This means that code in a nested user namespace with >5 extents will see
incorrect IDs. It also breaks some access checks, like
inode_owner_or_capable() and privileged_wrt_inode_uidgid(), so a process
can incorrectly appear to be capable relative to an inode.
To fix it, we have to make sure that the "lower_first" members of extents
in both arrays are translated; and we have to make sure that the reverse
map is sorted *after* the translation (since otherwise the translation can
break the sorting).
This is CVE-2018-18955.
Fixes: 6397fac4915a ("userns: bump idmap limits to 340")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Tested-by: Eric W. Biederman <[email protected]>
Reviewed-by: Eric W. Biederman <[email protected]>
Signed-off-by: Eric W. Biederman <[email protected]>
CWE ID: CWE-20 | static ssize_t map_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos,
int cap_setid,
struct uid_gid_map *map,
struct uid_gid_map *parent_map)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct uid_gid_map new_map;
unsigned idx;
struct uid_gid_extent extent;
char *kbuf = NULL, *pos, *next_line;
ssize_t ret;
/* Only allow < page size writes at the beginning of the file */
if ((*ppos != 0) || (count >= PAGE_SIZE))
return -EINVAL;
/* Slurp in the user data */
kbuf = memdup_user_nul(buf, count);
if (IS_ERR(kbuf))
return PTR_ERR(kbuf);
/*
* The userns_state_mutex serializes all writes to any given map.
*
* Any map is only ever written once.
*
* An id map fits within 1 cache line on most architectures.
*
* On read nothing needs to be done unless you are on an
* architecture with a crazy cache coherency model like alpha.
*
* There is a one time data dependency between reading the
* count of the extents and the values of the extents. The
* desired behavior is to see the values of the extents that
* were written before the count of the extents.
*
* To achieve this smp_wmb() is used on guarantee the write
* order and smp_rmb() is guaranteed that we don't have crazy
* architectures returning stale data.
*/
mutex_lock(&userns_state_mutex);
memset(&new_map, 0, sizeof(struct uid_gid_map));
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
goto out;
/*
* Adjusting namespace settings requires capabilities on the target.
*/
if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN))
goto out;
/* Parse the user data */
ret = -EINVAL;
pos = kbuf;
for (; pos; pos = next_line) {
/* Find the end of line and ensure I don't look past it */
next_line = strchr(pos, '\n');
if (next_line) {
*next_line = '\0';
next_line++;
if (*next_line == '\0')
next_line = NULL;
}
pos = skip_spaces(pos);
extent.first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent.lower_first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent.count = simple_strtoul(pos, &pos, 10);
if (*pos && !isspace(*pos))
goto out;
/* Verify there is not trailing junk on the line */
pos = skip_spaces(pos);
if (*pos != '\0')
goto out;
/* Verify we have been given valid starting values */
if ((extent.first == (u32) -1) ||
(extent.lower_first == (u32) -1))
goto out;
/* Verify count is not zero and does not cause the
* extent to wrap
*/
if ((extent.first + extent.count) <= extent.first)
goto out;
if ((extent.lower_first + extent.count) <=
extent.lower_first)
goto out;
/* Do the ranges in extent overlap any previous extents? */
if (mappings_overlap(&new_map, &extent))
goto out;
if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
(next_line != NULL))
goto out;
ret = insert_extent(&new_map, &extent);
if (ret < 0)
goto out;
ret = -EINVAL;
}
/* Be very certaint the new map actually exists */
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
/* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
goto out;
ret = -EPERM;
/* Map the lower ids from the parent user namespace to the
* kernel global id space.
*/
for (idx = 0; idx < new_map.nr_extents; idx++) {
struct uid_gid_extent *e;
u32 lower_first;
if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
e = &new_map.extent[idx];
else
e = &new_map.forward[idx];
lower_first = map_id_range_down(parent_map,
e->lower_first,
e->count);
/* Fail if we can not map the specified extent to
* the kernel global id space.
*/
if (lower_first == (u32) -1)
goto out;
e->lower_first = lower_first;
}
/*
* If we want to use binary search for lookup, this clones the extent
* array and sorts both copies.
*/
ret = sort_idmaps(&new_map);
if (ret < 0)
goto out;
/* Install the map */
if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
memcpy(map->extent, new_map.extent,
new_map.nr_extents * sizeof(new_map.extent[0]));
} else {
map->forward = new_map.forward;
map->reverse = new_map.reverse;
}
smp_wmb();
map->nr_extents = new_map.nr_extents;
*ppos = count;
ret = count;
out:
if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
kfree(new_map.forward);
kfree(new_map.reverse);
map->forward = NULL;
map->reverse = NULL;
map->nr_extents = 0;
}
mutex_unlock(&userns_state_mutex);
kfree(kbuf);
return ret;
}
| 168,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
const CompressionType compression,ExceptionInfo *exception)
{
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
ssize_t
y;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1451
CWE ID: CWE-399 | static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
const CompressionType compression,ExceptionInfo *exception)
{
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
ssize_t
y;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
| 169,729 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (mode != R_CORE_BIN_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
if (r->io->va && entry->paddr == entry->vaddr) {
RIOMap *map = r_io_map_get (r->io, entry->vaddr);
if (map) {
paddr = entry->vaddr - map->itv.addr + map->delta;
}
}
}
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry%i.preinit", i);
} else {
name = r_str_newf ("entry%i", i);
}
r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at);
r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr);
r_cons_printf ("s %s\n", name);
free (name);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923)
CWE ID: CWE-125 | static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
if (r_list_length (entries) > 1024) {
eprintf ("Too many entrypoints (%d)\n", r_list_length (entries));
return false;
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (mode != R_CORE_BIN_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
if (r->io->va && entry->paddr == entry->vaddr) {
RIOMap *map = r_io_map_get (r->io, entry->vaddr);
if (map) {
paddr = entry->vaddr - map->itv.addr + map->delta;
}
}
}
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry%i.preinit", i);
} else {
name = r_str_newf ("entry%i", i);
}
r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at);
r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr);
r_cons_printf ("s %s\n", name);
free (name);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
| 169,233 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer,
const char *tags, const char *message, int strip_colors,
t_hook_callback_print *callback, void *callback_data)
{
struct t_hook *new_hook;
struct t_hook_print *new_hook_print;
if (!callback)
return NULL;
new_hook = malloc (sizeof (*new_hook));
if (!new_hook)
return NULL;
new_hook_print = malloc (sizeof (*new_hook_print));
if (!new_hook_print)
{
rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb))
(ptr_hook->callback_data, tls_session, req_ca, nreq,
pk_algos, pk_algos_len, answer);
break;
}
ptr_hook = ptr_hook->next_hook;
new_hook->hook_data = new_hook_print;
new_hook_print->callback = callback;
new_hook_print->buffer = buffer;
if (tags)
{
new_hook_print->tags_array = string_split (tags, ",", 0, 0,
&new_hook_print->tags_count);
}
else
{
new_hook_print->tags_count = 0;
new_hook_print->tags_array = NULL;
}
new_hook_print->message = (message) ? strdup (message) : NULL;
new_hook_print->strip_colors = strip_colors;
hook_add_to_list (new_hook);
return new_hook;
}
Commit Message:
CWE ID: CWE-20 | hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer,
const char *tags, const char *message, int strip_colors,
t_hook_callback_print *callback, void *callback_data)
{
struct t_hook *new_hook;
struct t_hook_print *new_hook_print;
if (!callback)
return NULL;
new_hook = malloc (sizeof (*new_hook));
if (!new_hook)
return NULL;
new_hook_print = malloc (sizeof (*new_hook_print));
if (!new_hook_print)
{
rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb))
(ptr_hook->callback_data, tls_session, req_ca, nreq,
pk_algos, pk_algos_len, answer,
WEECHAT_HOOK_CONNECT_GNUTLS_CB_SET_CERT);
break;
}
ptr_hook = ptr_hook->next_hook;
new_hook->hook_data = new_hook_print;
new_hook_print->callback = callback;
new_hook_print->buffer = buffer;
if (tags)
{
new_hook_print->tags_array = string_split (tags, ",", 0, 0,
&new_hook_print->tags_count);
}
else
{
new_hook_print->tags_count = 0;
new_hook_print->tags_array = NULL;
}
new_hook_print->message = (message) ? strdup (message) : NULL;
new_hook_print->strip_colors = strip_colors;
hook_add_to_list (new_hook);
return new_hook;
}
| 164,711 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed a bug in the packet iterator code.
Added a new regression test case.
CWE ID: CWE-125 | static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
if (pirlvl->prcwidthexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
| 170,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> convert5Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.convert5");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(e*, , V8e::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8e::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->convert5();
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> convert5Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.convert5");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(e*, , V8e::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8e::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->convert5();
return v8::Handle<v8::Value>();
}
| 171,081 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
{
mainprog_info *mainprog_ptr;
/* retrieve the pointer to our special-purpose struct */
mainprog_ptr = png_get_progressive_ptr(png_ptr);
/* let the main program know that it should flush any buffered image
* data to the display now and set a "done" flag or whatever, but note
* that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
* NOT call readpng2_cleanup() either here or in the finish_display()
* routine; wait until control returns to the main program via
* readpng2_decode_data() */
(*mainprog_ptr->mainprog_finish_display)();
/* all done */
return;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
{
mainprog_info *mainprog_ptr;
/* retrieve the pointer to our special-purpose struct */
mainprog_ptr = png_get_progressive_ptr(png_ptr);
/* let the main program know that it should flush any buffered image
* data to the display now and set a "done" flag or whatever, but note
* that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
* NOT call readpng2_cleanup() either here or in the finish_display()
* routine; wait until control returns to the main program via
* readpng2_decode_data() */
(*mainprog_ptr->mainprog_finish_display)();
/* all done */
(void)info_ptr; /* Unused */
return;
}
| 173,568 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE) {
return -1;
}
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
uint32_t len2 = off + len - 4096;
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
Commit Message:
CWE ID: CWE-20 | static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp, xfers = 0;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE) {
return -1;
}
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
uint32_t len2 = off + len - 4096;
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
xfers++;
}
}
return xfers ? 0 : -1;
}
| 165,279 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ExtensionTtsSpeakFunction::RunImpl() {
std::string text;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text));
DictionaryValue* options = NULL;
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &options));
Task* completion_task = NewRunnableMethod(
this, &ExtensionTtsSpeakFunction::SpeechFinished);
utterance_ = new Utterance(profile(), text, options, completion_task);
AddRef(); // Balanced in SpeechFinished().
ExtensionTtsController::GetInstance()->SpeakOrEnqueue(utterance_);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ExtensionTtsSpeakFunction::RunImpl() {
int src_id = -1;
EXTENSION_FUNCTION_VALIDATE(
options->GetInteger(constants::kSrcIdKey, &src_id));
// If we got this far, the arguments were all in the valid format, so
// send the success response to the callback now - this ensures that
// the callback response always arrives before events, which makes
// the behavior more predictable and easier to write unit tests for too.
SendResponse(true);
UtteranceContinuousParameters continuous_params;
continuous_params.rate = rate;
continuous_params.pitch = pitch;
continuous_params.volume = volume;
Utterance* utterance = new Utterance(profile());
utterance->set_text(text);
utterance->set_voice_name(voice_name);
utterance->set_src_extension_id(extension_id());
utterance->set_src_id(src_id);
utterance->set_src_url(source_url());
utterance->set_lang(lang);
utterance->set_gender(gender);
utterance->set_continuous_parameters(continuous_params);
utterance->set_can_enqueue(can_enqueue);
utterance->set_required_event_types(required_event_types);
utterance->set_desired_event_types(desired_event_types);
utterance->set_extension_id(voice_extension_id);
utterance->set_options(options.get());
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
controller->SpeakOrEnqueue(utterance);
return true;
}
| 170,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sk_buff **gre_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct sk_buff *p;
const struct gre_base_hdr *greh;
unsigned int hlen, grehlen;
unsigned int off;
int flush = 1;
struct packet_offload *ptype;
__be16 type;
off = skb_gro_offset(skb);
hlen = off + sizeof(*greh);
greh = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out;
}
/* Only support version 0 and K (key), C (csum) flags. Note that
* although the support for the S (seq#) flag can be added easily
* for GRO, this is problematic for GSO hence can not be enabled
* here because a GRO pkt may end up in the forwarding path, thus
* requiring GSO support to break it up correctly.
*/
if ((greh->flags & ~(GRE_KEY|GRE_CSUM)) != 0)
goto out;
type = greh->protocol;
rcu_read_lock();
ptype = gro_find_receive_by_type(type);
if (!ptype)
goto out_unlock;
grehlen = GRE_HEADER_SECTION;
if (greh->flags & GRE_KEY)
grehlen += GRE_HEADER_SECTION;
if (greh->flags & GRE_CSUM)
grehlen += GRE_HEADER_SECTION;
hlen = off + grehlen;
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out_unlock;
}
/* Don't bother verifying checksum if we're going to flush anyway. */
if ((greh->flags & GRE_CSUM) && !NAPI_GRO_CB(skb)->flush) {
if (skb_gro_checksum_simple_validate(skb))
goto out_unlock;
skb_gro_checksum_try_convert(skb, IPPROTO_GRE, 0,
null_compute_pseudo);
}
for (p = *head; p; p = p->next) {
const struct gre_base_hdr *greh2;
if (!NAPI_GRO_CB(p)->same_flow)
continue;
/* The following checks are needed to ensure only pkts
* from the same tunnel are considered for aggregation.
* The criteria for "the same tunnel" includes:
* 1) same version (we only support version 0 here)
* 2) same protocol (we only support ETH_P_IP for now)
* 3) same set of flags
* 4) same key if the key field is present.
*/
greh2 = (struct gre_base_hdr *)(p->data + off);
if (greh2->flags != greh->flags ||
greh2->protocol != greh->protocol) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
if (greh->flags & GRE_KEY) {
/* compare keys */
if (*(__be32 *)(greh2+1) != *(__be32 *)(greh+1)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
}
skb_gro_pull(skb, grehlen);
/* Adjusted NAPI_GRO_CB(skb)->csum after skb_gro_pull()*/
skb_gro_postpull_rcsum(skb, greh, grehlen);
pp = ptype->callbacks.gro_receive(head, skb);
flush = 0;
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation.
When drivers express support for TSO of encapsulated packets, they
only mean that they can do it for one layer of encapsulation.
Supporting additional levels would mean updating, at a minimum,
more IP length fields and they are unaware of this.
No encapsulation device expresses support for handling offloaded
encapsulated packets, so we won't generate these types of frames
in the transmit path. However, GRO doesn't have a check for
multiple levels of encapsulation and will attempt to build them.
UDP tunnel GRO actually does prevent this situation but it only
handles multiple UDP tunnels stacked on top of each other. This
generalizes that solution to prevent any kind of tunnel stacking
that would cause problems.
Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack")
Signed-off-by: Jesse Gross <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-400 | static struct sk_buff **gre_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct sk_buff *p;
const struct gre_base_hdr *greh;
unsigned int hlen, grehlen;
unsigned int off;
int flush = 1;
struct packet_offload *ptype;
__be16 type;
if (NAPI_GRO_CB(skb)->encap_mark)
goto out;
NAPI_GRO_CB(skb)->encap_mark = 1;
off = skb_gro_offset(skb);
hlen = off + sizeof(*greh);
greh = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out;
}
/* Only support version 0 and K (key), C (csum) flags. Note that
* although the support for the S (seq#) flag can be added easily
* for GRO, this is problematic for GSO hence can not be enabled
* here because a GRO pkt may end up in the forwarding path, thus
* requiring GSO support to break it up correctly.
*/
if ((greh->flags & ~(GRE_KEY|GRE_CSUM)) != 0)
goto out;
type = greh->protocol;
rcu_read_lock();
ptype = gro_find_receive_by_type(type);
if (!ptype)
goto out_unlock;
grehlen = GRE_HEADER_SECTION;
if (greh->flags & GRE_KEY)
grehlen += GRE_HEADER_SECTION;
if (greh->flags & GRE_CSUM)
grehlen += GRE_HEADER_SECTION;
hlen = off + grehlen;
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out_unlock;
}
/* Don't bother verifying checksum if we're going to flush anyway. */
if ((greh->flags & GRE_CSUM) && !NAPI_GRO_CB(skb)->flush) {
if (skb_gro_checksum_simple_validate(skb))
goto out_unlock;
skb_gro_checksum_try_convert(skb, IPPROTO_GRE, 0,
null_compute_pseudo);
}
for (p = *head; p; p = p->next) {
const struct gre_base_hdr *greh2;
if (!NAPI_GRO_CB(p)->same_flow)
continue;
/* The following checks are needed to ensure only pkts
* from the same tunnel are considered for aggregation.
* The criteria for "the same tunnel" includes:
* 1) same version (we only support version 0 here)
* 2) same protocol (we only support ETH_P_IP for now)
* 3) same set of flags
* 4) same key if the key field is present.
*/
greh2 = (struct gre_base_hdr *)(p->data + off);
if (greh2->flags != greh->flags ||
greh2->protocol != greh->protocol) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
if (greh->flags & GRE_KEY) {
/* compare keys */
if (*(__be32 *)(greh2+1) != *(__be32 *)(greh+1)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
}
skb_gro_pull(skb, grehlen);
/* Adjusted NAPI_GRO_CB(skb)->csum after skb_gro_pull()*/
skb_gro_postpull_rcsum(skb, greh, grehlen);
pp = ptype->callbacks.gro_receive(head, skb);
flush = 0;
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
| 166,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
| 171,688 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppShortcutManager::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSIONS_READY: {
OnceOffCreateShortcuts();
break;
}
case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: {
#if defined(OS_MACOSX)
if (!apps::IsAppShimsEnabled())
break;
#endif // defined(OS_MACOSX)
const extensions::InstalledExtensionInfo* installed_info =
content::Details<const extensions::InstalledExtensionInfo>(details)
.ptr();
const Extension* extension = installed_info->extension;
if (installed_info->is_update) {
web_app::UpdateAllShortcuts(
base::UTF8ToUTF16(installed_info->old_name), profile_, extension);
} else if (ShouldCreateShortcutFor(profile_, extension)) {
CreateShortcutsInApplicationsMenu(profile_, extension);
}
break;
}
case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: {
const Extension* extension = content::Details<const Extension>(
details).ptr();
web_app::DeleteAllShortcuts(profile_, extension);
break;
}
default:
NOTREACHED();
}
}
Commit Message: Remove --disable-app-shims.
App shims have been enabled by default for 3 milestones
(since r242711).
BUG=350161
Review URL: https://codereview.chromium.org/298953002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AppShortcutManager::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSIONS_READY: {
OnceOffCreateShortcuts();
break;
}
case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: {
const extensions::InstalledExtensionInfo* installed_info =
content::Details<const extensions::InstalledExtensionInfo>(details)
.ptr();
const Extension* extension = installed_info->extension;
if (installed_info->is_update) {
web_app::UpdateAllShortcuts(
base::UTF8ToUTF16(installed_info->old_name), profile_, extension);
} else if (ShouldCreateShortcutFor(profile_, extension)) {
CreateShortcutsInApplicationsMenu(profile_, extension);
}
break;
}
case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: {
const Extension* extension = content::Details<const Extension>(
details).ptr();
web_app::DeleteAllShortcuts(profile_, extension);
break;
}
default:
NOTREACHED();
}
}
| 171,145 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int newary(struct ipc_namespace *ns, struct ipc_params *params)
{
int id;
int retval;
struct sem_array *sma;
int size;
key_t key = params->key;
int nsems = params->u.nsems;
int semflg = params->flg;
int i;
if (!nsems)
return -EINVAL;
if (ns->used_sems + nsems > ns->sc_semmns)
return -ENOSPC;
size = sizeof (*sma) + nsems * sizeof (struct sem);
sma = ipc_rcu_alloc(size);
if (!sma) {
return -ENOMEM;
}
memset (sma, 0, size);
sma->sem_perm.mode = (semflg & S_IRWXUGO);
sma->sem_perm.key = key;
sma->sem_perm.security = NULL;
retval = security_sem_alloc(sma);
if (retval) {
ipc_rcu_putref(sma);
return retval;
}
id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
if (id < 0) {
security_sem_free(sma);
ipc_rcu_putref(sma);
return id;
}
ns->used_sems += nsems;
sma->sem_base = (struct sem *) &sma[1];
for (i = 0; i < nsems; i++)
INIT_LIST_HEAD(&sma->sem_base[i].sem_pending);
sma->complex_count = 0;
INIT_LIST_HEAD(&sma->sem_pending);
INIT_LIST_HEAD(&sma->list_id);
sma->sem_nsems = nsems;
sma->sem_ctime = get_seconds();
sem_unlock(sma);
return sma->sem_perm.id;
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static int newary(struct ipc_namespace *ns, struct ipc_params *params)
{
int id;
int retval;
struct sem_array *sma;
int size;
key_t key = params->key;
int nsems = params->u.nsems;
int semflg = params->flg;
int i;
if (!nsems)
return -EINVAL;
if (ns->used_sems + nsems > ns->sc_semmns)
return -ENOSPC;
size = sizeof (*sma) + nsems * sizeof (struct sem);
sma = ipc_rcu_alloc(size);
if (!sma) {
return -ENOMEM;
}
memset (sma, 0, size);
sma->sem_perm.mode = (semflg & S_IRWXUGO);
sma->sem_perm.key = key;
sma->sem_perm.security = NULL;
retval = security_sem_alloc(sma);
if (retval) {
ipc_rcu_putref(sma);
return retval;
}
id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
if (id < 0) {
security_sem_free(sma);
ipc_rcu_putref(sma);
return id;
}
ns->used_sems += nsems;
sma->sem_base = (struct sem *) &sma[1];
for (i = 0; i < nsems; i++) {
INIT_LIST_HEAD(&sma->sem_base[i].sem_pending);
spin_lock_init(&sma->sem_base[i].lock);
}
sma->complex_count = 0;
INIT_LIST_HEAD(&sma->sem_pending);
INIT_LIST_HEAD(&sma->list_id);
sma->sem_nsems = nsems;
sma->sem_ctime = get_seconds();
sem_unlock(sma, -1);
return sma->sem_perm.id;
}
| 165,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
| 171,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
return FALSE;
}
if(flags & SOCK_THREAD_ADD_FD_SYNC)
{
if(ts[h].thread_id == pthread_self())
{
flags &= ~SOCK_THREAD_ADD_FD_SYNC;
add_poll(h, fd, type, flags, user_id);
return TRUE;
}
APPL_TRACE_DEBUG("THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async");
}
sock_cmd_t cmd = {CMD_ADD_FD, fd, type, flags, user_id};
APPL_TRACE_DEBUG("adding fd:%d, flags:0x%x", fd, flags);
return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
return FALSE;
}
if(flags & SOCK_THREAD_ADD_FD_SYNC)
{
if(ts[h].thread_id == pthread_self())
{
flags &= ~SOCK_THREAD_ADD_FD_SYNC;
add_poll(h, fd, type, flags, user_id);
return TRUE;
}
APPL_TRACE_DEBUG("THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async");
}
sock_cmd_t cmd = {CMD_ADD_FD, fd, type, flags, user_id};
APPL_TRACE_DEBUG("adding fd:%d, flags:0x%x", fd, flags);
return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd);
}
| 173,460 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(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 create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(0);
}
| 170,147 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: krb5_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
krb5_error_code code;
krb5_key key = NULL;
krb5_gss_ctx_id_t ctx;
int i;
OM_uint32 minor;
size_t prflen;
krb5_data t, ns;
unsigned char *p;
prf_out->length = 0;
prf_out->value = NULL;
t.length = 0;
t.data = NULL;
ns.length = 0;
ns.data = NULL;
ctx = (krb5_gss_ctx_id_t)context;
switch (prf_key) {
case GSS_C_PRF_KEY_FULL:
if (ctx->have_acceptor_subkey) {
key = ctx->acceptor_subkey;
break;
}
/* fallthrough */
case GSS_C_PRF_KEY_PARTIAL:
key = ctx->subkey;
break;
default:
code = EINVAL;
goto cleanup;
}
if (key == NULL) {
code = EINVAL;
goto cleanup;
}
if (desired_output_len == 0)
return GSS_S_COMPLETE;
prf_out->value = k5alloc(desired_output_len, &code);
if (prf_out->value == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
prf_out->length = desired_output_len;
code = krb5_c_prf_length(ctx->k5_context,
krb5_k_key_enctype(ctx->k5_context, key),
&prflen);
if (code != 0)
goto cleanup;
ns.length = 4 + prf_in->length;
ns.data = k5alloc(ns.length, &code);
if (ns.data == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
t.length = prflen;
t.data = k5alloc(t.length, &code);
if (t.data == NULL)
goto cleanup;
memcpy(ns.data + 4, prf_in->value, prf_in->length);
i = 0;
p = (unsigned char *)prf_out->value;
while (desired_output_len > 0) {
store_32_be(i, ns.data);
code = krb5_k_prf(ctx->k5_context, key, &ns, &t);
if (code != 0)
goto cleanup;
memcpy(p, t.data, MIN(t.length, desired_output_len));
p += t.length;
desired_output_len -= t.length;
i++;
}
cleanup:
if (code != 0)
gss_release_buffer(&minor, prf_out);
krb5_free_data_contents(ctx->k5_context, &ns);
krb5_free_data_contents(ctx->k5_context, &t);
*minor_status = (OM_uint32)code;
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | krb5_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
krb5_error_code code;
krb5_key key = NULL;
krb5_gss_ctx_id_t ctx;
int i;
OM_uint32 minor;
size_t prflen;
krb5_data t, ns;
unsigned char *p;
prf_out->length = 0;
prf_out->value = NULL;
t.length = 0;
t.data = NULL;
ns.length = 0;
ns.data = NULL;
ctx = (krb5_gss_ctx_id_t)context;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
switch (prf_key) {
case GSS_C_PRF_KEY_FULL:
if (ctx->have_acceptor_subkey) {
key = ctx->acceptor_subkey;
break;
}
/* fallthrough */
case GSS_C_PRF_KEY_PARTIAL:
key = ctx->subkey;
break;
default:
code = EINVAL;
goto cleanup;
}
if (key == NULL) {
code = EINVAL;
goto cleanup;
}
if (desired_output_len == 0)
return GSS_S_COMPLETE;
prf_out->value = k5alloc(desired_output_len, &code);
if (prf_out->value == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
prf_out->length = desired_output_len;
code = krb5_c_prf_length(ctx->k5_context,
krb5_k_key_enctype(ctx->k5_context, key),
&prflen);
if (code != 0)
goto cleanup;
ns.length = 4 + prf_in->length;
ns.data = k5alloc(ns.length, &code);
if (ns.data == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
t.length = prflen;
t.data = k5alloc(t.length, &code);
if (t.data == NULL)
goto cleanup;
memcpy(ns.data + 4, prf_in->value, prf_in->length);
i = 0;
p = (unsigned char *)prf_out->value;
while (desired_output_len > 0) {
store_32_be(i, ns.data);
code = krb5_k_prf(ctx->k5_context, key, &ns, &t);
if (code != 0)
goto cleanup;
memcpy(p, t.data, MIN(t.length, desired_output_len));
p += t.length;
desired_output_len -= t.length;
i++;
}
cleanup:
if (code != 0)
gss_release_buffer(&minor, prf_out);
krb5_free_data_contents(ctx->k5_context, &ns);
krb5_free_data_contents(ctx->k5_context, &t);
*minor_status = (OM_uint32)code;
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
| 166,822 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int getStrrtokenPos(char* str, int savedPos)
{
int result =-1;
int i;
for(i=savedPos-1; i>=0; i--) {
if(isIDSeparator(*(str+i)) ){
/* delimiter found; check for singleton */
if(i>=2 && isIDSeparator(*(str+i-2)) ){
/* a singleton; so send the position of token before the singleton */
result = i-2;
} else {
result = i;
}
break;
}
}
if(result < 1){
/* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */
result =-1;
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static int getStrrtokenPos(char* str, int savedPos)
{
int result =-1;
int i;
for(i=savedPos-1; i>=0; i--) {
if(isIDSeparator(*(str+i)) ){
/* delimiter found; check for singleton */
if(i>=2 && isIDSeparator(*(str+i-2)) ){
/* a singleton; so send the position of token before the singleton */
result = i-2;
} else {
result = i;
}
break;
}
}
if(result < 1){
/* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */
result =-1;
}
return result;
}
| 167,203 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PrintWebViewHelper::UpdatePrintSettings(
WebKit::WebFrame* frame, const WebKit::WebNode& node,
const DictionaryValue& passed_job_settings) {
DCHECK(is_preview_enabled_);
const DictionaryValue* job_settings = &passed_job_settings;
DictionaryValue modified_job_settings;
if (job_settings->empty()) {
if (!print_for_preview_)
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
bool source_is_html = true;
if (print_for_preview_) {
if (!job_settings->GetBoolean(printing::kSettingPreviewModifiable,
&source_is_html)) {
NOTREACHED();
}
} else {
source_is_html = !PrintingNodeOrPdfFrame(frame, node);
}
if (print_for_preview_ || !source_is_html) {
modified_job_settings.MergeDictionary(job_settings);
modified_job_settings.SetBoolean(printing::kSettingHeaderFooterEnabled,
false);
modified_job_settings.SetInteger(printing::kSettingMarginsType,
printing::NO_MARGINS);
job_settings = &modified_job_settings;
}
int cookie = print_pages_params_.get() ?
print_pages_params_->params.document_cookie : 0;
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_UpdatePrintSettings(routing_id(),
cookie, *job_settings, &settings));
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
if (!PrintMsg_Print_Params_IsValid(settings.params)) {
if (!print_for_preview_) {
print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
} else {
WebKit::WebFrame* print_frame = NULL;
GetPrintFrame(&print_frame);
if (print_frame) {
render_view()->RunModalAlertDialog(
print_frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
}
return false;
}
if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
return false;
}
if (!print_for_preview_) {
if (!job_settings->GetString(printing::kPreviewUIAddr,
&(settings.params.preview_ui_addr)) ||
!job_settings->GetInteger(printing::kPreviewRequestID,
&(settings.params.preview_request_id)) ||
!job_settings->GetBoolean(printing::kIsFirstRequest,
&(settings.params.is_first_request))) {
NOTREACHED();
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
UpdateFrameMarginsCssInfo(*job_settings);
settings.params.print_scaling_option = GetPrintScalingOption(
source_is_html, *job_settings, settings.params);
if (settings.params.display_header_footer) {
header_footer_info_.reset(new DictionaryValue());
header_footer_info_->SetString(printing::kSettingHeaderFooterDate,
settings.params.date);
header_footer_info_->SetString(printing::kSettingHeaderFooterURL,
settings.params.url);
header_footer_info_->SetString(printing::kSettingHeaderFooterTitle,
settings.params.title);
}
}
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
settings.params.document_cookie));
return true;
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | bool PrintWebViewHelper::UpdatePrintSettings(
WebKit::WebFrame* frame, const WebKit::WebNode& node,
const DictionaryValue& passed_job_settings) {
DCHECK(is_preview_enabled_);
const DictionaryValue* job_settings = &passed_job_settings;
DictionaryValue modified_job_settings;
if (job_settings->empty()) {
if (!print_for_preview_)
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
bool source_is_html = true;
if (print_for_preview_) {
if (!job_settings->GetBoolean(printing::kSettingPreviewModifiable,
&source_is_html)) {
NOTREACHED();
}
} else {
source_is_html = !PrintingNodeOrPdfFrame(frame, node);
}
if (print_for_preview_ || !source_is_html) {
modified_job_settings.MergeDictionary(job_settings);
modified_job_settings.SetBoolean(printing::kSettingHeaderFooterEnabled,
false);
modified_job_settings.SetInteger(printing::kSettingMarginsType,
printing::NO_MARGINS);
job_settings = &modified_job_settings;
}
int cookie = print_pages_params_.get() ?
print_pages_params_->params.document_cookie : 0;
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_UpdatePrintSettings(routing_id(),
cookie, *job_settings, &settings));
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
if (!PrintMsg_Print_Params_IsValid(settings.params)) {
if (!print_for_preview_) {
print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
} else {
WebKit::WebFrame* print_frame = NULL;
GetPrintFrame(&print_frame);
if (print_frame) {
render_view()->RunModalAlertDialog(
print_frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
}
return false;
}
if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
return false;
}
if (!print_for_preview_) {
if (!job_settings->GetInteger(printing::kPreviewUIID,
&(settings.params.preview_ui_id)) ||
!job_settings->GetInteger(printing::kPreviewRequestID,
&(settings.params.preview_request_id)) ||
!job_settings->GetBoolean(printing::kIsFirstRequest,
&(settings.params.is_first_request))) {
NOTREACHED();
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
UpdateFrameMarginsCssInfo(*job_settings);
settings.params.print_scaling_option = GetPrintScalingOption(
source_is_html, *job_settings, settings.params);
if (settings.params.display_header_footer) {
header_footer_info_.reset(new DictionaryValue());
header_footer_info_->SetString(printing::kSettingHeaderFooterDate,
settings.params.date);
header_footer_info_->SetString(printing::kSettingHeaderFooterURL,
settings.params.url);
header_footer_info_->SetString(printing::kSettingHeaderFooterTitle,
settings.params.title);
}
}
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
settings.params.document_cookie));
return true;
}
| 170,857 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: on_response(void *data, krb5_error_code retval, otp_response response)
{
struct request_state rs = *(struct request_state *)data;
free(data);
if (retval == 0 && response != otp_response_success)
retval = KRB5_PREAUTH_FAILED;
rs.respond(rs.arg, retval, NULL, NULL, NULL);
}
Commit Message: Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]
CWE ID: CWE-264 | on_response(void *data, krb5_error_code retval, otp_response response)
{
struct request_state rs = *(struct request_state *)data;
free(data);
if (retval == 0 && response != otp_response_success)
retval = KRB5_PREAUTH_FAILED;
if (retval == 0)
rs.enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
rs.respond(rs.arg, retval, NULL, NULL, NULL);
}
| 166,676 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int migrate_page_move_mapping(struct address_space *mapping,
struct page *newpage, struct page *page,
struct buffer_head *head, enum migrate_mode mode,
int extra_count)
{
int expected_count = 1 + extra_count;
void **pslot;
if (!mapping) {
/* Anonymous page without mapping */
if (page_count(page) != expected_count)
return -EAGAIN;
/* No turning back from here */
set_page_memcg(newpage, page_memcg(page));
newpage->index = page->index;
newpage->mapping = page->mapping;
if (PageSwapBacked(page))
SetPageSwapBacked(newpage);
return MIGRATEPAGE_SUCCESS;
}
spin_lock_irq(&mapping->tree_lock);
pslot = radix_tree_lookup_slot(&mapping->page_tree,
page_index(page));
expected_count += 1 + page_has_private(page);
if (page_count(page) != expected_count ||
radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
if (!page_freeze_refs(page, expected_count)) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
/*
* In the async migration case of moving a page with buffers, lock the
* buffers using trylock before the mapping is moved. If the mapping
* was moved, we later failed to lock the buffers and could not move
* the mapping back due to an elevated page count, we would have to
* block waiting on other references to be dropped.
*/
if (mode == MIGRATE_ASYNC && head &&
!buffer_migrate_lock_buffers(head, mode)) {
page_unfreeze_refs(page, expected_count);
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
/*
* Now we know that no one else is looking at the page:
* no turning back from here.
*/
set_page_memcg(newpage, page_memcg(page));
newpage->index = page->index;
newpage->mapping = page->mapping;
if (PageSwapBacked(page))
SetPageSwapBacked(newpage);
get_page(newpage); /* add cache reference */
if (PageSwapCache(page)) {
SetPageSwapCache(newpage);
set_page_private(newpage, page_private(page));
}
radix_tree_replace_slot(pslot, newpage);
/*
* Drop cache reference from old page by unfreezing
* to one less reference.
* We know this isn't the last reference.
*/
page_unfreeze_refs(page, expected_count - 1);
/*
* If moved to a different zone then also account
* the page for that zone. Other VM counters will be
* taken care of when we establish references to the
* new page and drop references to the old page.
*
* Note that anonymous pages are accounted for
* via NR_FILE_PAGES and NR_ANON_PAGES if they
* are mapped to swap space.
*/
__dec_zone_page_state(page, NR_FILE_PAGES);
__inc_zone_page_state(newpage, NR_FILE_PAGES);
if (!PageSwapCache(page) && PageSwapBacked(page)) {
__dec_zone_page_state(page, NR_SHMEM);
__inc_zone_page_state(newpage, NR_SHMEM);
}
spin_unlock_irq(&mapping->tree_lock);
return MIGRATEPAGE_SUCCESS;
}
Commit Message: mm: migrate dirty page without clear_page_dirty_for_io etc
clear_page_dirty_for_io() has accumulated writeback and memcg subtleties
since v2.6.16 first introduced page migration; and the set_page_dirty()
which completed its migration of PageDirty, later had to be moderated to
__set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too.
No actual problems seen with this procedure recently, but if you look into
what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually
achieving, it turns out to be nothing more than moving the PageDirty flag,
and its NR_FILE_DIRTY stat from one zone to another.
It would be good to avoid a pile of irrelevant decrementations and
incrementations, and improper event counting, and unnecessary descent of
the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which
radix_tree_replace_slot() left in place anyway).
Do the NR_FILE_DIRTY movement, like the other stats movements, while
interrupts still disabled in migrate_page_move_mapping(); and don't even
bother if the zone is the same. Do the PageDirty movement there under
tree_lock too, where old page is frozen and newpage not yet visible:
bearing in mind that as soon as newpage becomes visible in radix_tree, an
un-page-locked set_page_dirty() might interfere (or perhaps that's just
not possible: anything doing so should already hold an additional
reference to the old page, preventing its migration; but play safe).
But we do still need to transfer PageDirty in migrate_page_copy(), for
those who don't go the mapping route through migrate_page_move_mapping().
Signed-off-by: Hugh Dickins <[email protected]>
Cc: Christoph Lameter <[email protected]>
Cc: "Kirill A. Shutemov" <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Sasha Levin <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: KOSAKI Motohiro <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476 | int migrate_page_move_mapping(struct address_space *mapping,
struct page *newpage, struct page *page,
struct buffer_head *head, enum migrate_mode mode,
int extra_count)
{
struct zone *oldzone, *newzone;
int dirty;
int expected_count = 1 + extra_count;
void **pslot;
if (!mapping) {
/* Anonymous page without mapping */
if (page_count(page) != expected_count)
return -EAGAIN;
/* No turning back from here */
set_page_memcg(newpage, page_memcg(page));
newpage->index = page->index;
newpage->mapping = page->mapping;
if (PageSwapBacked(page))
SetPageSwapBacked(newpage);
return MIGRATEPAGE_SUCCESS;
}
oldzone = page_zone(page);
newzone = page_zone(newpage);
spin_lock_irq(&mapping->tree_lock);
pslot = radix_tree_lookup_slot(&mapping->page_tree,
page_index(page));
expected_count += 1 + page_has_private(page);
if (page_count(page) != expected_count ||
radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
if (!page_freeze_refs(page, expected_count)) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
/*
* In the async migration case of moving a page with buffers, lock the
* buffers using trylock before the mapping is moved. If the mapping
* was moved, we later failed to lock the buffers and could not move
* the mapping back due to an elevated page count, we would have to
* block waiting on other references to be dropped.
*/
if (mode == MIGRATE_ASYNC && head &&
!buffer_migrate_lock_buffers(head, mode)) {
page_unfreeze_refs(page, expected_count);
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
/*
* Now we know that no one else is looking at the page:
* no turning back from here.
*/
set_page_memcg(newpage, page_memcg(page));
newpage->index = page->index;
newpage->mapping = page->mapping;
if (PageSwapBacked(page))
SetPageSwapBacked(newpage);
get_page(newpage); /* add cache reference */
if (PageSwapCache(page)) {
SetPageSwapCache(newpage);
set_page_private(newpage, page_private(page));
}
/* Move dirty while page refs frozen and newpage not yet exposed */
dirty = PageDirty(page);
if (dirty) {
ClearPageDirty(page);
SetPageDirty(newpage);
}
radix_tree_replace_slot(pslot, newpage);
/*
* Drop cache reference from old page by unfreezing
* to one less reference.
* We know this isn't the last reference.
*/
page_unfreeze_refs(page, expected_count - 1);
spin_unlock(&mapping->tree_lock);
/* Leave irq disabled to prevent preemption while updating stats */
/*
* If moved to a different zone then also account
* the page for that zone. Other VM counters will be
* taken care of when we establish references to the
* new page and drop references to the old page.
*
* Note that anonymous pages are accounted for
* via NR_FILE_PAGES and NR_ANON_PAGES if they
* are mapped to swap space.
*/
if (newzone != oldzone) {
__dec_zone_state(oldzone, NR_FILE_PAGES);
__inc_zone_state(newzone, NR_FILE_PAGES);
if (PageSwapBacked(page) && !PageSwapCache(page)) {
__dec_zone_state(oldzone, NR_SHMEM);
__inc_zone_state(newzone, NR_SHMEM);
}
if (dirty && mapping_cap_account_dirty(mapping)) {
__dec_zone_state(oldzone, NR_FILE_DIRTY);
__inc_zone_state(newzone, NR_FILE_DIRTY);
}
}
local_irq_enable();
return MIGRATEPAGE_SUCCESS;
}
| 167,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line,
const std::wstring& switch_name) {
assert(!command_line.empty());
assert(!switch_name.empty());
std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line);
std::wstring switch_with_equal = L"--" + switch_name + L"=";
for (size_t i = 1; i < as_array.size(); ++i) {
const std::wstring& arg = as_array[i];
if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0)
return arg.substr(switch_with_equal.size());
}
return std::wstring();
}
Commit Message: Ignore switches following "--" when parsing a command line.
BUG=933004
[email protected]
Change-Id: I911be4cbfc38a4d41dec85d85f7fe0f50ddca392
Reviewed-on: https://chromium-review.googlesource.com/c/1481210
Auto-Submit: Greg Thompson <[email protected]>
Commit-Queue: Julian Pastarmov <[email protected]>
Reviewed-by: Julian Pastarmov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#634604}
CWE ID: CWE-77 | std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line,
const std::wstring& switch_name) {
static constexpr wchar_t kSwitchTerminator[] = L"--";
assert(!command_line.empty());
assert(!switch_name.empty());
std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line);
std::wstring switch_with_equal = L"--" + switch_name + L"=";
auto end = std::find(as_array.cbegin(), as_array.cend(), kSwitchTerminator);
for (auto scan = as_array.cbegin(); scan != end; ++scan) {
const std::wstring& arg = *scan;
if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0)
return arg.substr(switch_with_equal.size());
}
return std::wstring();
}
| 173,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(ctcptype);
Q_UNUSED(target);
if(!_ignoreListManager->ctcpMatch(prefix, network()->networkName())) {
QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix);
if(!param.isEmpty())
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
}
Commit Message:
CWE ID: CWE-399 | void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) {
Q_UNUSED(ctcptype);
Q_UNUSED(target);
Q_UNUSED(reply);
QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix);
if(!param.isEmpty())
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
| 164,876 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(dp->ip6f_offlg);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
Commit Message: CVE-2017-13031/Check for the presence of the entire IPv6 fragment header.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Clean up some whitespace in tests/TESTLIST while we're at it.
CWE ID: CWE-125 | frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(*dp);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
| 167,852 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NetworkHandler::SetNetworkConditions(
network::mojom::NetworkConditionsPtr conditions) {
if (!process_)
return;
StoragePartition* partition = process_->GetStoragePartition();
network::mojom::NetworkContext* context = partition->GetNetworkContext();
context->SetNetworkConditions(host_id_, std::move(conditions));
}
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::SetNetworkConditions(
network::mojom::NetworkConditionsPtr conditions) {
if (!storage_partition_)
return;
network::mojom::NetworkContext* context =
storage_partition_->GetNetworkContext();
context->SetNetworkConditions(host_id_, std::move(conditions));
}
| 172,762 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
int window_bits, png_uint_32 offset)
/* Initialize a zlib_control; the result is true/false */
{
CLEAR(*zlib);
zlib->idat = idat;
zlib->chunk = chunk;
zlib->file = chunk->file;
zlib->global = chunk->global;
zlib->rewrite_offset = offset; /* never changed for this zlib */
/* *_out does not need to be set: */
zlib->z.next_in = Z_NULL;
zlib->z.avail_in = 0;
zlib->z.zalloc = Z_NULL;
zlib->z.zfree = Z_NULL;
zlib->z.opaque = Z_NULL;
zlib->state = -1;
zlib->window_bits = window_bits;
zlib->compressed_digits = 0;
zlib->uncompressed_digits = 0;
/* These values are sticky across reset (in addition to the stuff in the
* first block, which is actually constant.)
*/
zlib->file_bits = 16;
zlib->ok_bits = 16; /* unset */
zlib->cksum = 0; /* set when a checksum error is detected */
/* '0' means use the header; inflateInit2 should always succeed because it
* does nothing apart from allocating the internal zstate.
*/
zlib->rc = inflateInit2(&zlib->z, 0);
if (zlib->rc != Z_OK)
{
zlib_message(zlib, 1/*unexpected*/);
return 0;
}
else
{
zlib->state = 0; /* initialized */
return 1;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
int window_bits, png_uint_32 offset)
/* Initialize a zlib_control; the result is true/false */
{
CLEAR(*zlib);
zlib->idat = idat;
zlib->chunk = chunk;
zlib->file = chunk->file;
zlib->global = chunk->global;
zlib->rewrite_offset = offset; /* never changed for this zlib */
/* *_out does not need to be set: */
zlib->z.next_in = Z_NULL;
zlib->z.avail_in = 0;
zlib->z.zalloc = Z_NULL;
zlib->z.zfree = Z_NULL;
zlib->z.opaque = Z_NULL;
zlib->state = -1;
zlib->window_bits = window_bits;
zlib->compressed_digits = 0;
zlib->uncompressed_digits = 0;
/* These values are sticky across reset (in addition to the stuff in the
* first block, which is actually constant.)
*/
zlib->file_bits = 24;
zlib->ok_bits = 16; /* unset */
zlib->cksum = 0; /* set when a checksum error is detected */
/* '0' means use the header; inflateInit2 should always succeed because it
* does nothing apart from allocating the internal zstate.
*/
zlib->rc = inflateInit2(&zlib->z, 0);
if (zlib->rc != Z_OK)
{
zlib_message(zlib, 1/*unexpected*/);
return 0;
}
else
{
zlib->state = 0; /* initialized */
return 1;
}
}
| 173,742 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) {
for (size_t i = 0; i < arraysize(kKeyboardOverlayMap); ++i) {
if (kKeyboardOverlayMap[i].input_method_id == input_method_id) {
return kKeyboardOverlayMap[i].keyboard_overlay_id;
}
}
return "";
}
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 | std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) {
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
return true;
}
| 170,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode image_clamping_mode,
ImageDecodingMode decode_mode) {
auto paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return;
auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode);
if (paint_image.decoding_mode() != paint_image_decoding_mode) {
paint_image = PaintImageBuilder::WithCopy(std::move(paint_image))
.set_decoding_mode(paint_image_decoding_mode)
.TakePaintImage();
}
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect,
image_clamping_mode, paint_image);
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void AcceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode image_clamping_mode,
ImageDecodingMode decode_mode) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return;
auto paint_image_decoding_mode = ToPaintImageDecodingMode(decode_mode);
if (paint_image.decoding_mode() != paint_image_decoding_mode) {
paint_image = PaintImageBuilder::WithCopy(std::move(paint_image))
.set_decoding_mode(paint_image_decoding_mode)
.TakePaintImage();
}
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect,
image_clamping_mode, paint_image);
}
| 172,594 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FileSystemManagerImpl::CreateWriter(const GURL& file_path,
CreateWriterCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
FileSystemURL url(context_->CrackURL(file_path));
base::Optional<base::File::Error> opt_error = ValidateFileSystemURL(url);
if (opt_error) {
std::move(callback).Run(opt_error.value(), nullptr);
return;
}
if (!security_policy_->CanWriteFileSystemFile(process_id_, url)) {
std::move(callback).Run(base::File::FILE_ERROR_SECURITY, nullptr);
return;
}
blink::mojom::FileWriterPtr writer;
mojo::MakeStrongBinding(std::make_unique<storage::FileWriterImpl>(
url, context_->CreateFileSystemOperationRunner(),
blob_storage_context_->context()->AsWeakPtr()),
MakeRequest(&writer));
std::move(callback).Run(base::File::FILE_OK, std::move(writer));
}
Commit Message: Disable FileSystemManager::CreateWriter if WritableFiles isn't enabled.
Bug: 922677
Change-Id: Ib16137cbabb2ec07f1ffc0484722f1d9cc533404
Reviewed-on: https://chromium-review.googlesource.com/c/1416570
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#623552}
CWE ID: CWE-189 | void FileSystemManagerImpl::CreateWriter(const GURL& file_path,
CreateWriterCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!base::FeatureList::IsEnabled(blink::features::kWritableFilesAPI)) {
bindings_.ReportBadMessage("FileSystemManager.CreateWriter");
return;
}
FileSystemURL url(context_->CrackURL(file_path));
base::Optional<base::File::Error> opt_error = ValidateFileSystemURL(url);
if (opt_error) {
std::move(callback).Run(opt_error.value(), nullptr);
return;
}
if (!security_policy_->CanWriteFileSystemFile(process_id_, url)) {
std::move(callback).Run(base::File::FILE_ERROR_SECURITY, nullptr);
return;
}
blink::mojom::FileWriterPtr writer;
mojo::MakeStrongBinding(std::make_unique<storage::FileWriterImpl>(
url, context_->CreateFileSystemOperationRunner(),
blob_storage_context_->context()->AsWeakPtr()),
MakeRequest(&writer));
std::move(callback).Run(base::File::FILE_OK, std::move(writer));
}
| 173,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20 | void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
#if defined(OS_MACOSX)
// On the Mac, the convention is to turn popups into new tabs when in
// fullscreen mode. Only worry about user-initiated fullscreen as showing a
// popup in HTML5 fullscreen would have kicked the page out of fullscreen.
if (disposition == WindowOpenDisposition::NEW_POPUP &&
exclusive_access_manager_->fullscreen_controller()
->IsFullscreenForBrowser()) {
disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
#endif
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
| 173,205 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
for (n = 0; n < hdesc->bNumDescriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
rdesc = kmalloc(rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
}
Commit Message: HID: usbhid: fix out-of-bounds bug
The hid descriptor identifies the length and type of subordinate
descriptors for a device. If the received hid descriptor is smaller than
the size of the struct hid_descriptor, it is possible to cause
out-of-bounds.
In addition, if bNumDescriptors of the hid descriptor have an incorrect
value, this can also cause out-of-bounds while approaching hdesc->desc[n].
So check the size of hid descriptor and bNumDescriptors.
BUG: KASAN: slab-out-of-bounds in usbhid_parse+0x9b1/0xa20
Read of size 1 at addr ffff88006c5f8edf by task kworker/1:2/1261
CPU: 1 PID: 1261 Comm: kworker/1:2 Not tainted
4.14.0-rc1-42251-gebb2c2437d80 #169
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
Workqueue: usb_hub_wq hub_event
Call Trace:
__dump_stack lib/dump_stack.c:16
dump_stack+0x292/0x395 lib/dump_stack.c:52
print_address_description+0x78/0x280 mm/kasan/report.c:252
kasan_report_error mm/kasan/report.c:351
kasan_report+0x22f/0x340 mm/kasan/report.c:409
__asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427
usbhid_parse+0x9b1/0xa20 drivers/hid/usbhid/hid-core.c:1004
hid_add_device+0x16b/0xb30 drivers/hid/hid-core.c:2944
usbhid_probe+0xc28/0x1100 drivers/hid/usbhid/hid-core.c:1369
usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932
generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174
usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457
hub_port_connect drivers/usb/core/hub.c:4903
hub_port_connect_change drivers/usb/core/hub.c:5009
port_event drivers/usb/core/hub.c:5115
hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195
process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119
worker_thread+0x221/0x1850 kernel/workqueue.c:2253
kthread+0x3a1/0x470 kernel/kthread.c:231
ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431
Cc: [email protected]
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Jaejoong Kim <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Acked-by: Alan Stern <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-125 | static int usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
int num_descriptors;
size_t offset = offsetof(struct hid_descriptor, desc);
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
if (hdesc->bLength < sizeof(struct hid_descriptor)) {
dbg_hid("hid descriptor is too short\n");
return -EINVAL;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
num_descriptors = min_t(int, hdesc->bNumDescriptors,
(hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));
for (n = 0; n < num_descriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
rdesc = kmalloc(rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
}
| 167,677 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t TrimTrailingSpaces ( char * firstChar, size_t origLen )
{
if ( origLen == 0 ) return 0;
char * lastChar = firstChar + origLen - 1;
if ( (*lastChar != ' ') && (*lastChar != 0) ) return origLen; // Nothing to do.
while ( (firstChar <= lastChar) && ((*lastChar == ' ') || (*lastChar == 0)) ) --lastChar;
XMP_Assert ( (lastChar == firstChar-1) ||
((lastChar >= firstChar) && (*lastChar != ' ') && (*lastChar != 0)) );
size_t newLen = (size_t)((lastChar+1) - firstChar);
XMP_Assert ( newLen <= origLen );
if ( newLen < origLen ) {
++lastChar;
*lastChar = 0;
}
return newLen;
} // TrimTrailingSpaces
Commit Message:
CWE ID: CWE-416 | static size_t TrimTrailingSpaces ( char * firstChar, size_t origLen )
{
if ( !firstChar || origLen == 0 ) return 0;
char * lastChar = firstChar + origLen - 1;
if ( (*lastChar != ' ') && (*lastChar != 0) ) return origLen; // Nothing to do.
while ( (firstChar <= lastChar) && ((*lastChar == ' ') || (*lastChar == 0)) ) --lastChar;
XMP_Assert ( (lastChar == firstChar-1) ||
((lastChar >= firstChar) && (*lastChar != ' ') && (*lastChar != 0)) );
size_t newLen = (size_t)((lastChar+1) - firstChar);
XMP_Assert ( newLen <= origLen );
if ( newLen < origLen ) {
++lastChar;
*lastChar = 0;
}
return newLen;
} // TrimTrailingSpaces
| 165,367 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PresentationConnectionProxy::DidChangeState(
content::PresentationConnectionState state) {
if (state == content::PRESENTATION_CONNECTION_STATE_CONNECTED) {
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Connected);
} else if (state == content::PRESENTATION_CONNECTION_STATE_CLOSED) {
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Closed);
} else {
NOTREACHED();
}
}
Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures
Add layout test.
1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead.
BUG=697719
Review-Url: https://codereview.chromium.org/2730123003
Cr-Commit-Position: refs/heads/master@{#455225}
CWE ID: | void PresentationConnectionProxy::DidChangeState(
content::PresentationConnectionState state) {
if (state == content::PRESENTATION_CONNECTION_STATE_CONNECTED) {
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Connected);
} else if (state == content::PRESENTATION_CONNECTION_STATE_CLOSED) {
source_connection_->didClose();
} else {
NOTREACHED();
}
}
| 172,044 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline bool is_exception(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-388 | static inline bool is_exception(u32 intr_info)
static inline bool is_nmi(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
}
| 166,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
int *len, int *strid, int read_packet) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE, startpos;
int ret;
recover:
startpos = avio_tell(pb);
syncword = avio_rb16(pb);
streamid = avio_r8(pb);
avio_r8(pb); /* counter not used */
reserved = avio_r8(pb);
flags = avio_r8(pb);
length = avio_rb16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = avio_rb32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
/* PVA Audio Packets either start with a signaled PES packet or
* are a continuation of the previous PES packet. New PES packets
* always start at the beginning of a PVA Packet, never somewhere in
* the middle. */
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = avio_rb24(pb);
avio_r8(pb);
pes_packet_length = avio_rb16(pb);
pes_flags = avio_rb16(pb);
pes_header_data_length = avio_r8(pb);
if (pes_signal != 1 || pes_header_data_length == 0) {
pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "
"trying to recover\n");
avio_skip(pb, length - 9);
if (!read_packet)
return AVERROR(EIO);
goto recover;
}
ret = avio_read(pb, pes_header_data, pes_header_data_length);
if (ret != pes_header_data_length)
return ret < 0 ? ret : AVERROR_INVALIDDATA;
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {
if (pes_header_data_length < 5) {
pva_log(s, AV_LOG_ERROR, "header too short\n");
avio_skip(pb, length);
return AVERROR_INVALIDDATA;
}
pva_pts = ff_parse_pes_pts(pes_header_data);
}
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if (pva_pts != AV_NOPTS_VALUE)
av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
*pts = pva_pts;
*len = length;
*strid = streamid;
return 0;
}
Commit Message: avformat/pva: Check for EOF before retrying in read_part_of_packet()
Fixes: Infinite loop
Fixes: pva-4b1835dbc2027bf3c567005dcc78e85199240d06
Found-by: Paul Ch <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-835 | static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
int *len, int *strid, int read_packet) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE, startpos;
int ret;
recover:
startpos = avio_tell(pb);
syncword = avio_rb16(pb);
streamid = avio_r8(pb);
avio_r8(pb); /* counter not used */
reserved = avio_r8(pb);
flags = avio_r8(pb);
length = avio_rb16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = avio_rb32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
/* PVA Audio Packets either start with a signaled PES packet or
* are a continuation of the previous PES packet. New PES packets
* always start at the beginning of a PVA Packet, never somewhere in
* the middle. */
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = avio_rb24(pb);
avio_r8(pb);
pes_packet_length = avio_rb16(pb);
pes_flags = avio_rb16(pb);
pes_header_data_length = avio_r8(pb);
if (avio_feof(pb)) {
return AVERROR_EOF;
}
if (pes_signal != 1 || pes_header_data_length == 0) {
pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "
"trying to recover\n");
avio_skip(pb, length - 9);
if (!read_packet)
return AVERROR(EIO);
goto recover;
}
ret = avio_read(pb, pes_header_data, pes_header_data_length);
if (ret != pes_header_data_length)
return ret < 0 ? ret : AVERROR_INVALIDDATA;
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {
if (pes_header_data_length < 5) {
pva_log(s, AV_LOG_ERROR, "header too short\n");
avio_skip(pb, length);
return AVERROR_INVALIDDATA;
}
pva_pts = ff_parse_pes_pts(pes_header_data);
}
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if (pva_pts != AV_NOPTS_VALUE)
av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
*pts = pva_pts;
*len = length;
*strid = streamid;
return 0;
}
| 168,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void perform_gamma_sbit_tests(png_modifier *pm)
{
png_byte sbit;
/* The only interesting cases are colour and grayscale, alpha is ignored here
* for overall speed. Only bit depths where sbit is less than the bit depth
* are tested.
*/
for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
{
png_byte colour_type = 0, bit_depth = 0;
unsigned int npalette = 0;
while (next_format(&colour_type, &bit_depth, &npalette, 1/*gamma*/))
if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
((colour_type == 3 && sbit < 8) ||
(colour_type != 3 && sbit < bit_depth)))
{
unsigned int i;
for (i=0; i<pm->ngamma_tests; ++i)
{
unsigned int j;
for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, npalette,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void perform_gamma_sbit_tests(png_modifier *pm)
{
png_byte sbit;
/* The only interesting cases are colour and grayscale, alpha is ignored here
* for overall speed. Only bit depths where sbit is less than the bit depth
* are tested.
*/
for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
{
png_byte colour_type = 0, bit_depth = 0;
unsigned int npalette = 0;
while (next_format(&colour_type, &bit_depth, &npalette,
pm->test_lbg_gamma_sbit, pm->test_tRNS))
if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
((colour_type == 3 && sbit < 8) ||
(colour_type != 3 && sbit < bit_depth)))
{
unsigned int i;
for (i=0; i<pm->ngamma_tests; ++i)
{
unsigned int j;
for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, npalette,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
}
| 173,680 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void prefetch_dec(void)
{
prefetch_table((const void *)&dec_tables, sizeof(dec_tables));
}
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 | static void prefetch_dec(void)
{
/* Modify counters to trigger copy-on-write and unsharing if physical pages
* of look-up table are shared between processes. Modifying counters also
* causes checksums for pages to change and hint same-page merging algorithm
* that these pages are frequently changing. */
dec_tables.counter_head++;
dec_tables.counter_tail++;
/* Prefetch look-up tables to cache. */
prefetch_table((const void *)&dec_tables, sizeof(dec_tables));
}
| 170,213 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
Commit Message:
CWE ID: CWE-119 | static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
if (size > (R_MAX - R_RX_BUF0 - rxbase) * 4) {
D(qemu_log("ethlite packet is too big, size=%x\n", size));
return -1;
}
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
| 164,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_timer_create(clockid_t which_clock, struct sigevent *event,
timer_t __user *created_timer_id)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct k_itimer *new_timer;
int error, new_timer_id;
int it_id_set = IT_ID_NOT_SET;
if (!kc)
return -EINVAL;
if (!kc->timer_create)
return -EOPNOTSUPP;
new_timer = alloc_posix_timer();
if (unlikely(!new_timer))
return -EAGAIN;
spin_lock_init(&new_timer->it_lock);
new_timer_id = posix_timer_add(new_timer);
if (new_timer_id < 0) {
error = new_timer_id;
goto out;
}
it_id_set = IT_ID_SET;
new_timer->it_id = (timer_t) new_timer_id;
new_timer->it_clock = which_clock;
new_timer->kclock = kc;
new_timer->it_overrun = -1;
if (event) {
rcu_read_lock();
new_timer->it_pid = get_pid(good_sigevent(event));
rcu_read_unlock();
if (!new_timer->it_pid) {
error = -EINVAL;
goto out;
}
new_timer->it_sigev_notify = event->sigev_notify;
new_timer->sigq->info.si_signo = event->sigev_signo;
new_timer->sigq->info.si_value = event->sigev_value;
} else {
new_timer->it_sigev_notify = SIGEV_SIGNAL;
new_timer->sigq->info.si_signo = SIGALRM;
memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t));
new_timer->sigq->info.si_value.sival_int = new_timer->it_id;
new_timer->it_pid = get_pid(task_tgid(current));
}
new_timer->sigq->info.si_tid = new_timer->it_id;
new_timer->sigq->info.si_code = SI_TIMER;
if (copy_to_user(created_timer_id,
&new_timer_id, sizeof (new_timer_id))) {
error = -EFAULT;
goto out;
}
error = kc->timer_create(new_timer);
if (error)
goto out;
spin_lock_irq(¤t->sighand->siglock);
new_timer->it_signal = current->signal;
list_add(&new_timer->list, ¤t->signal->posix_timers);
spin_unlock_irq(¤t->sighand->siglock);
return 0;
/*
* In the case of the timer belonging to another task, after
* the task is unlocked, the timer is owned by the other task
* and may cease to exist at any time. Don't use or modify
* new_timer after the unlock call.
*/
out:
release_posix_timer(new_timer, it_id_set);
return error;
}
Commit Message: posix-timers: Sanitize overrun handling
The posix timer overrun handling is broken because the forwarding functions
can return a huge number of overruns which does not fit in an int. As a
consequence timer_getoverrun(2) and siginfo::si_overrun can turn into
random number generators.
The k_clock::timer_forward() callbacks return a 64 bit value now. Make
k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal
accounting is correct. 3Remove the temporary (int) casts.
Add a helper function which clamps the overrun value returned to user space
via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value
between 0 and INT_MAX. INT_MAX is an indicator for user space that the
overrun value has been clamped.
Reported-by: Team OWL337 <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Acked-by: John Stultz <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michael Kerrisk <[email protected]>
Link: https://lkml.kernel.org/r/[email protected]
CWE ID: CWE-190 | static int do_timer_create(clockid_t which_clock, struct sigevent *event,
timer_t __user *created_timer_id)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct k_itimer *new_timer;
int error, new_timer_id;
int it_id_set = IT_ID_NOT_SET;
if (!kc)
return -EINVAL;
if (!kc->timer_create)
return -EOPNOTSUPP;
new_timer = alloc_posix_timer();
if (unlikely(!new_timer))
return -EAGAIN;
spin_lock_init(&new_timer->it_lock);
new_timer_id = posix_timer_add(new_timer);
if (new_timer_id < 0) {
error = new_timer_id;
goto out;
}
it_id_set = IT_ID_SET;
new_timer->it_id = (timer_t) new_timer_id;
new_timer->it_clock = which_clock;
new_timer->kclock = kc;
new_timer->it_overrun = -1LL;
if (event) {
rcu_read_lock();
new_timer->it_pid = get_pid(good_sigevent(event));
rcu_read_unlock();
if (!new_timer->it_pid) {
error = -EINVAL;
goto out;
}
new_timer->it_sigev_notify = event->sigev_notify;
new_timer->sigq->info.si_signo = event->sigev_signo;
new_timer->sigq->info.si_value = event->sigev_value;
} else {
new_timer->it_sigev_notify = SIGEV_SIGNAL;
new_timer->sigq->info.si_signo = SIGALRM;
memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t));
new_timer->sigq->info.si_value.sival_int = new_timer->it_id;
new_timer->it_pid = get_pid(task_tgid(current));
}
new_timer->sigq->info.si_tid = new_timer->it_id;
new_timer->sigq->info.si_code = SI_TIMER;
if (copy_to_user(created_timer_id,
&new_timer_id, sizeof (new_timer_id))) {
error = -EFAULT;
goto out;
}
error = kc->timer_create(new_timer);
if (error)
goto out;
spin_lock_irq(¤t->sighand->siglock);
new_timer->it_signal = current->signal;
list_add(&new_timer->list, ¤t->signal->posix_timers);
spin_unlock_irq(¤t->sighand->siglock);
return 0;
/*
* In the case of the timer belonging to another task, after
* the task is unlocked, the timer is owned by the other task
* and may cease to exist at any time. Don't use or modify
* new_timer after the unlock call.
*/
out:
release_posix_timer(new_timer, it_id_set);
return error;
}
| 169,181 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)
{
irda_queue_t* queue;
unsigned long flags = 0;
int i;
IRDA_ASSERT(hashbin != NULL, return -1;);
IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags,
hashbin_lock_depth++);
}
/*
* Free the entries in the hashbin, TODO: use hashbin_clear when
* it has been shown to work
*/
for (i = 0; i < HASHBIN_SIZE; i ++ ) {
queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);
while (queue ) {
if (free_func)
(*free_func)(queue);
queue = dequeue_first(
(irda_queue_t**) &hashbin->hb_queue[i]);
}
}
/* Cleanup local data */
hashbin->hb_current = NULL;
hashbin->magic = ~HB_MAGIC;
/* Release lock */
if ( hashbin->hb_type & HB_LOCK) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
#ifdef CONFIG_LOCKDEP
hashbin_lock_depth--;
#endif
}
/*
* Free the hashbin structure
*/
kfree(hashbin);
return 0;
}
Commit Message: irda: Fix lockdep annotations in hashbin_delete().
A nested lock depth was added to the hasbin_delete() code but it
doesn't actually work some well and results in tons of lockdep splats.
Fix the code instead to properly drop the lock around the operation
and just keep peeking the head of the hashbin queue.
Reported-by: Dmitry Vyukov <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)
{
irda_queue_t* queue;
unsigned long flags = 0;
int i;
IRDA_ASSERT(hashbin != NULL, return -1;);
IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);
/* Synchronize */
if (hashbin->hb_type & HB_LOCK)
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
/*
* Free the entries in the hashbin, TODO: use hashbin_clear when
* it has been shown to work
*/
for (i = 0; i < HASHBIN_SIZE; i ++ ) {
while (1) {
queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);
if (!queue)
break;
if (free_func) {
if (hashbin->hb_type & HB_LOCK)
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
free_func(queue);
if (hashbin->hb_type & HB_LOCK)
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
}
}
}
/* Cleanup local data */
hashbin->hb_current = NULL;
hashbin->magic = ~HB_MAGIC;
/* Release lock */
if (hashbin->hb_type & HB_LOCK)
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
/*
* Free the hashbin structure
*/
kfree(hashbin);
return 0;
}
| 168,344 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> V8Debugger::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
if (!enabled()) {
NOTREACHED();
return v8::Undefined(m_isolate);
}
v8::Local<v8::Value> argv[] = { object };
v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked();
if (!entriesValue->IsArray())
return v8::Undefined(m_isolate);
v8::Local<v8::Array> entries = entriesValue.As<v8::Array>();
if (!markArrayEntriesAsInternal(context, entries, V8InternalValueType::kEntry))
return v8::Undefined(m_isolate);
if (!entries->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false))
return v8::Undefined(m_isolate);
return entries;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::Local<v8::Value> V8Debugger::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
if (!enabled()) {
NOTREACHED();
return v8::Undefined(m_isolate);
}
v8::Local<v8::Value> argv[] = { object };
v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked();
v8::Local<v8::Value> copied;
if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, entriesValue).ToLocal(&copied) || !copied->IsArray())
return v8::Undefined(m_isolate);
if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kEntry))
return v8::Undefined(m_isolate);
return copied;
}
| 172,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {
len = ff_amf_tag_size(data, data_end);
if (len < 0)
len = data_end - data;
data += len;
}
if (data_end - data < 3)
return -1;
data++;
for (;;) {
int size = bytestream_get_be16(&data);
if (!size)
break;
if (size < 0 || size >= data_end - data)
return -1;
data += size;
if (size == namelen && !memcmp(data-size, name, namelen)) {
switch (*data++) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", *data ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream_get_be16(&data);
av_strlcpy(dst, data, FFMIN(len+1, dst_size));
break;
default:
return -1;
}
return 0;
}
len = ff_amf_tag_size(data, data_end);
if (len < 0 || len >= data_end - data)
return -1;
data += len;
}
return -1;
}
Commit Message: avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2
Fixes: out of array accesses
Found-by: JunDong Xie of Ant-financial Light-Year Security Lab
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-20 | int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
static int amf_get_field_value2(GetByteContext *gb,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (bytestream2_peek_byte(gb) != AMF_DATA_TYPE_OBJECT && bytestream2_get_bytes_left(gb) > 0) {
int ret = amf_tag_skip(gb);
if (ret < 0)
return -1;
}
if (bytestream2_get_bytes_left(gb) < 3)
return -1;
bytestream2_get_byte(gb);
for (;;) {
int size = bytestream2_get_be16(gb);
if (!size)
break;
if (size < 0 || size >= bytestream2_get_bytes_left(gb))
return -1;
bytestream2_skip(gb, size);
if (size == namelen && !memcmp(gb->buffer-size, name, namelen)) {
switch (bytestream2_get_byte(gb)) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(bytestream2_get_be64(gb)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", bytestream2_get_byte(gb) ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream2_get_be16(gb);
if (dst_size < 1)
return -1;
if (dst_size < len + 1)
len = dst_size - 1;
bytestream2_get_buffer(gb, dst, len);
dst[len] = 0;
break;
default:
return -1;
}
return 0;
}
len = amf_tag_skip(gb);
if (len < 0 || bytestream2_get_bytes_left(gb) <= 0)
return -1;
}
return -1;
}
| 168,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason) {
unsigned long identifier = CreateUniqueIdentifier();
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | void InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason,
Resource::Type resource_type) {
unsigned long identifier = CreateUniqueIdentifier();
InspectorPageAgent::ResourceType type =
InspectorPageAgent::ToResourceType(resource_type);
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info, type);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
| 172,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (!poolAppendChar(&dtd->pool, *s))
return 0;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
}
}
return 1;
}
Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186)
CWE ID: CWE-611 | setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (!poolAppendChar(&dtd->pool, *s))
return 0;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
break;
}
}
return 1;
}
| 169,775 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_Parse( const char *value )
{
cJSON *c;
ep = 0;
if ( ! ( c = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! parse_value( c, skip( value ) ) ) {
cJSON_Delete( c );
return 0;
}
return c;
}
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_Parse( const char *value )
cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
{
const char *end=0,**ep=return_parse_end?return_parse_end:&global_ep;
cJSON *c=cJSON_New_Item();
*ep=0;
if (!c) return 0; /* memory fail */
end=parse_value(c,skip(value),ep);
if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);*ep=end;return 0;}}
if (return_parse_end) *return_parse_end=end;
return c;
}
| 167,292 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos,
long long size) {
assert(pReader);
assert(pos >= 0);
if ((size <= 0) || (size > 8))
return E_FILE_FORMAT_INVALID;
long long result = 0;
for (long long i = 0; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return result;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos,
long long UnserializeUInt(IMkvReader* pReader, long long pos, long long size) {
if (!pReader || pos < 0 || (size <= 0) || (size > 8))
return E_FILE_FORMAT_INVALID;
long long result = 0;
for (long long i = 0; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return result;
}
| 173,868 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PlatformSensorProviderWin::CreateSensorInternal(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!StartSensorThread()) {
callback.Run(nullptr);
return;
}
switch (type) {
case mojom::SensorType::LINEAR_ACCELERATION: {
auto linear_acceleration_fusion_algorithm = std::make_unique<
LinearAccelerationFusionAlgorithmUsingAccelerometer>();
PlatformSensorFusion::Create(
std::move(mapping), this,
std::move(linear_acceleration_fusion_algorithm), callback);
break;
}
default: {
base::PostTaskAndReplyWithResult(
sensor_thread_->task_runner().get(), FROM_HERE,
base::Bind(&PlatformSensorProviderWin::CreateSensorReader,
base::Unretained(this), type),
base::Bind(&PlatformSensorProviderWin::SensorReaderCreated,
base::Unretained(this), type, base::Passed(&mapping),
callback));
break;
}
}
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void PlatformSensorProviderWin::CreateSensorInternal(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
const CreateSensorCallback& callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!StartSensorThread()) {
callback.Run(nullptr);
return;
}
switch (type) {
case mojom::SensorType::LINEAR_ACCELERATION: {
auto linear_acceleration_fusion_algorithm = std::make_unique<
LinearAccelerationFusionAlgorithmUsingAccelerometer>();
PlatformSensorFusion::Create(
reading_buffer, this, std::move(linear_acceleration_fusion_algorithm),
callback);
break;
}
default: {
base::PostTaskAndReplyWithResult(
sensor_thread_->task_runner().get(), FROM_HERE,
base::Bind(&PlatformSensorProviderWin::CreateSensorReader,
base::Unretained(this), type),
base::Bind(&PlatformSensorProviderWin::SensorReaderCreated,
base::Unretained(this), type, reading_buffer, callback));
break;
}
}
}
| 172,847 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle,
base::ProcessHandle process,
bool close_source_handle) {
IPC::PlatformFileForTransit out_handle;
#if defined(OS_WIN)
DWORD options = DUPLICATE_SAME_ACCESS;
if (close_source_handle)
options |= DUPLICATE_CLOSE_SOURCE;
if (!::DuplicateHandle(::GetCurrentProcess(),
handle,
process,
&out_handle,
0,
FALSE,
options)) {
out_handle = IPC::InvalidPlatformFileForTransit();
}
#elif defined(OS_POSIX)
int fd = close_source_handle ? handle : ::dup(handle);
out_handle = base::FileDescriptor(fd, true);
#else
#error Not implemented.
#endif
return out_handle;
}
Commit Message: GetFileHandleForProcess should check for INVALID_HANDLE_VALUE
BUG=243339
[email protected]
Review URL: https://codereview.chromium.org/16020004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202207 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle,
base::ProcessHandle process,
bool close_source_handle) {
IPC::PlatformFileForTransit out_handle;
#if defined(OS_WIN)
DWORD options = DUPLICATE_SAME_ACCESS;
if (close_source_handle)
options |= DUPLICATE_CLOSE_SOURCE;
if (handle == INVALID_HANDLE_VALUE ||
!::DuplicateHandle(::GetCurrentProcess(),
handle,
process,
&out_handle,
0,
FALSE,
options)) {
out_handle = IPC::InvalidPlatformFileForTransit();
}
#elif defined(OS_POSIX)
int fd = close_source_handle ? handle : ::dup(handle);
out_handle = base::FileDescriptor(fd, true);
#else
#error Not implemented.
#endif
return out_handle;
}
| 171,314 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long EBMLHeader::Parse(
IMkvReader* pReader,
long long& pos)
{
assert(pReader);
long long total, available;
long status = pReader->Length(&total, &available);
if (status < 0) //error
return status;
pos = 0;
long long end = (available >= 1024) ? 1024 : available;
for (;;)
{
unsigned char b = 0;
while (pos < end)
{
status = pReader->Read(pos, 1, &b);
if (status < 0) //error
return status;
if (b == 0x1A)
break;
++pos;
}
if (b != 0x1A)
{
if (pos >= 1024)
return E_FILE_FORMAT_INVALID; //don't bother looking anymore
if ((total >= 0) && ((total - available) < 5))
return E_FILE_FORMAT_INVALID;
return available + 5; //5 = 4-byte ID + 1st byte of size
}
if ((total >= 0) && ((total - pos) < 5))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < 5)
return pos + 5; //try again later
long len;
const long long result = ReadUInt(pReader, pos, len);
if (result < 0) //error
return result;
if (result == 0x0A45DFA3) //EBML Header ID
{
pos += len; //consume ID
break;
}
++pos; //throw away just the 0x1A byte, and try again
}
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return result;
if (result > 0) //need more data
return result;
assert(len > 0);
assert(len <= 8);
if ((total >= 0) && ((total - pos) < len))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < len)
return pos + len; //try again later
result = ReadUInt(pReader, pos, len);
if (result < 0) //error
return result;
pos += len; //consume size field
if ((total >= 0) && ((total - pos) < result))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < result)
return pos + result;
end = pos + result;
Init();
while (pos < end)
{
long long id, size;
status = ParseElementHeader(
pReader,
pos,
end,
id,
size);
if (status < 0) //error
return status;
if (size == 0) //weird
return E_FILE_FORMAT_INVALID;
if (id == 0x0286) //version
{
m_version = UnserializeUInt(pReader, pos, size);
if (m_version <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x02F7) //read version
{
m_readVersion = UnserializeUInt(pReader, pos, size);
if (m_readVersion <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x02F2) //max id length
{
m_maxIdLength = UnserializeUInt(pReader, pos, size);
if (m_maxIdLength <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x02F3) //max size length
{
m_maxSizeLength = UnserializeUInt(pReader, pos, size);
if (m_maxSizeLength <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0282) //doctype
{
if (m_docType)
return E_FILE_FORMAT_INVALID;
status = UnserializeString(pReader, pos, size, m_docType);
if (status) //error
return status;
}
else if (id == 0x0287) //doctype version
{
m_docTypeVersion = UnserializeUInt(pReader, pos, size);
if (m_docTypeVersion <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0285) //doctype read version
{
m_docTypeReadVersion = UnserializeUInt(pReader, pos, size);
if (m_docTypeReadVersion <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size;
}
assert(pos == end);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long EBMLHeader::Parse(
if (status < 0) // error
return status;
pos = 0;
long long end = (available >= 1024) ? 1024 : available;
for (;;) {
unsigned char b = 0;
while (pos < end) {
status = pReader->Read(pos, 1, &b);
if (status < 0) // error
return status;
if (b == 0x1A)
break;
++pos;
}
if (b != 0x1A) {
if (pos >= 1024)
return E_FILE_FORMAT_INVALID; // don't bother looking anymore
if ((total >= 0) && ((total - available) < 5))
return E_FILE_FORMAT_INVALID;
return available + 5; // 5 = 4-byte ID + 1st byte of size
}
if ((total >= 0) && ((total - pos) < 5))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < 5)
return pos + 5; // try again later
long len;
const long long result = ReadUInt(pReader, pos, len);
if (result < 0) // error
return result;
if (result == 0x0A45DFA3) { // EBML Header ID
pos += len; // consume ID
break;
}
++pos; // throw away just the 0x1A byte, and try again
}
// pos designates start of size field
// get length of size field
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) // need more data
return result;
assert(len > 0);
assert(len <= 8);
if ((total >= 0) && ((total - pos) < len))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < len)
return pos + len; // try again later
// get the EBML header size
result = ReadUInt(pReader, pos, len);
if (result < 0) // error
return result;
pos += len; // consume size field
// pos now designates start of payload
if ((total >= 0) && ((total - pos) < result))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < result)
return pos + result;
end = pos + result;
Init();
while (pos < end) {
long long id, size;
status = ParseElementHeader(pReader, pos, end, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
return E_FILE_FORMAT_INVALID;
if (id == 0x0286) { // version
m_version = UnserializeUInt(pReader, pos, size);
if (m_version <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x02F7) { // read version
m_readVersion = UnserializeUInt(pReader, pos, size);
if (m_readVersion <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x02F2) { // max id length
m_maxIdLength = UnserializeUInt(pReader, pos, size);
if (m_maxIdLength <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x02F3) { // max size length
m_maxSizeLength = UnserializeUInt(pReader, pos, size);
if (m_maxSizeLength <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0282) { // doctype
if (m_docType)
return E_FILE_FORMAT_INVALID;
status = UnserializeString(pReader, pos, size, m_docType);
if (status) // error
return status;
} else if (id == 0x0287) { // doctype version
m_docTypeVersion = UnserializeUInt(pReader, pos, size);
if (m_docTypeVersion <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0285) { // doctype read version
m_docTypeReadVersion = UnserializeUInt(pReader, pos, size);
if (m_docTypeReadVersion <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size;
}
assert(pos == end);
return 0;
}
Segment::Segment(IMkvReader* pReader, long long elem_start,
// long long elem_size,
long long start, long long size)
: m_pReader(pReader),
m_element_start(elem_start),
// m_element_size(elem_size),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0) {}
Segment::~Segment() {
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** i = m_clusters;
Cluster** j = m_clusters + count;
while (i != j) {
Cluster* const p = *i++;
assert(p);
delete p;
}
delete[] m_clusters;
delete m_pTracks;
delete m_pInfo;
delete m_pCues;
delete m_pChapters;
delete m_pSeekHead;
}
long long Segment::CreateInstance(IMkvReader* pReader, long long pos,
Segment*& pSegment) {
assert(pReader);
assert(pos >= 0);
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) // error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
// I would assume that in practice this loop would execute
// exactly once, but we allow for other elements (e.g. Void)
// to immediately follow the EBML header. This is fine for
// the source filter case (since the entire file is available),
// but in the splitter case over a network we should probably
// just give up early. We could for example decide only to
// execute this loop a maximum of, say, 10 times.
// TODO:
// There is an implied "give up early" by only parsing up
// to the available limit. We do do that, but only if the
// total file size is unknown. We could decide to always
// use what's available as our limit (irrespective of whether
// we happen to know the total file length). This would have
// as its sense "parse this much of the file before giving up",
// which a slightly different sense from "try to parse up to
// 10 EMBL elements before giving up".
for (;;) {
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
// Read ID
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return id;
pos += len; // consume ID
// Read Size
result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
// Pos now points to start of payload
// Handle "unknown size" for live streaming of webm files.
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) { // Segment ID
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(pReader, idpos,
// elem_size
pos, size);
if (pSegment == 0)
return -1; // generic error
return 0; // success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; // consume payload
}
}
| 174,405 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
Commit Message:
CWE ID: CWE-189 | tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
| 164,739 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ipt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
const struct iphdr *ip;
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ipt_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
ip = ip_hdr(skb);
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
acpar.thoff = ip_hdrlen(skb);
acpar.hotdrop = false;
acpar.state = state;
WARN_ON(!(table->valid_hooks & (1 << hook)));
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct ipt_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
WARN_ON(!e);
if (!ip_packet_match(ip, indev, outdev,
&e->ip, acpar.fragoff)) {
no_match:
e = ipt_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ipt_get_target(e);
WARN_ON(!t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
} else {
e = jumpstack[--stackidx];
e = ipt_next_entry(e);
}
continue;
}
if (table_base + v != ipt_next_entry(e) &&
!(e->ip.flags & IPT_F_GOTO))
jumpstack[stackidx++] = e;
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE) {
/* Target might have changed stuff. */
ip = ip_hdr(skb);
e = ipt_next_entry(e);
} else {
/* Verdict */
break;
}
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
}
Commit Message: netfilter: add back stackpointer size checks
The rationale for removing the check is only correct for rulesets
generated by ip(6)tables.
In iptables, a jump can only occur to a user-defined chain, i.e.
because we size the stack based on number of user-defined chains we
cannot exceed stack size.
However, the underlying binary format has no such restriction,
and the validation step only ensures that the jump target is a
valid rule start point.
IOW, its possible to build a rule blob that has no user-defined
chains but does contain a jump.
If this happens, no jump stack gets allocated and crash occurs
because no jumpstack was allocated.
Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset")
Reported-by: [email protected]
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-476 | ipt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
const struct iphdr *ip;
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ipt_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
ip = ip_hdr(skb);
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
acpar.thoff = ip_hdrlen(skb);
acpar.hotdrop = false;
acpar.state = state;
WARN_ON(!(table->valid_hooks & (1 << hook)));
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct ipt_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
WARN_ON(!e);
if (!ip_packet_match(ip, indev, outdev,
&e->ip, acpar.fragoff)) {
no_match:
e = ipt_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ipt_get_target(e);
WARN_ON(!t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
} else {
e = jumpstack[--stackidx];
e = ipt_next_entry(e);
}
continue;
}
if (table_base + v != ipt_next_entry(e) &&
!(e->ip.flags & IPT_F_GOTO)) {
if (unlikely(stackidx >= private->stacksize)) {
verdict = NF_DROP;
break;
}
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE) {
/* Target might have changed stuff. */
ip = ip_hdr(skb);
e = ipt_next_entry(e);
} else {
/* Verdict */
break;
}
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
}
| 169,363 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher(
const GURL& url) {
std::unique_ptr<net::URLFetcher> fetcher =
net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
fetcher->SetRequestContext(helper_->request_context());
fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
fetcher->SetAutomaticallyRetryOnNetworkChanges(1);
return fetcher;
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190 | GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher(
const GURL& url) {
std::unique_ptr<net::URLFetcher> fetcher =
net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
fetcher->SetRequestContext(helper_->request_context());
fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
data_use_measurement::DataUseUserData::AttachToFetcher(
fetcher.get(), data_use_measurement::DataUseUserData::SIGNIN);
fetcher->SetAutomaticallyRetryOnNetworkChanges(1);
return fetcher;
}
| 172,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)())
{
char *file;
int file_len;
long srcx, srcy, width, height;
gdImagePtr im = NULL;
php_stream *stream;
FILE * fp = NULL;
#ifdef HAVE_GD_JPG
long ignore_warning;
#endif
if (image_type == PHP_GDIMG_TYPE_GD2PART) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) {
return;
}
if (width < 1 || height < 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed");
RETURN_FALSE;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_len) == FAILURE) {
return;
}
}
stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
#ifndef USE_GD_IOCTX
ioctx_func_p = NULL; /* don't allow sockets without IOCtx */
#endif
if (image_type == PHP_GDIMG_TYPE_WEBP) {
size_t buff_size;
char *buff;
/* needs to be malloc (persistent) - GD will free() it later */
buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1);
if (!buff_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data");
goto out_err;
}
im = (*ioctx_func_p)(buff_size, buff);
if (!im) {
goto out_err;
}
goto register_im;
}
/* try and avoid allocating a FILE* if the stream is not naturally a FILE* */
if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) {
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
goto out_err;
}
} else if (ioctx_func_p) {
#ifdef USE_GD_IOCTX
/* we can create an io context */
gdIOCtx* io_ctx;
size_t buff_size;
char *buff;
/* needs to be malloc (persistent) - GD will free() it later */
buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1);
if (!buff_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data");
goto out_err;
}
io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0);
if (!io_ctx) {
pefree(buff, 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context");
goto out_err;
}
if (image_type == PHP_GDIMG_TYPE_GD2PART) {
im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height);
} else {
im = (*ioctx_func_p)(io_ctx);
}
#if HAVE_LIBGD204
io_ctx->gd_free(io_ctx);
#else
io_ctx->free(io_ctx);
#endif
pefree(buff, 1);
#endif
}
else {
/* try and force the stream to be FILE* */
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) {
goto out_err;
}
}
if (!im && fp) {
switch (image_type) {
case PHP_GDIMG_TYPE_GD2PART:
im = (*func_p)(fp, srcx, srcy, width, height);
break;
#if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED)
case PHP_GDIMG_TYPE_XPM:
im = gdImageCreateFromXpm(file);
break;
#endif
#ifdef HAVE_GD_JPG
case PHP_GDIMG_TYPE_JPG:
ignore_warning = INI_INT("gd.jpeg_ignore_warning");
#ifdef HAVE_GD_BUNDLED
im = gdImageCreateFromJpeg(fp, ignore_warning);
#else
im = gdImageCreateFromJpeg(fp);
#endif
break;
#endif
default:
im = (*func_p)(fp);
break;
}
fflush(fp);
}
register_im:
if (im) {
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
php_stream_close(stream);
return;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn);
out_err:
php_stream_close(stream);
RETURN_FALSE;
}
Commit Message:
CWE ID: CWE-254 | static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)())
{
char *file;
int file_len;
long srcx, srcy, width, height;
gdImagePtr im = NULL;
php_stream *stream;
FILE * fp = NULL;
#ifdef HAVE_GD_JPG
long ignore_warning;
#endif
if (image_type == PHP_GDIMG_TYPE_GD2PART) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) {
return;
}
if (width < 1 || height < 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed");
RETURN_FALSE;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) {
return;
}
}
stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
#ifndef USE_GD_IOCTX
ioctx_func_p = NULL; /* don't allow sockets without IOCtx */
#endif
if (image_type == PHP_GDIMG_TYPE_WEBP) {
size_t buff_size;
char *buff;
/* needs to be malloc (persistent) - GD will free() it later */
buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1);
if (!buff_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data");
goto out_err;
}
im = (*ioctx_func_p)(buff_size, buff);
if (!im) {
goto out_err;
}
goto register_im;
}
/* try and avoid allocating a FILE* if the stream is not naturally a FILE* */
if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) {
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
goto out_err;
}
} else if (ioctx_func_p) {
#ifdef USE_GD_IOCTX
/* we can create an io context */
gdIOCtx* io_ctx;
size_t buff_size;
char *buff;
/* needs to be malloc (persistent) - GD will free() it later */
buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1);
if (!buff_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data");
goto out_err;
}
io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0);
if (!io_ctx) {
pefree(buff, 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context");
goto out_err;
}
if (image_type == PHP_GDIMG_TYPE_GD2PART) {
im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height);
} else {
im = (*ioctx_func_p)(io_ctx);
}
#if HAVE_LIBGD204
io_ctx->gd_free(io_ctx);
#else
io_ctx->free(io_ctx);
#endif
pefree(buff, 1);
#endif
}
else {
/* try and force the stream to be FILE* */
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) {
goto out_err;
}
}
if (!im && fp) {
switch (image_type) {
case PHP_GDIMG_TYPE_GD2PART:
im = (*func_p)(fp, srcx, srcy, width, height);
break;
#if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED)
case PHP_GDIMG_TYPE_XPM:
im = gdImageCreateFromXpm(file);
break;
#endif
#ifdef HAVE_GD_JPG
case PHP_GDIMG_TYPE_JPG:
ignore_warning = INI_INT("gd.jpeg_ignore_warning");
#ifdef HAVE_GD_BUNDLED
im = gdImageCreateFromJpeg(fp, ignore_warning);
#else
im = gdImageCreateFromJpeg(fp);
#endif
break;
#endif
default:
im = (*func_p)(fp);
break;
}
fflush(fp);
}
register_im:
if (im) {
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
php_stream_close(stream);
return;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn);
out_err:
php_stream_close(stream);
RETURN_FALSE;
}
| 165,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
Commit Message: xfrm_user: fix info leak in copy_to_user_policy()
The memory reserved to dump the xfrm policy includes multiple padding
bytes added by the compiler for alignment (padding bytes in struct
xfrm_selector and struct xfrm_userpolicy_info). Add an explicit
memset(0) before filling the buffer to avoid the heap info leak.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memset(p, 0, sizeof(*p));
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
| 169,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestWebKitPlatformSupport::TestWebKitPlatformSupport(bool unit_test_mode)
: unit_test_mode_(unit_test_mode) {
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(true);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebScriptController::enableV8SingleThreadMode();
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableDataTransferItems(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableGamepad(true);
bool enable_media = false;
FilePath module_path;
if (PathService::Get(base::DIR_MODULE, &module_path)) {
#if defined(OS_MACOSX)
if (base::mac::AmIBundled())
module_path = module_path.DirName().DirName().DirName();
#endif
if (media::InitializeMediaLibrary(module_path))
enable_media = true;
}
WebKit::WebRuntimeFeatures::enableMediaPlayer(enable_media);
LOG_IF(WARNING, !enable_media) << "Failed to initialize the media library.\n";
WebKit::WebRuntimeFeatures::enableGeolocation(false);
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
blob_registry_ = new TestShellWebBlobRegistryImpl();
file_utilities_.set_sandbox_enabled(false);
if (!file_system_root_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the filesystem."
"FileSystem feature will be disabled.";
DCHECK(file_system_root_.path().empty());
}
#if defined(OS_WIN)
SetThemeEngine(NULL);
#endif
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
net::CookieMonster::EnableFileScheme();
SimpleResourceLoaderBridge::Init(FilePath(), cache_mode, true);
webkit_glue::SetJavaScriptFlags(" --expose-gc");
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | TestWebKitPlatformSupport::TestWebKitPlatformSupport(bool unit_test_mode)
: unit_test_mode_(unit_test_mode) {
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(true);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsEmptyDocument(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebScriptController::enableV8SingleThreadMode();
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableDataTransferItems(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableGamepad(true);
bool enable_media = false;
FilePath module_path;
if (PathService::Get(base::DIR_MODULE, &module_path)) {
#if defined(OS_MACOSX)
if (base::mac::AmIBundled())
module_path = module_path.DirName().DirName().DirName();
#endif
if (media::InitializeMediaLibrary(module_path))
enable_media = true;
}
WebKit::WebRuntimeFeatures::enableMediaPlayer(enable_media);
LOG_IF(WARNING, !enable_media) << "Failed to initialize the media library.\n";
WebKit::WebRuntimeFeatures::enableGeolocation(false);
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
blob_registry_ = new TestShellWebBlobRegistryImpl();
file_utilities_.set_sandbox_enabled(false);
if (!file_system_root_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the filesystem."
"FileSystem feature will be disabled.";
DCHECK(file_system_root_.path().empty());
}
#if defined(OS_WIN)
SetThemeEngine(NULL);
#endif
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
net::CookieMonster::EnableFileScheme();
SimpleResourceLoaderBridge::Init(FilePath(), cache_mode, true);
webkit_glue::SetJavaScriptFlags(" --expose-gc");
WebScriptController::registerExtension(extensions_v8::GCExtension::Get());
}
| 171,035 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod3(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->overloadedMethod(strArg);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod3(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->overloadedMethod(strArg);
return JSValue::encode(jsUndefined());
}
| 170,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: idna_strerror (Idna_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case IDNA_SUCCESS:
p = _("Success");
break;
case IDNA_STRINGPREP_ERROR:
p = _("String preparation failed");
break;
case IDNA_PUNYCODE_ERROR:
p = _("Punycode failed");
break;
case IDNA_CONTAINS_NON_LDH:
p = _("Non-digit/letter/hyphen in input");
break;
case IDNA_CONTAINS_MINUS:
p = _("Forbidden leading or trailing minus sign (`-')");
break;
case IDNA_INVALID_LENGTH:
p = _("Output would be too large or too small");
break;
case IDNA_NO_ACE_PREFIX:
p = _("Input does not start with ACE prefix (`xn--')");
break;
case IDNA_ROUNDTRIP_VERIFY_ERROR:
p = _("String not idempotent under ToASCII");
break;
case IDNA_CONTAINS_ACE_PREFIX:
p = _("Input already contain ACE prefix (`xn--')");
break;
case IDNA_ICONV_ERROR:
p = _("System iconv failed");
break;
case IDNA_MALLOC_ERROR:
p = _("Cannot allocate memory");
break;
case IDNA_DLOPEN_ERROR:
p = _("System dlopen failed");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
Commit Message:
CWE ID: CWE-119 | idna_strerror (Idna_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case IDNA_SUCCESS:
p = _("Success");
break;
case IDNA_STRINGPREP_ERROR:
p = _("String preparation failed");
break;
case IDNA_PUNYCODE_ERROR:
p = _("Punycode failed");
break;
case IDNA_CONTAINS_NON_LDH:
p = _("Non-digit/letter/hyphen in input");
break;
case IDNA_CONTAINS_MINUS:
p = _("Forbidden leading or trailing minus sign (`-')");
break;
case IDNA_INVALID_LENGTH:
p = _("Output would be too large or too small");
break;
case IDNA_NO_ACE_PREFIX:
p = _("Input does not start with ACE prefix (`xn--')");
break;
case IDNA_ROUNDTRIP_VERIFY_ERROR:
p = _("String not idempotent under ToASCII");
break;
case IDNA_CONTAINS_ACE_PREFIX:
p = _("Input already contain ACE prefix (`xn--')");
break;
case IDNA_ICONV_ERROR:
p = _("Could not convert string in locale encoding");
break;
case IDNA_MALLOC_ERROR:
p = _("Cannot allocate memory");
break;
case IDNA_DLOPEN_ERROR:
p = _("System dlopen failed");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
| 164,760 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.