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: void traverse_commit_list(struct rev_info *revs, show_commit_fn show_commit, show_object_fn show_object, void *data) { int i; struct commit *commit; struct strbuf base; strbuf_init(&base, PATH_MAX); while ((commit = get_revision(revs)) != NULL) { /* * an uninteresting boundary commit may not have its tree * parsed yet, but we are not going to show them anyway */ if (commit->tree) add_pending_tree(revs, commit->tree); show_commit(commit, data); } for (i = 0; i < revs->pending.nr; i++) { struct object_array_entry *pending = revs->pending.objects + i; struct object *obj = pending->item; const char *name = pending->name; const char *path = pending->path; if (obj->flags & (UNINTERESTING | SEEN)) continue; if (obj->type == OBJ_TAG) { obj->flags |= SEEN; show_object(obj, NULL, name, data); continue; } if (!path) path = ""; if (obj->type == OBJ_TREE) { process_tree(revs, (struct tree *)obj, show_object, &base, path, data); continue; } if (obj->type == OBJ_BLOB) { process_blob(revs, (struct blob *)obj, show_object, NULL, path, data); continue; } die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name); } object_array_clear(&revs->pending); strbuf_release(&base); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
void traverse_commit_list(struct rev_info *revs, show_commit_fn show_commit, show_object_fn show_object, void *data) { int i; struct commit *commit; struct strbuf base; strbuf_init(&base, PATH_MAX); while ((commit = get_revision(revs)) != NULL) { /* * an uninteresting boundary commit may not have its tree * parsed yet, but we are not going to show them anyway */ if (commit->tree) add_pending_tree(revs, commit->tree); show_commit(commit, data); } for (i = 0; i < revs->pending.nr; i++) { struct object_array_entry *pending = revs->pending.objects + i; struct object *obj = pending->item; const char *name = pending->name; const char *path = pending->path; if (obj->flags & (UNINTERESTING | SEEN)) continue; if (obj->type == OBJ_TAG) { obj->flags |= SEEN; show_object(obj, name, data); continue; } if (!path) path = ""; if (obj->type == OBJ_TREE) { process_tree(revs, (struct tree *)obj, show_object, &base, path, data); continue; } if (obj->type == OBJ_BLOB) { process_blob(revs, (struct blob *)obj, show_object, &base, path, data); continue; } die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name); } object_array_clear(&revs->pending); strbuf_release(&base); }
167,420
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 boolean ReadIPTCProfile(j_decompress_ptr jpeg_info) { char magick[MagickPathExtent]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *iptc_profile, *profile; /* Determine length of binary data stored here. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } /* Validate that this was written as a Photoshop resource format slug. */ for (i=0; i < 10; i++) magick[i]=(char) GetCharacter(jpeg_info); magick[10]='\0'; length-=10; if (length <= 10) return(TRUE); if (LocaleCompare(magick,"Photoshop ") != 0) { /* Not a IPTC profile, return. */ for (i=0; i < (ssize_t) length; i++) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } /* Remove the version number. */ for (i=0; i < 4; i++) if (GetCharacter(jpeg_info) == EOF) break; if (length <= 11) return(TRUE); length-=4; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) { int c; c=GetCharacter(jpeg_info); if (c == EOF) break; *p++=(unsigned char) c; } error_manager->profile=NULL; if (i != (ssize_t) length) { profile=DestroyStringInfo(profile); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"InsufficientImageDataInFile","`%s'", image->filename); return(FALSE); } /* The IPTC profile is actually an 8bim */ iptc_profile=(StringInfo *) GetImageProfile(image,"8bim"); if (iptc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(iptc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: iptc, %.20g bytes",(double) length); return(TRUE); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641 CWE ID:
static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info) { char magick[MagickPathExtent]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *iptc_profile, *profile; /* Determine length of binary data stored here. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } /* Validate that this was written as a Photoshop resource format slug. */ for (i=0; i < 10; i++) magick[i]=(char) GetCharacter(jpeg_info); magick[10]='\0'; length-=10; if (length <= 10) return(TRUE); if (LocaleCompare(magick,"Photoshop ") != 0) { /* Not a IPTC profile, return. */ for (i=0; i < (ssize_t) length; i++) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } /* Remove the version number. */ for (i=0; i < 4; i++) if (GetCharacter(jpeg_info) == EOF) break; if (length <= 11) return(TRUE); length-=4; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) { int c; c=GetCharacter(jpeg_info); if (c == EOF) break; *p++=(unsigned char) c; } error_manager->profile=NULL; if (i != (ssize_t) length) { profile=DestroyStringInfo(profile); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"InsufficientImageDataInFile","`%s'", image->filename); return(FALSE); } /* The IPTC profile is actually an 8bim. */ iptc_profile=(StringInfo *) GetImageProfile(image,"8bim"); if (iptc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(iptc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: iptc, %.20g bytes",(double) length); return(TRUE); }
169,488
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(curl_escape) { char *str = NULL, *res = NULL; size_t str_len = 0; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if ((res = curl_easy_escape(ch->cp, str, str_len))) { RETVAL_STRING(res); curl_free(res); } else { RETURN_FALSE; } } Commit Message: Fix bug #72674 - check both curl_escape and curl_unescape CWE ID: CWE-119
PHP_FUNCTION(curl_escape) { char *str = NULL, *res = NULL; size_t str_len = 0; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ZEND_SIZE_T_INT_OVFL(str_len)) { RETURN_FALSE; } if ((res = curl_easy_escape(ch->cp, str, str_len))) { RETVAL_STRING(res); curl_free(res); } else { RETURN_FALSE; } }
166,946
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 gfs2_bmap_alloc(struct inode *inode, const sector_t lblock, struct buffer_head *bh_map, struct metapath *mp, const unsigned int sheight, const unsigned int height, const unsigned int maxlen) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); struct buffer_head *dibh = mp->mp_bh[0]; u64 bn, dblock = 0; unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0; unsigned dblks = 0; unsigned ptrs_per_blk; const unsigned end_of_metadata = height - 1; int eob = 0; enum alloc_state state; __be64 *ptr; __be64 zero_bn = 0; BUG_ON(sheight < 1); BUG_ON(dibh == NULL); gfs2_trans_add_bh(ip->i_gl, dibh, 1); if (height == sheight) { struct buffer_head *bh; /* Bottom indirect block exists, find unalloced extent size */ ptr = metapointer(end_of_metadata, mp); bh = mp->mp_bh[end_of_metadata]; dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob); BUG_ON(dblks < 1); state = ALLOC_DATA; } else { /* Need to allocate indirect blocks */ ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs; dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]); if (height == ip->i_height) { /* Writing into existing tree, extend tree down */ iblks = height - sheight; state = ALLOC_GROW_DEPTH; } else { /* Building up tree height */ state = ALLOC_GROW_HEIGHT; iblks = height - ip->i_height; branch_start = metapath_branch_start(mp); iblks += (height - branch_start); } } /* start of the second part of the function (state machine) */ blks = dblks + iblks; i = sheight; do { int error; n = blks - alloced; error = gfs2_alloc_block(ip, &bn, &n); if (error) return error; alloced += n; if (state != ALLOC_DATA || gfs2_is_jdata(ip)) gfs2_trans_add_unrevoke(sdp, bn, n); switch (state) { /* Growing height of tree */ case ALLOC_GROW_HEIGHT: if (i == 1) { ptr = (__be64 *)(dibh->b_data + sizeof(struct gfs2_dinode)); zero_bn = *ptr; } for (; i - 1 < height - ip->i_height && n > 0; i++, n--) gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++); if (i - 1 == height - ip->i_height) { i--; gfs2_buffer_copy_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header), dibh, sizeof(struct gfs2_dinode)); gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + sizeof(__be64)); ptr = (__be64 *)(mp->mp_bh[i]->b_data + sizeof(struct gfs2_meta_header)); *ptr = zero_bn; state = ALLOC_GROW_DEPTH; for(i = branch_start; i < height; i++) { if (mp->mp_bh[i] == NULL) break; brelse(mp->mp_bh[i]); mp->mp_bh[i] = NULL; } i = branch_start; } if (n == 0) break; /* Branching from existing tree */ case ALLOC_GROW_DEPTH: if (i > 1 && i < height) gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1); for (; i < height && n > 0; i++, n--) gfs2_indirect_init(mp, ip->i_gl, i, mp->mp_list[i-1], bn++); if (i == height) state = ALLOC_DATA; if (n == 0) break; /* Tree complete, adding data blocks */ case ALLOC_DATA: BUG_ON(n > dblks); BUG_ON(mp->mp_bh[end_of_metadata] == NULL); gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1); dblks = n; ptr = metapointer(end_of_metadata, mp); dblock = bn; while (n-- > 0) *ptr++ = cpu_to_be64(bn++); break; } } while ((state != ALLOC_DATA) || !dblock); ip->i_height = height; gfs2_add_inode_blocks(&ip->i_inode, alloced); gfs2_dinode_out(ip, mp->mp_bh[0]->b_data); map_bh(bh_map, inode->i_sb, dblock); bh_map->b_size = dblks << inode->i_blkbits; set_buffer_new(bh_map); return 0; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119
static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock, struct buffer_head *bh_map, struct metapath *mp, const unsigned int sheight, const unsigned int height, const unsigned int maxlen) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); struct super_block *sb = sdp->sd_vfs; struct buffer_head *dibh = mp->mp_bh[0]; u64 bn, dblock = 0; unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0; unsigned dblks = 0; unsigned ptrs_per_blk; const unsigned end_of_metadata = height - 1; int ret; int eob = 0; enum alloc_state state; __be64 *ptr; __be64 zero_bn = 0; BUG_ON(sheight < 1); BUG_ON(dibh == NULL); gfs2_trans_add_bh(ip->i_gl, dibh, 1); if (height == sheight) { struct buffer_head *bh; /* Bottom indirect block exists, find unalloced extent size */ ptr = metapointer(end_of_metadata, mp); bh = mp->mp_bh[end_of_metadata]; dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob); BUG_ON(dblks < 1); state = ALLOC_DATA; } else { /* Need to allocate indirect blocks */ ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs; dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]); if (height == ip->i_height) { /* Writing into existing tree, extend tree down */ iblks = height - sheight; state = ALLOC_GROW_DEPTH; } else { /* Building up tree height */ state = ALLOC_GROW_HEIGHT; iblks = height - ip->i_height; branch_start = metapath_branch_start(mp); iblks += (height - branch_start); } } /* start of the second part of the function (state machine) */ blks = dblks + iblks; i = sheight; do { int error; n = blks - alloced; error = gfs2_alloc_block(ip, &bn, &n); if (error) return error; alloced += n; if (state != ALLOC_DATA || gfs2_is_jdata(ip)) gfs2_trans_add_unrevoke(sdp, bn, n); switch (state) { /* Growing height of tree */ case ALLOC_GROW_HEIGHT: if (i == 1) { ptr = (__be64 *)(dibh->b_data + sizeof(struct gfs2_dinode)); zero_bn = *ptr; } for (; i - 1 < height - ip->i_height && n > 0; i++, n--) gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++); if (i - 1 == height - ip->i_height) { i--; gfs2_buffer_copy_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header), dibh, sizeof(struct gfs2_dinode)); gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + sizeof(__be64)); ptr = (__be64 *)(mp->mp_bh[i]->b_data + sizeof(struct gfs2_meta_header)); *ptr = zero_bn; state = ALLOC_GROW_DEPTH; for(i = branch_start; i < height; i++) { if (mp->mp_bh[i] == NULL) break; brelse(mp->mp_bh[i]); mp->mp_bh[i] = NULL; } i = branch_start; } if (n == 0) break; /* Branching from existing tree */ case ALLOC_GROW_DEPTH: if (i > 1 && i < height) gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1); for (; i < height && n > 0; i++, n--) gfs2_indirect_init(mp, ip->i_gl, i, mp->mp_list[i-1], bn++); if (i == height) state = ALLOC_DATA; if (n == 0) break; /* Tree complete, adding data blocks */ case ALLOC_DATA: BUG_ON(n > dblks); BUG_ON(mp->mp_bh[end_of_metadata] == NULL); gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1); dblks = n; ptr = metapointer(end_of_metadata, mp); dblock = bn; while (n-- > 0) *ptr++ = cpu_to_be64(bn++); if (buffer_zeronew(bh_map)) { ret = sb_issue_zeroout(sb, dblock, dblks, GFP_NOFS); if (ret) { fs_err(sdp, "Failed to zero data buffers\n"); clear_buffer_zeronew(bh_map); } } break; } } while ((state != ALLOC_DATA) || !dblock); ip->i_height = height; gfs2_add_inode_blocks(&ip->i_inode, alloced); gfs2_dinode_out(ip, mp->mp_bh[0]->b_data); map_bh(bh_map, inode->i_sb, dblock); bh_map->b_size = dblks << inode->i_blkbits; set_buffer_new(bh_map); return 0; }
166,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } Commit Message: (for 4.9.3) CVE-2018-14881/BGP: Fix BGP_CAPCODE_RESTART. Add a bounds check and a comment to bgp_capabilities_print(). 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). CWE ID: CWE-125
bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ ND_TCHECK_16BITS(opt + i + 2); ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); }
169,833
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: PassRefPtr<DocumentFragment> Range::createDocumentFragmentForElement(const String& markup, Element* element, FragmentScriptingPermission scriptingPermission) { ASSERT(element); HTMLElement* htmlElement = toHTMLElement(element); if (htmlElement->ieForbidsInsertHTML()) return 0; if (htmlElement->hasLocalName(colTag) || htmlElement->hasLocalName(colgroupTag) || htmlElement->hasLocalName(framesetTag) || htmlElement->hasLocalName(headTag) || htmlElement->hasLocalName(styleTag) || htmlElement->hasLocalName(titleTag)) return 0; RefPtr<DocumentFragment> fragment = element->document()->createDocumentFragment(); if (element->document()->isHTMLDocument()) fragment->parseHTML(markup, element, scriptingPermission); else if (!fragment->parseXML(markup, element, scriptingPermission)) return 0; // FIXME: We should propagate a syntax error exception out here. RefPtr<Node> nextNode; for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) { nextNode = node->nextSibling(); if (node->hasTagName(htmlTag) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) { HTMLElement* element = toHTMLElement(node.get()); if (Node* firstChild = element->firstChild()) nextNode = firstChild; removeElementPreservingChildren(fragment, element); } } return fragment.release(); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
PassRefPtr<DocumentFragment> Range::createDocumentFragmentForElement(const String& markup, Element* element, FragmentScriptingPermission scriptingPermission)
170,435
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 RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { free (ptr); return ret; } ut32 j = 0; while (i < len && j < ptr->num_elem ) { ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; int buflen = bin->buf->length - (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { goto beach; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { goto beach; } ut32 j = 0; while (i < len && j < ptr->num_elem) { ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; beach: free (ptr); return ret; }
168,252
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: ScriptValue ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus) { String sourceURL = sourceCode.url(); const String* savedSourceURL = m_sourceURL; m_sourceURL = &sourceURL; v8::HandleScope handleScope; v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame); if (v8Context.IsEmpty()) return ScriptValue(); v8::Context::Scope scope(v8Context); RefPtr<Frame> protect(m_frame); v8::Local<v8::Value> object = compileAndRunScript(sourceCode, corsStatus); m_sourceURL = savedSourceURL; if (object.IsEmpty()) return ScriptValue(); return ScriptValue(object); } Commit Message: Call didAccessInitialDocument when javascript: URLs are used. BUG=265221 TEST=See bug for repro. Review URL: https://chromiumcodereview.appspot.com/22572004 git-svn-id: svn://svn.chromium.org/blink/trunk@155790 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
ScriptValue ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus) { String sourceURL = sourceCode.url(); const String* savedSourceURL = m_sourceURL; m_sourceURL = &sourceURL; v8::HandleScope handleScope; v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame); if (v8Context.IsEmpty()) return ScriptValue(); RefPtr<Frame> protect(m_frame); if (m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) m_frame->loader()->didAccessInitialDocument(); v8::Context::Scope scope(v8Context); v8::Local<v8::Value> object = compileAndRunScript(sourceCode, corsStatus); m_sourceURL = savedSourceURL; if (object.IsEmpty()) return ScriptValue(); return ScriptValue(object); }
171,179
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 SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK_EQ(-1, mapped_file_); if (options.size == 0) return false; if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) return false; base::ThreadRestrictions::ScopedAllowIO allow_io; FILE *fp; bool fix_size = true; FilePath path; if (options.name == NULL || options.name->empty()) { DCHECK(!options.open_existing); fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable); if (fp) { if (unlink(path.value().c_str())) PLOG(WARNING) << "unlink"; } } else { if (!FilePathForMemoryName(*options.name, &path)) return false; fp = file_util::OpenFile(path, "w+x"); if (fp == NULL && options.open_existing) { fp = file_util::OpenFile(path, "a+"); fix_size = false; } } if (fp && fix_size) { struct stat stat; if (fstat(fileno(fp), &stat) != 0) { file_util::CloseFile(fp); return false; } const size_t current_size = stat.st_size; if (current_size != options.size) { if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) { file_util::CloseFile(fp); return false; } } requested_size_ = options.size; } if (fp == NULL) { #if !defined(OS_MACOSX) PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; FilePath dir = path.DirName(); if (access(dir.value().c_str(), W_OK | X_OK) < 0) { PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value(); if (dir.value() == "/dev/shm") { LOG(FATAL) << "This is frequently caused by incorrect permissions on " << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix."; } } #else PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; #endif return false; } return PrepareMapFile(fp); } Commit Message: Posix: fix named SHM mappings permissions. Make sure that named mappings in /dev/shm/ aren't created with broad permissions. BUG=254159 [email protected], [email protected] Review URL: https://codereview.chromium.org/17779002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209814 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK_EQ(-1, mapped_file_); if (options.size == 0) return false; if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) return false; base::ThreadRestrictions::ScopedAllowIO allow_io; FILE *fp; bool fix_size = true; FilePath path; if (options.name == NULL || options.name->empty()) { DCHECK(!options.open_existing); fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable); if (fp) { if (unlink(path.value().c_str())) PLOG(WARNING) << "unlink"; } } else { if (!FilePathForMemoryName(*options.name, &path)) return false; // Make sure that the file is opened without any permission // to other users on the system. const mode_t kOwnerOnly = S_IRUSR | S_IWUSR; // First, try to create the file. int fd = HANDLE_EINTR( open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly)); if (fd == -1 && options.open_existing) { // If this doesn't work, try and open an existing file in append mode. // Opening an existing file in a world writable directory has two main // security implications: // - Attackers could plant a file under their control, so ownership of // the file is checked below. // - Attackers could plant a symbolic link so that an unexpected file // is opened, so O_NOFOLLOW is passed to open(). fd = HANDLE_EINTR( open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW)); // Check that the current user owns the file. // If uid != euid, then a more complex permission model is used and this // API is not appropriate. const uid_t real_uid = getuid(); const uid_t effective_uid = geteuid(); struct stat sb; if (fd >= 0 && (fstat(fd, &sb) != 0 || sb.st_uid != real_uid || sb.st_uid != effective_uid)) { LOG(ERROR) << "Invalid owner when opening existing shared memory file."; HANDLE_EINTR(close(fd)); return false; } // An existing file was opened, so its size should not be fixed. fix_size = false; } fp = NULL; if (fd >= 0) { // "a+" is always appropriate: if it's a new file, a+ is similar to w+. fp = fdopen(fd, "a+"); } } if (fp && fix_size) { struct stat stat; if (fstat(fileno(fp), &stat) != 0) { file_util::CloseFile(fp); return false; } const size_t current_size = stat.st_size; if (current_size != options.size) { if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) { file_util::CloseFile(fp); return false; } } requested_size_ = options.size; } if (fp == NULL) { #if !defined(OS_MACOSX) PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; FilePath dir = path.DirName(); if (access(dir.value().c_str(), W_OK | X_OK) < 0) { PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value(); if (dir.value() == "/dev/shm") { LOG(FATAL) << "This is frequently caused by incorrect permissions on " << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix."; } } #else PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; #endif return false; } return PrepareMapFile(fp); }
171,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(get_html_translation_table) { long all = HTML_SPECIALCHARS, flags = ENT_COMPAT; int doctype; entity_table_opt entity_table; const enc_to_uni *to_uni_table = NULL; char *charset_hint = NULL; int charset_hint_len; enum entity_charset charset; /* in this function we have to jump through some loops because we're * getting the translated table from data structures that are optimized for * random access, not traversal */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &all, &flags, &charset_hint, &charset_hint_len) == FAILURE) { return; } charset = determine_charset(charset_hint TSRMLS_CC); doctype = flags & ENT_HTML_DOC_TYPE_MASK; LIMIT_ALL(all, doctype, charset); array_init(return_value); entity_table = determine_entity_table(all, doctype); if (all && !CHARSET_UNICODE_COMPAT(charset)) { to_uni_table = enc_to_uni_index[charset]; } if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */ const entity_stage1_row *ms_table = entity_table.ms_table; if (CHARSET_UNICODE_COMPAT(charset)) { unsigned i, j, k, max_i, max_j, max_k; /* no mapping to unicode required */ if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */ max_i = 1; max_j = 4; max_k = 64; } else { max_i = 0x1E; max_j = 64; max_k = 64; } for (i = 0; i < max_i; i++) { if (ms_table[i] == empty_stage2_table) continue; for (j = 0; j < max_j; j++) { if (ms_table[i][j] == empty_stage3_table) continue; for (k = 0; k < max_k; k++) { const entity_stage3_row *r = &ms_table[i][j][k]; unsigned code; if (r->data.ent.entity == NULL) continue; code = ENT_CODE_POINT_FROM_STAGES(i, j, k); if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; write_s3row_data(r, code, charset, return_value); } } } } else { /* we have to iterate through the set of code points for this * encoding and map them to unicode code points */ unsigned i; for (i = 0; i <= 0xFF; i++) { const entity_stage3_row *r; unsigned uni_cp; /* can be done before mapping, they're invariant */ if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; map_to_unicode(i, to_uni_table, &uni_cp); r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)]; if (r->data.ent.entity == NULL) continue; write_s3row_data(r, i, charset, return_value); } } } else { /* we could use sizeof(stage3_table_be_apos_00000) as well */ unsigned j, numelems = sizeof(stage3_table_be_noapos_00000) / sizeof(*stage3_table_be_noapos_00000); for (j = 0; j < numelems; j++) { const entity_stage3_row *r = &entity_table.table[j]; if (r->data.ent.entity == NULL) continue; if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; /* charset is indifferent, used cs_8859_1 for efficiency */ write_s3row_data(r, j, cs_8859_1, return_value); } } } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
PHP_FUNCTION(get_html_translation_table) { long all = HTML_SPECIALCHARS, flags = ENT_COMPAT; int doctype; entity_table_opt entity_table; const enc_to_uni *to_uni_table = NULL; char *charset_hint = NULL; int charset_hint_len; enum entity_charset charset; /* in this function we have to jump through some loops because we're * getting the translated table from data structures that are optimized for * random access, not traversal */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &all, &flags, &charset_hint, &charset_hint_len) == FAILURE) { return; } charset = determine_charset(charset_hint TSRMLS_CC); doctype = flags & ENT_HTML_DOC_TYPE_MASK; LIMIT_ALL(all, doctype, charset); array_init(return_value); entity_table = determine_entity_table(all, doctype); if (all && !CHARSET_UNICODE_COMPAT(charset)) { to_uni_table = enc_to_uni_index[charset]; } if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */ const entity_stage1_row *ms_table = entity_table.ms_table; if (CHARSET_UNICODE_COMPAT(charset)) { unsigned i, j, k, max_i, max_j, max_k; /* no mapping to unicode required */ if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */ max_i = 1; max_j = 4; max_k = 64; } else { max_i = 0x1E; max_j = 64; max_k = 64; } for (i = 0; i < max_i; i++) { if (ms_table[i] == empty_stage2_table) continue; for (j = 0; j < max_j; j++) { if (ms_table[i][j] == empty_stage3_table) continue; for (k = 0; k < max_k; k++) { const entity_stage3_row *r = &ms_table[i][j][k]; unsigned code; if (r->data.ent.entity == NULL) continue; code = ENT_CODE_POINT_FROM_STAGES(i, j, k); if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; write_s3row_data(r, code, charset, return_value); } } } } else { /* we have to iterate through the set of code points for this * encoding and map them to unicode code points */ unsigned i; for (i = 0; i <= 0xFF; i++) { const entity_stage3_row *r; unsigned uni_cp; /* can be done before mapping, they're invariant */ if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; map_to_unicode(i, to_uni_table, &uni_cp); r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)]; if (r->data.ent.entity == NULL) continue; write_s3row_data(r, i, charset, return_value); } } } else { /* we could use sizeof(stage3_table_be_apos_00000) as well */ unsigned j, numelems = sizeof(stage3_table_be_noapos_00000) / sizeof(*stage3_table_be_noapos_00000); for (j = 0; j < numelems; j++) { const entity_stage3_row *r = &entity_table.table[j]; if (r->data.ent.entity == NULL) continue; if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; /* charset is indifferent, used cs_8859_1 for efficiency */ write_s3row_data(r, j, cs_8859_1, return_value); } } }
167,168
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> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[]) { v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> method; if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) { fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(scriptState->isolate()); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(method), scriptState->getExecutionContext(), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) { rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[]) { v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> method; if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) { fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(scriptState->isolate()); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(method), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) { rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; }
172,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: int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 new_size, u32 min_type) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_file_extent_item *fi; struct btrfs_key key; struct btrfs_key found_key; u64 extent_start = 0; u64 extent_num_bytes = 0; u64 extent_offset = 0; u64 item_end = 0; u64 last_size = new_size; u32 found_type = (u8)-1; int found_extent; int del_item; int pending_del_nr = 0; int pending_del_slot = 0; int extent_type = -1; int ret; int err = 0; u64 ino = btrfs_ino(inode); u64 bytes_deleted = 0; bool be_nice = 0; bool should_throttle = 0; bool should_end = 0; BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); /* * for non-free space inodes and ref cows, we want to back off from * time to time */ if (!btrfs_is_free_space_inode(inode) && test_bit(BTRFS_ROOT_REF_COWS, &root->state)) be_nice = 1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = -1; /* * We want to drop from the next block forward in case this new size is * not block aligned since we will be keeping the last block of the * extent just the way it is. */ if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root) btrfs_drop_extent_cache(inode, ALIGN(new_size, root->sectorsize), (u64)-1, 0); /* * This function is also used to drop the items in the log tree before * we relog the inode, so if root != BTRFS_I(inode)->root, it means * it is used to drop the loged items. So we shouldn't kill the delayed * items. */ if (min_type == 0 && root == BTRFS_I(inode)->root) btrfs_kill_delayed_inode_items(inode); key.objectid = ino; key.offset = (u64)-1; key.type = (u8)-1; search_again: /* * with a 16K leaf size and 128MB extents, you can actually queue * up a huge file in a single leaf. Most of the time that * bytes_deleted is > 0, it will be huge by the time we get here */ if (be_nice && bytes_deleted > 32 * 1024 * 1024) { if (btrfs_should_end_transaction(trans, root)) { err = -EAGAIN; goto error; } } path->leave_spinning = 1; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) { err = ret; goto out; } if (ret > 0) { /* there are no items in the tree for us to truncate, we're * done */ if (path->slots[0] == 0) goto out; path->slots[0]--; } while (1) { fi = NULL; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = found_key.type; if (found_key.objectid != ino) break; if (found_type < min_type) break; item_end = found_key.offset; if (found_type == BTRFS_EXTENT_DATA_KEY) { fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type != BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_num_bytes(leaf, fi); } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_inline_len(leaf, path->slots[0], fi); } item_end--; } if (found_type > min_type) { del_item = 1; } else { if (item_end < new_size) break; if (found_key.offset >= new_size) del_item = 1; else del_item = 0; } found_extent = 0; /* FIXME, shrink the extent if the ref count is only 1 */ if (found_type != BTRFS_EXTENT_DATA_KEY) goto delete; if (del_item) last_size = found_key.offset; else last_size = new_size; if (extent_type != BTRFS_FILE_EXTENT_INLINE) { u64 num_dec; extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); if (!del_item) { u64 orig_num_bytes = btrfs_file_extent_num_bytes(leaf, fi); extent_num_bytes = ALIGN(new_size - found_key.offset, root->sectorsize); btrfs_set_file_extent_num_bytes(leaf, fi, extent_num_bytes); num_dec = (orig_num_bytes - extent_num_bytes); if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) && extent_start != 0) inode_sub_bytes(inode, num_dec); btrfs_mark_buffer_dirty(leaf); } else { extent_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); extent_offset = found_key.offset - btrfs_file_extent_offset(leaf, fi); /* FIXME blocksize != 4096 */ num_dec = btrfs_file_extent_num_bytes(leaf, fi); if (extent_start != 0) { found_extent = 1; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, num_dec); } } } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { /* * we can't truncate inline items that have had * special encodings */ if (!del_item && btrfs_file_extent_compression(leaf, fi) == 0 && btrfs_file_extent_encryption(leaf, fi) == 0 && btrfs_file_extent_other_encoding(leaf, fi) == 0) { u32 size = new_size - found_key.offset; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, item_end + 1 - new_size); /* * update the ram bytes to properly reflect * the new size of our item */ btrfs_set_file_extent_ram_bytes(leaf, fi, size); size = btrfs_file_extent_calc_inline_size(size); btrfs_truncate_item(root, path, size, 1); } else if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) { inode_sub_bytes(inode, item_end + 1 - found_key.offset); } } delete: if (del_item) { if (!pending_del_nr) { /* no pending yet, add ourselves */ pending_del_slot = path->slots[0]; pending_del_nr = 1; } else if (pending_del_nr && path->slots[0] + 1 == pending_del_slot) { /* hop on the pending chunk */ pending_del_nr++; pending_del_slot = path->slots[0]; } else { BUG(); } } else { break; } should_throttle = 0; if (found_extent && (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root)) { btrfs_set_path_blocking(path); bytes_deleted += extent_num_bytes; ret = btrfs_free_extent(trans, root, extent_start, extent_num_bytes, 0, btrfs_header_owner(leaf), ino, extent_offset, 0); BUG_ON(ret); if (btrfs_should_throttle_delayed_refs(trans, root)) btrfs_async_run_delayed_refs(root, trans->delayed_ref_updates * 2, 0); if (be_nice) { if (truncate_space_check(trans, root, extent_num_bytes)) { should_end = 1; } if (btrfs_should_throttle_delayed_refs(trans, root)) { should_throttle = 1; } } } if (found_type == BTRFS_INODE_ITEM_KEY) break; if (path->slots[0] == 0 || path->slots[0] != pending_del_slot || should_throttle || should_end) { if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } pending_del_nr = 0; } btrfs_release_path(path); if (should_throttle) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } /* * if we failed to refill our space rsv, bail out * and let the transaction restart */ if (should_end) { err = -EAGAIN; goto error; } goto search_again; } else { path->slots[0]--; } } out: if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) btrfs_abort_transaction(trans, root, ret); } error: if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) btrfs_ordered_update_i_size(inode, last_size, NULL); btrfs_free_path(path); if (be_nice && bytes_deleted > 32 * 1024 * 1024) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } return err; } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: [email protected] Signed-off-by: Filipe Manana <[email protected]> CWE ID: CWE-200
int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 new_size, u32 min_type) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_file_extent_item *fi; struct btrfs_key key; struct btrfs_key found_key; u64 extent_start = 0; u64 extent_num_bytes = 0; u64 extent_offset = 0; u64 item_end = 0; u64 last_size = new_size; u32 found_type = (u8)-1; int found_extent; int del_item; int pending_del_nr = 0; int pending_del_slot = 0; int extent_type = -1; int ret; int err = 0; u64 ino = btrfs_ino(inode); u64 bytes_deleted = 0; bool be_nice = 0; bool should_throttle = 0; bool should_end = 0; BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); /* * for non-free space inodes and ref cows, we want to back off from * time to time */ if (!btrfs_is_free_space_inode(inode) && test_bit(BTRFS_ROOT_REF_COWS, &root->state)) be_nice = 1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = -1; /* * We want to drop from the next block forward in case this new size is * not block aligned since we will be keeping the last block of the * extent just the way it is. */ if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root) btrfs_drop_extent_cache(inode, ALIGN(new_size, root->sectorsize), (u64)-1, 0); /* * This function is also used to drop the items in the log tree before * we relog the inode, so if root != BTRFS_I(inode)->root, it means * it is used to drop the loged items. So we shouldn't kill the delayed * items. */ if (min_type == 0 && root == BTRFS_I(inode)->root) btrfs_kill_delayed_inode_items(inode); key.objectid = ino; key.offset = (u64)-1; key.type = (u8)-1; search_again: /* * with a 16K leaf size and 128MB extents, you can actually queue * up a huge file in a single leaf. Most of the time that * bytes_deleted is > 0, it will be huge by the time we get here */ if (be_nice && bytes_deleted > 32 * 1024 * 1024) { if (btrfs_should_end_transaction(trans, root)) { err = -EAGAIN; goto error; } } path->leave_spinning = 1; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) { err = ret; goto out; } if (ret > 0) { /* there are no items in the tree for us to truncate, we're * done */ if (path->slots[0] == 0) goto out; path->slots[0]--; } while (1) { fi = NULL; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = found_key.type; if (found_key.objectid != ino) break; if (found_type < min_type) break; item_end = found_key.offset; if (found_type == BTRFS_EXTENT_DATA_KEY) { fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type != BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_num_bytes(leaf, fi); } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_inline_len(leaf, path->slots[0], fi); } item_end--; } if (found_type > min_type) { del_item = 1; } else { if (item_end < new_size) break; if (found_key.offset >= new_size) del_item = 1; else del_item = 0; } found_extent = 0; /* FIXME, shrink the extent if the ref count is only 1 */ if (found_type != BTRFS_EXTENT_DATA_KEY) goto delete; if (del_item) last_size = found_key.offset; else last_size = new_size; if (extent_type != BTRFS_FILE_EXTENT_INLINE) { u64 num_dec; extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); if (!del_item) { u64 orig_num_bytes = btrfs_file_extent_num_bytes(leaf, fi); extent_num_bytes = ALIGN(new_size - found_key.offset, root->sectorsize); btrfs_set_file_extent_num_bytes(leaf, fi, extent_num_bytes); num_dec = (orig_num_bytes - extent_num_bytes); if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) && extent_start != 0) inode_sub_bytes(inode, num_dec); btrfs_mark_buffer_dirty(leaf); } else { extent_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); extent_offset = found_key.offset - btrfs_file_extent_offset(leaf, fi); /* FIXME blocksize != 4096 */ num_dec = btrfs_file_extent_num_bytes(leaf, fi); if (extent_start != 0) { found_extent = 1; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, num_dec); } } } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { /* * we can't truncate inline items that have had * special encodings */ if (!del_item && btrfs_file_extent_encryption(leaf, fi) == 0 && btrfs_file_extent_other_encoding(leaf, fi) == 0) { /* * Need to release path in order to truncate a * compressed extent. So delete any accumulated * extent items so far. */ if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE && pending_del_nr) { err = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (err) { btrfs_abort_transaction(trans, root, err); goto error; } pending_del_nr = 0; } err = truncate_inline_extent(inode, path, &found_key, item_end, new_size); if (err) { btrfs_abort_transaction(trans, root, err); goto error; } } else if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) { inode_sub_bytes(inode, item_end + 1 - new_size); } } delete: if (del_item) { if (!pending_del_nr) { /* no pending yet, add ourselves */ pending_del_slot = path->slots[0]; pending_del_nr = 1; } else if (pending_del_nr && path->slots[0] + 1 == pending_del_slot) { /* hop on the pending chunk */ pending_del_nr++; pending_del_slot = path->slots[0]; } else { BUG(); } } else { break; } should_throttle = 0; if (found_extent && (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root)) { btrfs_set_path_blocking(path); bytes_deleted += extent_num_bytes; ret = btrfs_free_extent(trans, root, extent_start, extent_num_bytes, 0, btrfs_header_owner(leaf), ino, extent_offset, 0); BUG_ON(ret); if (btrfs_should_throttle_delayed_refs(trans, root)) btrfs_async_run_delayed_refs(root, trans->delayed_ref_updates * 2, 0); if (be_nice) { if (truncate_space_check(trans, root, extent_num_bytes)) { should_end = 1; } if (btrfs_should_throttle_delayed_refs(trans, root)) { should_throttle = 1; } } } if (found_type == BTRFS_INODE_ITEM_KEY) break; if (path->slots[0] == 0 || path->slots[0] != pending_del_slot || should_throttle || should_end) { if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } pending_del_nr = 0; } btrfs_release_path(path); if (should_throttle) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } /* * if we failed to refill our space rsv, bail out * and let the transaction restart */ if (should_end) { err = -EAGAIN; goto error; } goto search_again; } else { path->slots[0]--; } } out: if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) btrfs_abort_transaction(trans, root, ret); } error: if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) btrfs_ordered_update_i_size(inode, last_size, NULL); btrfs_free_path(path); if (be_nice && bytes_deleted > 32 * 1024 * 1024) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } return err; }
166,567
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: dtls1_hm_fragment_free(hm_fragment *frag) { if (frag->fragment) OPENSSL_free(frag->fragment); if (frag->reassembly) OPENSSL_free(frag->reassembly); OPENSSL_free(frag); int curr_mtu; unsigned int len, frag_off, mac_size, blocksize; /* AHA! Figure out the MTU, and stick to the right size */ if (s->d1->mtu < dtls1_min_mtu() && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) { s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); /* I've seen the kernel return bogus numbers when it doesn't know * (initial write), so just make sure we have a reasonable number */ if (s->d1->mtu < dtls1_min_mtu()) { s->d1->mtu = 0; s->d1->mtu = dtls1_guess_mtu(s->d1->mtu); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, s->d1->mtu, NULL); } } #if 0 mtu = s->d1->mtu; fprintf(stderr, "using MTU = %d\n", mtu); mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s)); if ( curr_mtu > 0) mtu = curr_mtu; else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0) return ret; if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu) { ret = BIO_flush(SSL_get_wbio(s)); if ( ret <= 0) return ret; mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); } #endif OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */ if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE) OPENSSL_assert(s->init_num == (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH); if (s->write_hash) mac_size = EVP_MD_CTX_size(s->write_hash); else mac_size = 0; if (s->enc_write_ctx && (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE)) blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher); else blocksize = 0; frag_off = 0; while( s->init_num) { curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) - DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH) { /* grr.. we could get an error if MTU picked was wrong */ ret = BIO_flush(SSL_get_wbio(s)); if ( ret <= 0) return ret; curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; } if ( s->init_num > curr_mtu) len = curr_mtu; else len = s->init_num; /* XDTLS: this function is too long. split out the CCS part */ if ( type == SSL3_RT_HANDSHAKE) { if ( s->init_off != 0) { OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH); s->init_off -= DTLS1_HM_HEADER_LENGTH; s->init_num += DTLS1_HM_HEADER_LENGTH; if ( s->init_num > curr_mtu) len = curr_mtu; else len = s->init_num; } dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH); dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]); OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH); } ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off], len); if (ret < 0) { /* might need to update MTU here, but we don't know * which previous packet caused the failure -- so can't * really retransmit anything. continue as if everything * is fine and wait for an alert to handle the * retransmit */ if ( BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 ) s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); else return(-1); } else { /* bad if this assert fails, only part of the handshake * message got sent. but why would this happen? */ OPENSSL_assert(len == (unsigned int)ret); if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting) { /* should not be done for 'Hello Request's, but in that case * we'll ignore the result anyway */ unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off]; const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; int xlen; if (frag_off == 0 && s->version != DTLS1_BAD_VER) { /* reconstruct message header is if it * is being sent in single fragment */ *p++ = msg_hdr->type; l2n3(msg_hdr->msg_len,p); s2n (msg_hdr->seq,p); l2n3(0,p); l2n3(msg_hdr->msg_len,p); p -= DTLS1_HM_HEADER_LENGTH; xlen = ret; } else { p += DTLS1_HM_HEADER_LENGTH; xlen = ret - DTLS1_HM_HEADER_LENGTH; } ssl3_finish_mac(s, p, xlen); } if (ret == s->init_num) { if (s->msg_callback) s->msg_callback(1, s->version, type, s->init_buf->data, (size_t)(s->init_off + s->init_num), s, s->msg_callback_arg); s->init_off = 0; /* done writing this message */ s->init_num = 0; return(1); } s->init_off+=ret; s->init_num-=ret; frag_off += (ret -= DTLS1_HM_HEADER_LENGTH); } } return(0); } Commit Message: CWE ID: CWE-310
dtls1_hm_fragment_free(hm_fragment *frag) { if (frag->msg_header.is_ccs) { EVP_CIPHER_CTX_free(frag->msg_header.saved_retransmit_state.enc_write_ctx); EVP_MD_CTX_destroy(frag->msg_header.saved_retransmit_state.write_hash); } if (frag->fragment) OPENSSL_free(frag->fragment); if (frag->reassembly) OPENSSL_free(frag->reassembly); OPENSSL_free(frag); int curr_mtu; unsigned int len, frag_off, mac_size, blocksize; /* AHA! Figure out the MTU, and stick to the right size */ if (s->d1->mtu < dtls1_min_mtu() && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) { s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); /* I've seen the kernel return bogus numbers when it doesn't know * (initial write), so just make sure we have a reasonable number */ if (s->d1->mtu < dtls1_min_mtu()) { s->d1->mtu = 0; s->d1->mtu = dtls1_guess_mtu(s->d1->mtu); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, s->d1->mtu, NULL); } } #if 0 mtu = s->d1->mtu; fprintf(stderr, "using MTU = %d\n", mtu); mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s)); if ( curr_mtu > 0) mtu = curr_mtu; else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0) return ret; if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu) { ret = BIO_flush(SSL_get_wbio(s)); if ( ret <= 0) return ret; mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); } #endif OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */ if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE) OPENSSL_assert(s->init_num == (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH); if (s->write_hash) mac_size = EVP_MD_CTX_size(s->write_hash); else mac_size = 0; if (s->enc_write_ctx && (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE)) blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher); else blocksize = 0; frag_off = 0; while( s->init_num) { curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) - DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH) { /* grr.. we could get an error if MTU picked was wrong */ ret = BIO_flush(SSL_get_wbio(s)); if ( ret <= 0) return ret; curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; } if ( s->init_num > curr_mtu) len = curr_mtu; else len = s->init_num; /* XDTLS: this function is too long. split out the CCS part */ if ( type == SSL3_RT_HANDSHAKE) { if ( s->init_off != 0) { OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH); s->init_off -= DTLS1_HM_HEADER_LENGTH; s->init_num += DTLS1_HM_HEADER_LENGTH; if ( s->init_num > curr_mtu) len = curr_mtu; else len = s->init_num; } dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH); dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]); OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH); } ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off], len); if (ret < 0) { /* might need to update MTU here, but we don't know * which previous packet caused the failure -- so can't * really retransmit anything. continue as if everything * is fine and wait for an alert to handle the * retransmit */ if ( BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 ) s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); else return(-1); } else { /* bad if this assert fails, only part of the handshake * message got sent. but why would this happen? */ OPENSSL_assert(len == (unsigned int)ret); if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting) { /* should not be done for 'Hello Request's, but in that case * we'll ignore the result anyway */ unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off]; const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; int xlen; if (frag_off == 0 && s->version != DTLS1_BAD_VER) { /* reconstruct message header is if it * is being sent in single fragment */ *p++ = msg_hdr->type; l2n3(msg_hdr->msg_len,p); s2n (msg_hdr->seq,p); l2n3(0,p); l2n3(msg_hdr->msg_len,p); p -= DTLS1_HM_HEADER_LENGTH; xlen = ret; } else { p += DTLS1_HM_HEADER_LENGTH; xlen = ret - DTLS1_HM_HEADER_LENGTH; } ssl3_finish_mac(s, p, xlen); } if (ret == s->init_num) { if (s->msg_callback) s->msg_callback(1, s->version, type, s->init_buf->data, (size_t)(s->init_off + s->init_num), s, s->msg_callback_arg); s->init_off = 0; /* done writing this message */ s->init_num = 0; return(1); } s->init_off+=ret; s->init_num-=ret; frag_off += (ret -= DTLS1_HM_HEADER_LENGTH); } } return(0); }
165,334
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 AddChunk(const TransformPaintPropertyNode* t, const ClipPaintPropertyNode* c, const EffectPaintPropertyNode* e, const FloatRect& bounds = FloatRect(0, 0, 100, 100)) { auto record = sk_make_sp<PaintRecord>(); record->push<cc::DrawRectOp>(bounds, cc::PaintFlags()); AddChunk(std::move(record), t, c, e, bounds); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void AddChunk(const TransformPaintPropertyNode* t, void AddChunk(const TransformPaintPropertyNode& t, const ClipPaintPropertyNode& c, const EffectPaintPropertyNode& e, const FloatRect& bounds = FloatRect(0, 0, 100, 100)) { auto record = sk_make_sp<PaintRecord>(); record->push<cc::DrawRectOp>(bounds, cc::PaintFlags()); AddChunk(std::move(record), t, c, e, bounds); }
171,825
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 check_line_charstring(void) { char *p = line; while (isspace(*p)) p++; return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p')); } Commit Message: Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char. CWE ID: CWE-119
static int check_line_charstring(void) { char *p = line; while (isspace((unsigned char) *p)) p++; return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p')); }
166,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas, const cc::PaintFlags& flags, const FloatRect& dst_rect, const FloatRect& src_rect, RespectImageOrientationEnum, ImageClampingMode clamp_mode, ImageDecodingMode) { StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode, PaintImageForCurrentFrame()); } 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 UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas, const cc::PaintFlags& flags, const FloatRect& dst_rect, const FloatRect& src_rect, RespectImageOrientationEnum, ImageClampingMode clamp_mode, ImageDecodingMode) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode, PaintImageForCurrentFrame()); }
172,600
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 ExtensionDevToolsClientHost::AgentHostClosed( DevToolsAgentHost* agent_host) { DCHECK(agent_host == agent_host_.get()); SendDetachedEvent(); delete this; } 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
void ExtensionDevToolsClientHost::AgentHostClosed( DevToolsAgentHost* agent_host) { DCHECK(agent_host == agent_host_.get()); RespondDetachedToPendingRequests(); SendDetachedEvent(); delete this; }
173,236
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: char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); } Commit Message: CWE ID: CWE-787
char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *(unsigned char *)ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }
164,745
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 AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { VLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (base::RandDouble() > upload_rate) { VLOG(1) << "AutofillDownloadManager: Upload request is ignored."; return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses BUG=84693 TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest Review URL: http://codereview.chromium.org/6969090 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { VLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (form.upload_required() == UPLOAD_NOT_REQUIRED || (form.upload_required() == USE_UPLOAD_RATES && base::RandDouble() > upload_rate)) { VLOG(1) << "AutofillDownloadManager: Upload request is ignored."; return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); }
170,446
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 RunAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1u, max_error) << "Error: 4x4 FHT/IHT has an individual round trip error > 1"; EXPECT_GE(count_test_block , total_error) << "Error: 4x4 FHT/IHT has average round trip error > 1 per block"; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunAccuracyCheck() { void RunAccuracyCheck(int limit) { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); #endif for (int j = 0; j < kNumCoeffs; ++j) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; test_input_block[j] = src16[j] - dst16[j]; #endif } } ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < kNumCoeffs; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const uint32_t diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else ASSERT_EQ(VPX_BITS_8, bit_depth_); const uint32_t diff = dst[j] - src[j]; #endif const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(static_cast<uint32_t>(limit), max_error) << "Error: 4x4 FHT/IHT has an individual round trip error > " << limit; EXPECT_GE(count_test_block * limit, total_error) << "Error: 4x4 FHT/IHT has average round trip error > " << limit << " per block"; }
174,547
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual bool Speak( const std::string& utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume) { error_ = kNotSupportedError; return false; } 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
virtual bool Speak( int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { error_ = kNotSupportedError; return false; }
170,400
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 perf_swevent_event(struct perf_event *event, u64 nr, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; local64_add(nr, &event->count); if (!regs) return; if (!is_sampling_event(event)) return; if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) return perf_swevent_overflow(event, 1, nmi, data, regs); if (local64_add_negative(nr, &hwc->period_left)) return; perf_swevent_overflow(event, 0, nmi, data, regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static void perf_swevent_event(struct perf_event *event, u64 nr, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; local64_add(nr, &event->count); if (!regs) return; if (!is_sampling_event(event)) return; if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) return perf_swevent_overflow(event, 1, data, regs); if (local64_add_negative(nr, &hwc->period_left)) return; perf_swevent_overflow(event, 0, data, regs); }
165,837
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 WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } Commit Message: fix deinterlacing for small pictures fixes #12 CWE ID: CWE-119
static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } while(context->pass > 0 && context->pass < 4 && context->curY >= p->height) { switch(++context->pass) { case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY = i->posY + 4; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY = i->posY + 2; break; case 4: /* 4th pass : every odd row */ context->curY = i->posY + 1; break; } } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } }
169,511
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: kadm5_create_principal_3(void *server_handle, kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_policy_ent_rec polent; krb5_boolean have_polent = FALSE; krb5_timestamp now; krb5_tl_data *tl_data_tail; unsigned int ret; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); /* * Argument sanity checking, and opening up the DB */ if (entry == NULL) return EINVAL; if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || (mask & KADM5_FAIL_AUTH_COUNT)) return KADM5_BAD_MASK; if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && entry->policy == NULL) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; /* * Check to see if the principal exists */ ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); switch(ret) { case KADM5_UNK_PRINC: break; case 0: kdb_free_entry(handle, kdb, &adb); return KADM5_DUP; default: return ret; } kdb = calloc(1, sizeof(*kdb)); if (kdb == NULL) return ENOMEM; memset(&adb, 0, sizeof(osa_princ_ent_rec)); /* * If a policy was specified, load it. * If we can not find the one specified return an error */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &polent, &have_polent); if (ret) goto cleanup; } if (password) { ret = passwd_check(handle, password, have_polent ? &polent : NULL, entry->principal); if (ret) goto cleanup; } /* * Start populating the various DB fields, using the * "defaults" for fields that were not specified by the * mask. */ if ((ret = krb5_timeofday(handle->context, &now))) goto cleanup; kdb->magic = KRB5_KDB_MAGIC_NUMBER; kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; else kdb->attributes = handle->params.flags; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; else kdb->max_life = handle->params.max_life; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; else kdb->max_renewable_life = handle->params.max_rlife; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; else kdb->expiration = handle->params.expiration; kdb->pw_expiration = 0; if (have_polent) { if(polent.pw_max_life) kdb->pw_expiration = ts_incr(now, polent.pw_max_life); else kdb->pw_expiration = 0; } if ((mask & KADM5_PW_EXPIRATION)) kdb->pw_expiration = entry->pw_expiration; kdb->last_success = 0; kdb->last_failed = 0; kdb->fail_auth_count = 0; /* this is kind of gross, but in order to free the tl data, I need to free the entire kdb entry, and that will try to free the principal. */ ret = krb5_copy_principal(handle->context, entry->principal, &kdb->princ); if (ret) goto cleanup; if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto cleanup; if (mask & KADM5_TL_DATA) { /* splice entry->tl_data onto the front of kdb->tl_data */ for (tl_data_tail = entry->tl_data; tl_data_tail; tl_data_tail = tl_data_tail->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); if( ret ) goto cleanup; } } /* * We need to have setup the TL data, so we have strings, so we can * check enctype policy, which is why we check/initialize ks_tuple * this late. */ ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto cleanup; /* initialize the keys */ ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto cleanup; if (mask & KADM5_KEY_DATA) { /* The client requested no keys for this principal. */ assert(entry->n_key_data == 0); } else if (password) { ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, (mask & KADM5_KVNO)?entry->kvno:1, FALSE, kdb); } else { /* Null password means create with random key (new in 1.8). */ ret = krb5_dbe_crk(handle->context, &master_keyblock, new_ks_tuple, new_n_ks_tuple, FALSE, kdb); } if (ret) goto cleanup; /* Record the master key VNO used to encrypt this entry's keys */ ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto cleanup; ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto cleanup; /* populate the admin-server-specific fields. In the OV server, this used to be in a separate database. Since there's already marshalling code for the admin fields, to keep things simple, I'm going to keep it, and make all the admin stuff occupy a single tl_data record, */ adb.admin_history_kvno = INITIAL_HIST_KVNO; if (mask & KADM5_POLICY) { adb.aux_attributes = KADM5_POLICY; /* this does *not* need to be strdup'ed, because adb is xdr */ /* encoded in osa_adb_create_princ, and not ever freed */ adb.policy = entry->policy; } /* In all cases key and the principal data is set, let the database provider know */ kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; /* store the new db entry */ ret = kdb_put_entry(handle, kdb, &adb); (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); cleanup: free(new_ks_tuple); krb5_db_free_principal(handle->context, kdb); if (have_polent) (void) kadm5_free_policy_ent(handle->lhandle, &polent); return ret; } Commit Message: Fix flaws in LDAP DN checking KDB_TL_USER_INFO tl-data is intended to be internal to the LDAP KDB module, and not used in disk or wire principal entries. Prevent kadmin clients from sending KDB_TL_USER_INFO tl-data by giving it a type number less than 256 and filtering out type numbers less than 256 in kadm5_create_principal_3(). (We already filter out low type numbers in kadm5_modify_principal()). In the LDAP KDB module, if containerdn and linkdn are both specified in a put_principal operation, check both linkdn and the computed standalone_principal_dn for container membership. To that end, factor out the checks into helper functions and call them on all applicable client-influenced DNs. CVE-2018-5729: In MIT krb5 1.6 or later, an authenticated kadmin user with permission to add principals to an LDAP Kerberos database can cause a null dereference in kadmind, or circumvent a DN container check, by supplying tagged data intended to be internal to the database module. Thanks to Sharwan Ram and Pooja Anil for discovering the potential null dereference. CVE-2018-5730: In MIT krb5 1.6 or later, an authenticated kadmin user with permission to add principals to an LDAP Kerberos database can circumvent a DN containership check by supplying both a "linkdn" and "containerdn" database argument, or by supplying a DN string which is a left extension of a container DN string but is not hierarchically within the container DN. ticket: 8643 (new) tags: pullup target_version: 1.16-next target_version: 1.15-next CWE ID: CWE-90
kadm5_create_principal_3(void *server_handle, kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_policy_ent_rec polent; krb5_boolean have_polent = FALSE; krb5_timestamp now; krb5_tl_data *tl_data_tail; unsigned int ret; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); /* * Argument sanity checking, and opening up the DB */ if (entry == NULL) return EINVAL; if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || (mask & KADM5_FAIL_AUTH_COUNT)) return KADM5_BAD_MASK; if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && entry->policy == NULL) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if (mask & KADM5_TL_DATA) { for (tl_data_tail = entry->tl_data; tl_data_tail != NULL; tl_data_tail = tl_data_tail->tl_data_next) { if (tl_data_tail->tl_data_type < 256) return KADM5_BAD_TL_TYPE; } } /* * Check to see if the principal exists */ ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); switch(ret) { case KADM5_UNK_PRINC: break; case 0: kdb_free_entry(handle, kdb, &adb); return KADM5_DUP; default: return ret; } kdb = calloc(1, sizeof(*kdb)); if (kdb == NULL) return ENOMEM; memset(&adb, 0, sizeof(osa_princ_ent_rec)); /* * If a policy was specified, load it. * If we can not find the one specified return an error */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &polent, &have_polent); if (ret) goto cleanup; } if (password) { ret = passwd_check(handle, password, have_polent ? &polent : NULL, entry->principal); if (ret) goto cleanup; } /* * Start populating the various DB fields, using the * "defaults" for fields that were not specified by the * mask. */ if ((ret = krb5_timeofday(handle->context, &now))) goto cleanup; kdb->magic = KRB5_KDB_MAGIC_NUMBER; kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; else kdb->attributes = handle->params.flags; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; else kdb->max_life = handle->params.max_life; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; else kdb->max_renewable_life = handle->params.max_rlife; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; else kdb->expiration = handle->params.expiration; kdb->pw_expiration = 0; if (have_polent) { if(polent.pw_max_life) kdb->pw_expiration = ts_incr(now, polent.pw_max_life); else kdb->pw_expiration = 0; } if ((mask & KADM5_PW_EXPIRATION)) kdb->pw_expiration = entry->pw_expiration; kdb->last_success = 0; kdb->last_failed = 0; kdb->fail_auth_count = 0; /* this is kind of gross, but in order to free the tl data, I need to free the entire kdb entry, and that will try to free the principal. */ ret = krb5_copy_principal(handle->context, entry->principal, &kdb->princ); if (ret) goto cleanup; if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto cleanup; if (mask & KADM5_TL_DATA) { /* splice entry->tl_data onto the front of kdb->tl_data */ for (tl_data_tail = entry->tl_data; tl_data_tail; tl_data_tail = tl_data_tail->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); if( ret ) goto cleanup; } } /* * We need to have setup the TL data, so we have strings, so we can * check enctype policy, which is why we check/initialize ks_tuple * this late. */ ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto cleanup; /* initialize the keys */ ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto cleanup; if (mask & KADM5_KEY_DATA) { /* The client requested no keys for this principal. */ assert(entry->n_key_data == 0); } else if (password) { ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, (mask & KADM5_KVNO)?entry->kvno:1, FALSE, kdb); } else { /* Null password means create with random key (new in 1.8). */ ret = krb5_dbe_crk(handle->context, &master_keyblock, new_ks_tuple, new_n_ks_tuple, FALSE, kdb); } if (ret) goto cleanup; /* Record the master key VNO used to encrypt this entry's keys */ ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto cleanup; ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto cleanup; /* populate the admin-server-specific fields. In the OV server, this used to be in a separate database. Since there's already marshalling code for the admin fields, to keep things simple, I'm going to keep it, and make all the admin stuff occupy a single tl_data record, */ adb.admin_history_kvno = INITIAL_HIST_KVNO; if (mask & KADM5_POLICY) { adb.aux_attributes = KADM5_POLICY; /* this does *not* need to be strdup'ed, because adb is xdr */ /* encoded in osa_adb_create_princ, and not ever freed */ adb.policy = entry->policy; } /* In all cases key and the principal data is set, let the database provider know */ kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; /* store the new db entry */ ret = kdb_put_entry(handle, kdb, &adb); (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); cleanup: free(new_ks_tuple); krb5_db_free_principal(handle->context, kdb); if (have_polent) (void) kadm5_free_policy_ent(handle->lhandle, &polent); return ret; }
169,350
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 inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct fib_result res = {}; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; u32 table_id = RT_TABLE_MAIN; kuid_t uid; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); /* Bugfix: need to give ip_route_input enough of an IP header to * not gag. */ ip_hdr(skb)->protocol = IPPROTO_UDP; ip_hdr(skb)->saddr = src; ip_hdr(skb)->daddr = dst; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_free; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = rt->rt_table_id; if (rtm->rtm_flags & RTM_F_FIB_MATCH) err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); else err = rt_fill_info(net, dst, src, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); if (err < 0) goto errout_free; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: rcu_read_unlock(); kfree_skb(skb); goto errout; } Commit Message: net: check and errout if res->fi is NULL when RTM_F_FIB_MATCH is set Syzkaller hit 'general protection fault in fib_dump_info' bug on commit 4.13-rc5.. Guilty file: net/ipv4/fib_semantics.c kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN Modules linked in: CPU: 0 PID: 2808 Comm: syz-executor0 Not tainted 4.13.0-rc5 #1 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 task: ffff880078562700 task.stack: ffff880078110000 RIP: 0010:fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314 RSP: 0018:ffff880078117010 EFLAGS: 00010206 RAX: dffffc0000000000 RBX: 00000000000000fe RCX: 0000000000000002 RDX: 0000000000000006 RSI: ffff880078117084 RDI: 0000000000000030 RBP: ffff880078117268 R08: 000000000000000c R09: ffff8800780d80c8 R10: 0000000058d629b4 R11: 0000000067fce681 R12: 0000000000000000 R13: ffff8800784bd540 R14: ffff8800780d80b5 R15: ffff8800780d80a4 FS: 00000000022fa940(0000) GS:ffff88007fc00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00000000004387d0 CR3: 0000000079135000 CR4: 00000000000006f0 Call Trace: inet_rtm_getroute+0xc89/0x1f50 net/ipv4/route.c:2766 rtnetlink_rcv_msg+0x288/0x680 net/core/rtnetlink.c:4217 netlink_rcv_skb+0x340/0x470 net/netlink/af_netlink.c:2397 rtnetlink_rcv+0x28/0x30 net/core/rtnetlink.c:4223 netlink_unicast_kernel net/netlink/af_netlink.c:1265 [inline] netlink_unicast+0x4c4/0x6e0 net/netlink/af_netlink.c:1291 netlink_sendmsg+0x8c4/0xca0 net/netlink/af_netlink.c:1854 sock_sendmsg_nosec net/socket.c:633 [inline] sock_sendmsg+0xca/0x110 net/socket.c:643 ___sys_sendmsg+0x779/0x8d0 net/socket.c:2035 __sys_sendmsg+0xd1/0x170 net/socket.c:2069 SYSC_sendmsg net/socket.c:2080 [inline] SyS_sendmsg+0x2d/0x50 net/socket.c:2076 entry_SYSCALL_64_fastpath+0x1a/0xa5 RIP: 0033:0x4512e9 RSP: 002b:00007ffc75584cc8 EFLAGS: 00000216 ORIG_RAX: 000000000000002e RAX: ffffffffffffffda RBX: 0000000000000002 RCX: 00000000004512e9 RDX: 0000000000000000 RSI: 0000000020f2cfc8 RDI: 0000000000000003 RBP: 000000000000000e R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000216 R12: fffffffffffffffe R13: 0000000000718000 R14: 0000000020c44ff0 R15: 0000000000000000 Code: 00 0f b6 8d ec fd ff ff 48 8b 85 f0 fd ff ff 88 48 17 48 8b 45 28 48 8d 78 30 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <0f> b6 04 02 84 c0 74 08 3c 03 0f 8e cb 0c 00 00 48 8b 45 28 44 RIP: fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314 RSP: ffff880078117010 ---[ end trace 254a7af28348f88b ]--- This patch adds a res->fi NULL check. example run: $ip route get 0.0.0.0 iif virt1-0 broadcast 0.0.0.0 dev lo cache <local,brd> iif virt1-0 $ip route get 0.0.0.0 iif virt1-0 fibmatch RTNETLINK answers: No route to host Reported-by: idaifish <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Fixes: b61798130f1b ("net: ipv4: RTM_GETROUTE: return matched fib result when requested") Signed-off-by: Roopa Prabhu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476
static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct fib_result res = {}; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; u32 table_id = RT_TABLE_MAIN; kuid_t uid; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); /* Bugfix: need to give ip_route_input enough of an IP header to * not gag. */ ip_hdr(skb)->protocol = IPPROTO_UDP; ip_hdr(skb)->saddr = src; ip_hdr(skb)->daddr = dst; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_free; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = rt->rt_table_id; if (rtm->rtm_flags & RTM_F_FIB_MATCH) { if (!res.fi) { err = fib_props[res.type].error; if (!err) err = -EHOSTUNREACH; goto errout_free; } err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); } else { err = rt_fill_info(net, dst, src, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); } if (err < 0) goto errout_free; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: rcu_read_unlock(); kfree_skb(skb); goto errout; }
167,806
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: SafeAlphaCompositeSolidMask_nx8x8888( CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); if (dstMask == FB_ALLONES && pDst->pDrawable->bitsPerPixel == 32 && width * height > rootless_CompositePixels_threshold && SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels) { void *srcp[2], *destp[2]; unsigned int dest_rowbytes[2]; unsigned int fn; srcp[0] = &src; srcp[1] = &src; /* null rowbytes pointer means use first value as a constant */ destp[0] = dstLine; destp[1] = dstLine; dest_rowbytes[0] = dstStride * 4; dest_rowbytes[1] = dest_rowbytes[0]; fn = RL_COMPOSITE_FUNCTION(RL_COMPOSITE_OVER, RL_DEPTH_ARGB8888, RL_DEPTH_A8, RL_DEPTH_ARGB8888); if (SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels( width, height, fn, srcp, NULL, maskLine, maskStride, destp, dest_rowbytes) == Success) { return; } } while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { } void SafeAlphaComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; CompositeFunc func = 0; Bool srcRepeat = pSrc->repeat; Bool maskRepeat = FALSE; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; int w, h, w_this, h_this; int dstDepth = pDst->pDrawable->depth; int oldFormat = pDst->format; xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; if (pMask) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; maskRepeat = pMask->repeat; maskAlphaMap = pMask->alphaMap != 0; } /* * We can use the more optimized fbpict code, but it sets bits above * the depth to zero. Temporarily adjust destination depth if needed. PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, { pDst->pDrawable->depth = 32; } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ int n; { pDst->format = PICT_a8r8g8b8; } if (!pSrc->transform && !(pMask && pMask->transform)) if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap) switch (op) { case PictOpSrc: #ifdef USE_MMX if (!pMask && pSrc->format == pDst->format && pSrc->pDrawable != pDst->pDrawable) { func = fbCompositeCopyAreammx; } #endif break; case PictOpOver: if (pMask) { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { srcRepeat = FALSE; if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = SafeAlphaCompositeSolidMask_nx8x8888; break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = fbCompositeSolidMask_nx1xn; break; } break; } } } else /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; } break; } else { /* non-repeating source, repeating mask => translucent window */ if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { if (pSrc->format == PICT_x8r8g8b8 && pDst->format == PICT_x8r8g8b8 && pMask->format == PICT_a8) { #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; #endif } } } } } else /* no mask */ { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; } break; } } else { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_r5g6b5: switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSrc_0565x0565; break; } break; case PICT_b5g6r5: switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSrc_0565x0565; break; } break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; } break; } } break; } if (!func) { /* no fast path, use the general code */ fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; return; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; } } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ if (oldFormat == PICT_x8r8g8b8) { pDst->format = PICT_a8r8g8b8; } if (!pSrc->transform && !(pMask && pMask->transform)) if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap) switch (op) { case PictOpSrc: #ifdef USE_MMX if (!pMask && pSrc->format == pDst->format && pSrc->pDrawable != pDst->pDrawable) { func = fbCompositeCopyAreammx; } #endif break; case PictOpOver: if (pMask) { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { srcRepeat = FALSE; if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = SafeAlphaCompositeSolidMask_nx8x8888; break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = fbCompositeSolidMask_nx1xn; break; } break; } } } else /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; } break; } else { /* non-repeating source, repeating mask => translucent window */ if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { if (pSrc->format == PICT_x8r8g8b8 && pDst->format == PICT_x8r8g8b8 && pMask->format == PICT_a8) { #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; #endif } } } } } else /* no mask */ { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; } break; } } else { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_r5g6b5: switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSrc_0565x0565; break; } break; case PICT_b5g6r5: switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSrc_0565x0565; break; } break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; } break; } } break; } if (!func) { /* no fast path, use the general code */ fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; return; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; } Commit Message: CWE ID: CWE-189
SafeAlphaCompositeSolidMask_nx8x8888( CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); if (dstMask == FB_ALLONES && pDst->pDrawable->bitsPerPixel == 32 && width * height > rootless_CompositePixels_threshold && SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels) { void *srcp[2], *destp[2]; unsigned int dest_rowbytes[2]; unsigned int fn; srcp[0] = &src; srcp[1] = &src; /* null rowbytes pointer means use first value as a constant */ destp[0] = dstLine; destp[1] = dstLine; dest_rowbytes[0] = dstStride * 4; dest_rowbytes[1] = dest_rowbytes[0]; fn = RL_COMPOSITE_FUNCTION(RL_COMPOSITE_OVER, RL_DEPTH_ARGB8888, RL_DEPTH_A8, RL_DEPTH_ARGB8888); if (SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels( width, height, fn, srcp, NULL, maskLine, maskStride, destp, dest_rowbytes) == Success) { return; } } while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { } void SafeAlphaComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { int oldDepth = pDst->pDrawable->depth; int oldFormat = pDst->format; /* * We can use the more optimized fbpict code, but it sets bits above * the depth to zero. Temporarily adjust destination depth if needed. PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, { pDst->pDrawable->depth = 32; } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ int n; { pDst->format = PICT_a8r8g8b8; } if (pSrc->pDrawable && pMask->pDrawable && !pSrc->transform && !pMask->transform && !pSrc->alphaMap && !pMask->alphaMap && !pMask->repeat && !pMask->componentAlpha && !pDst->alphaMap && pMask->format == PICT_a8 && pSrc->repeatType == RepeatNormal && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1 && (pDst->format == PICT_a8r8g8b8 || pDst->format == PICT_x8r8g8b8 || pDst->format == PICT_a8b8g8r8 || pDst->format == PICT_x8b8g8r8)) { fbWalkCompositeRegion (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height, TRUE /* srcRepeat */, FALSE /* maskRepeat */, SafeAlphaCompositeSolidMask_nx8x8888); } else { fbComposite (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); } pDst->pDrawable->depth = oldDepth; pDst->format = oldFormat; } } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ if (oldFormat == PICT_x8r8g8b8) { pDst->format = PICT_a8r8g8b8; } if (!pSrc->transform && !(pMask && pMask->transform)) if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap) switch (op) { case PictOpSrc: #ifdef USE_MMX if (!pMask && pSrc->format == pDst->format && pSrc->pDrawable != pDst->pDrawable) { func = fbCompositeCopyAreammx; } #endif break; case PictOpOver: if (pMask) { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { srcRepeat = FALSE; if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = SafeAlphaCompositeSolidMask_nx8x8888; break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = fbCompositeSolidMask_nx1xn; break; } break; } } } else /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; } break; } else { /* non-repeating source, repeating mask => translucent window */ if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { if (pSrc->format == PICT_x8r8g8b8 && pDst->format == PICT_x8r8g8b8 && pMask->format == PICT_a8) { #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; #endif } } } } } else /* no mask */ { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; } break; } } else { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_r5g6b5: switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSrc_0565x0565; break; } break; case PICT_b5g6r5: switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSrc_0565x0565; break; } break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; } break; } } break; } if (!func) { /* no fast path, use the general code */ fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; return; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; }
165,131
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: ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct sock *sk = sock->sk; struct tcp_splice_state tss = { .pipe = pipe, .len = len, .flags = flags, }; long timeo; ssize_t spliced; int ret; sock_rps_record_flow(sk); /* * We can't seek on a socket input */ if (unlikely(*ppos)) return -ESPIPE; ret = spliced = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); while (tss.len) { ret = __tcp_splice_read(sk, &tss); if (ret < 0) break; else if (!ret) { if (spliced) break; if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { ret = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { /* * This occurs when user tries to read * from never connected socket. */ if (!sock_flag(sk, SOCK_DONE)) ret = -ENOTCONN; break; } if (!timeo) { ret = -EAGAIN; break; } sk_wait_data(sk, &timeo, NULL); if (signal_pending(current)) { ret = sock_intr_errno(timeo); break; } continue; } tss.len -= ret; spliced += ret; if (!timeo) break; release_sock(sk); lock_sock(sk); if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current)) break; } release_sock(sk); if (spliced) return spliced; return ret; } Commit Message: tcp: avoid infinite loop in tcp_splice_read() Splicing from TCP socket is vulnerable when a packet with URG flag is received and stored into receive queue. __tcp_splice_read() returns 0, and sk_wait_data() immediately returns since there is the problematic skb in queue. This is a nice way to burn cpu (aka infinite loop) and trigger soft lockups. Again, this gem was found by syzkaller tool. Fixes: 9c55e01c0cc8 ("[TCP]: Splice receive support.") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Cc: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-835
ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct sock *sk = sock->sk; struct tcp_splice_state tss = { .pipe = pipe, .len = len, .flags = flags, }; long timeo; ssize_t spliced; int ret; sock_rps_record_flow(sk); /* * We can't seek on a socket input */ if (unlikely(*ppos)) return -ESPIPE; ret = spliced = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); while (tss.len) { ret = __tcp_splice_read(sk, &tss); if (ret < 0) break; else if (!ret) { if (spliced) break; if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { ret = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { /* * This occurs when user tries to read * from never connected socket. */ if (!sock_flag(sk, SOCK_DONE)) ret = -ENOTCONN; break; } if (!timeo) { ret = -EAGAIN; break; } /* if __tcp_splice_read() got nothing while we have * an skb in receive queue, we do not want to loop. * This might happen with URG data. */ if (!skb_queue_empty(&sk->sk_receive_queue)) break; sk_wait_data(sk, &timeo, NULL); if (signal_pending(current)) { ret = sock_intr_errno(timeo); break; } continue; } tss.len -= ret; spliced += ret; if (!timeo) break; release_sock(sk); lock_sock(sk); if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current)) break; } release_sock(sk); if (spliced) return spliced; return ret; }
168,361
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 copyMono24( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] >> 8; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMono24( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] >> 8; } }
174,016
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 PaymentRequest::SatisfiesSkipUIConstraints() const { return base::FeatureList::IsEnabled(features::kWebPaymentsSingleAppUiSkip) && base::FeatureList::IsEnabled(::features::kServiceWorkerPaymentApps) && is_show_user_gesture_ && state()->is_get_all_instruments_finished() && state()->available_instruments().size() == 1 && spec()->stringified_method_data().size() == 1 && !spec()->request_shipping() && !spec()->request_payer_name() && !spec()->request_payer_phone() && !spec()->request_payer_email() && spec()->url_payment_method_identifiers().size() == 1; } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
bool PaymentRequest::SatisfiesSkipUIConstraints() const {
173,086
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: AudioRendererHostTest() : log_factory(base::MakeUnique<media::FakeAudioLogFactory>()), audio_manager_(base::MakeUnique<FakeAudioManagerWithAssociations>( base::ThreadTaskRunnerHandle::Get(), log_factory.get())), render_process_host_(&browser_context_, &auth_run_loop_) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kUseFakeDeviceForMediaStream); media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get())); host_ = new MockAudioRendererHost( &auth_run_loop_, render_process_host_.GetID(), audio_manager_.get(), &mirroring_manager_, media_stream_manager_.get(), kSalt); host_->set_peer_process_for_testing(base::Process::Current()); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
AudioRendererHostTest() : log_factory(base::MakeUnique<media::FakeAudioLogFactory>()), audio_manager_(base::MakeUnique<FakeAudioManagerWithAssociations>( base::ThreadTaskRunnerHandle::Get(), log_factory.get())), audio_system_(media::AudioSystemImpl::Create(audio_manager_.get())), render_process_host_(&browser_context_, &auth_run_loop_) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kUseFakeDeviceForMediaStream); media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get())); host_ = new MockAudioRendererHost( &auth_run_loop_, render_process_host_.GetID(), audio_manager_.get(), audio_system_.get(), &mirroring_manager_, media_stream_manager_.get(), kSalt); host_->set_peer_process_for_testing(base::Process::Current()); }
171,985
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: BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) { } 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
BlockEntry::BlockEntry(Cluster* p, long idx) : BlockEntry::~BlockEntry() {} bool BlockEntry::EOS() const { return (GetKind() == kBlockEOS); } const Cluster* BlockEntry::GetCluster() const { return m_pCluster; } long BlockEntry::GetIndex() const { return m_index; } SimpleBlock::SimpleBlock(Cluster* pCluster, long idx, long long start, long long size) : BlockEntry(pCluster, idx), m_block(start, size, 0) {} long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); } BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; } const Block* SimpleBlock::GetBlock() const { return &m_block; } BlockGroup::BlockGroup(Cluster* pCluster, long idx, long long block_start, long long block_size, long long prev, long long next, long long duration, long long discard_padding) : BlockEntry(pCluster, idx), m_block(block_start, block_size, discard_padding), m_prev(prev), m_next(next), m_duration(duration) {} long BlockGroup::Parse() { const long status = m_block.Parse(m_pCluster); if (status) return status; m_block.SetKey((m_prev > 0) && (m_next <= 0)); return 0; }
174,241
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: PageInfoUI::IdentityInfo::IdentityInfo() : identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN), safe_browsing_status(PageInfo::SAFE_BROWSING_STATUS_NONE), connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN), show_ssl_decision_revoke_button(false), show_change_password_buttons(false) {} Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311
PageInfoUI::IdentityInfo::IdentityInfo() : identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN), connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN), show_ssl_decision_revoke_button(false), show_change_password_buttons(false) {}
172,441
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 AudioRendererAlgorithm::FillBuffer( uint8* dest, int requested_frames) { DCHECK_NE(bytes_per_frame_, 0); if (playback_rate_ == 0.0f) return 0; int total_frames_rendered = 0; uint8* output_ptr = dest; while (total_frames_rendered < requested_frames) { if (index_into_window_ == window_size_) ResetWindow(); bool rendered_frame = true; if (playback_rate_ > 1.0) rendered_frame = OutputFasterPlayback(output_ptr); else if (playback_rate_ < 1.0) rendered_frame = OutputSlowerPlayback(output_ptr); else rendered_frame = OutputNormalPlayback(output_ptr); if (!rendered_frame) { needs_more_data_ = true; break; } output_ptr += bytes_per_frame_; total_frames_rendered++; } return total_frames_rendered; } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
int AudioRendererAlgorithm::FillBuffer( uint8* dest, int requested_frames) { DCHECK_NE(bytes_per_frame_, 0); if (playback_rate_ == 0.0f) return 0; int slower_step = ceil(window_size_ * playback_rate_); int faster_step = ceil(window_size_ / playback_rate_); AlignToFrameBoundary(&slower_step); AlignToFrameBoundary(&faster_step); int total_frames_rendered = 0; uint8* output_ptr = dest; while (total_frames_rendered < requested_frames) { if (index_into_window_ == window_size_) ResetWindow(); bool rendered_frame = true; if (window_size_ > faster_step) { rendered_frame = OutputFasterPlayback( output_ptr, window_size_, faster_step); } else if (slower_step < window_size_) { rendered_frame = OutputSlowerPlayback( output_ptr, slower_step, window_size_); } else { rendered_frame = OutputNormalPlayback(output_ptr); } if (!rendered_frame) { needs_more_data_ = true; break; } output_ptr += bytes_per_frame_; total_frames_rendered++; } return total_frames_rendered; }
171,527
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 init_vmcb(struct vcpu_svm *svm) { struct vmcb_control_area *control = &svm->vmcb->control; struct vmcb_save_area *save = &svm->vmcb->save; svm->vcpu.fpu_active = 1; svm->vcpu.arch.hflags = 0; set_cr_intercept(svm, INTERCEPT_CR0_READ); set_cr_intercept(svm, INTERCEPT_CR3_READ); set_cr_intercept(svm, INTERCEPT_CR4_READ); set_cr_intercept(svm, INTERCEPT_CR0_WRITE); set_cr_intercept(svm, INTERCEPT_CR3_WRITE); set_cr_intercept(svm, INTERCEPT_CR4_WRITE); set_cr_intercept(svm, INTERCEPT_CR8_WRITE); set_dr_intercepts(svm); set_exception_intercept(svm, PF_VECTOR); set_exception_intercept(svm, UD_VECTOR); set_exception_intercept(svm, MC_VECTOR); set_exception_intercept(svm, AC_VECTOR); set_intercept(svm, INTERCEPT_INTR); set_intercept(svm, INTERCEPT_NMI); set_intercept(svm, INTERCEPT_SMI); set_intercept(svm, INTERCEPT_SELECTIVE_CR0); set_intercept(svm, INTERCEPT_RDPMC); set_intercept(svm, INTERCEPT_CPUID); set_intercept(svm, INTERCEPT_INVD); set_intercept(svm, INTERCEPT_HLT); set_intercept(svm, INTERCEPT_INVLPG); set_intercept(svm, INTERCEPT_INVLPGA); set_intercept(svm, INTERCEPT_IOIO_PROT); set_intercept(svm, INTERCEPT_MSR_PROT); set_intercept(svm, INTERCEPT_TASK_SWITCH); set_intercept(svm, INTERCEPT_SHUTDOWN); set_intercept(svm, INTERCEPT_VMRUN); set_intercept(svm, INTERCEPT_VMMCALL); set_intercept(svm, INTERCEPT_VMLOAD); set_intercept(svm, INTERCEPT_VMSAVE); set_intercept(svm, INTERCEPT_STGI); set_intercept(svm, INTERCEPT_CLGI); set_intercept(svm, INTERCEPT_SKINIT); set_intercept(svm, INTERCEPT_WBINVD); set_intercept(svm, INTERCEPT_MONITOR); set_intercept(svm, INTERCEPT_MWAIT); set_intercept(svm, INTERCEPT_XSETBV); control->iopm_base_pa = iopm_base; control->msrpm_base_pa = __pa(svm->msrpm); control->int_ctl = V_INTR_MASKING_MASK; init_seg(&save->es); init_seg(&save->ss); init_seg(&save->ds); init_seg(&save->fs); init_seg(&save->gs); save->cs.selector = 0xf000; save->cs.base = 0xffff0000; /* Executable/Readable Code Segment */ save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; save->cs.limit = 0xffff; save->gdtr.limit = 0xffff; save->idtr.limit = 0xffff; init_sys_seg(&save->ldtr, SEG_TYPE_LDT); init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); svm_set_efer(&svm->vcpu, 0); save->dr6 = 0xffff0ff0; kvm_set_rflags(&svm->vcpu, 2); save->rip = 0x0000fff0; svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; /* * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. * It also updates the guest-visible cr0 value. */ svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); kvm_mmu_reset_context(&svm->vcpu); save->cr4 = X86_CR4_PAE; /* rdx = ?? */ if (npt_enabled) { /* Setup VMCB for Nested Paging */ control->nested_ctl = 1; clr_intercept(svm, INTERCEPT_INVLPG); clr_exception_intercept(svm, PF_VECTOR); clr_cr_intercept(svm, INTERCEPT_CR3_READ); clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); save->g_pat = svm->vcpu.arch.pat; save->cr3 = 0; save->cr4 = 0; } svm->asid_generation = 0; svm->nested.vmcb = 0; svm->vcpu.arch.hflags = 0; if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { control->pause_filter_count = 3000; set_intercept(svm, INTERCEPT_PAUSE); } mark_all_dirty(svm->vmcb); enable_gif(svm); } Commit Message: KVM: svm: unconditionally intercept #DB This is needed to avoid the possibility that the guest triggers an infinite stream of #DB exceptions (CVE-2015-8104). VMX is not affected: because it does not save DR6 in the VMCS, it already intercepts #DB unconditionally. Reported-by: Jan Beulich <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399
static void init_vmcb(struct vcpu_svm *svm) { struct vmcb_control_area *control = &svm->vmcb->control; struct vmcb_save_area *save = &svm->vmcb->save; svm->vcpu.fpu_active = 1; svm->vcpu.arch.hflags = 0; set_cr_intercept(svm, INTERCEPT_CR0_READ); set_cr_intercept(svm, INTERCEPT_CR3_READ); set_cr_intercept(svm, INTERCEPT_CR4_READ); set_cr_intercept(svm, INTERCEPT_CR0_WRITE); set_cr_intercept(svm, INTERCEPT_CR3_WRITE); set_cr_intercept(svm, INTERCEPT_CR4_WRITE); set_cr_intercept(svm, INTERCEPT_CR8_WRITE); set_dr_intercepts(svm); set_exception_intercept(svm, PF_VECTOR); set_exception_intercept(svm, UD_VECTOR); set_exception_intercept(svm, MC_VECTOR); set_exception_intercept(svm, AC_VECTOR); set_exception_intercept(svm, DB_VECTOR); set_intercept(svm, INTERCEPT_INTR); set_intercept(svm, INTERCEPT_NMI); set_intercept(svm, INTERCEPT_SMI); set_intercept(svm, INTERCEPT_SELECTIVE_CR0); set_intercept(svm, INTERCEPT_RDPMC); set_intercept(svm, INTERCEPT_CPUID); set_intercept(svm, INTERCEPT_INVD); set_intercept(svm, INTERCEPT_HLT); set_intercept(svm, INTERCEPT_INVLPG); set_intercept(svm, INTERCEPT_INVLPGA); set_intercept(svm, INTERCEPT_IOIO_PROT); set_intercept(svm, INTERCEPT_MSR_PROT); set_intercept(svm, INTERCEPT_TASK_SWITCH); set_intercept(svm, INTERCEPT_SHUTDOWN); set_intercept(svm, INTERCEPT_VMRUN); set_intercept(svm, INTERCEPT_VMMCALL); set_intercept(svm, INTERCEPT_VMLOAD); set_intercept(svm, INTERCEPT_VMSAVE); set_intercept(svm, INTERCEPT_STGI); set_intercept(svm, INTERCEPT_CLGI); set_intercept(svm, INTERCEPT_SKINIT); set_intercept(svm, INTERCEPT_WBINVD); set_intercept(svm, INTERCEPT_MONITOR); set_intercept(svm, INTERCEPT_MWAIT); set_intercept(svm, INTERCEPT_XSETBV); control->iopm_base_pa = iopm_base; control->msrpm_base_pa = __pa(svm->msrpm); control->int_ctl = V_INTR_MASKING_MASK; init_seg(&save->es); init_seg(&save->ss); init_seg(&save->ds); init_seg(&save->fs); init_seg(&save->gs); save->cs.selector = 0xf000; save->cs.base = 0xffff0000; /* Executable/Readable Code Segment */ save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; save->cs.limit = 0xffff; save->gdtr.limit = 0xffff; save->idtr.limit = 0xffff; init_sys_seg(&save->ldtr, SEG_TYPE_LDT); init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); svm_set_efer(&svm->vcpu, 0); save->dr6 = 0xffff0ff0; kvm_set_rflags(&svm->vcpu, 2); save->rip = 0x0000fff0; svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; /* * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. * It also updates the guest-visible cr0 value. */ svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); kvm_mmu_reset_context(&svm->vcpu); save->cr4 = X86_CR4_PAE; /* rdx = ?? */ if (npt_enabled) { /* Setup VMCB for Nested Paging */ control->nested_ctl = 1; clr_intercept(svm, INTERCEPT_INVLPG); clr_exception_intercept(svm, PF_VECTOR); clr_cr_intercept(svm, INTERCEPT_CR3_READ); clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); save->g_pat = svm->vcpu.arch.pat; save->cr3 = 0; save->cr4 = 0; } svm->asid_generation = 0; svm->nested.vmcb = 0; svm->vcpu.arch.hflags = 0; if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { control->pause_filter_count = 3000; set_intercept(svm, INTERCEPT_PAUSE); } mark_all_dirty(svm->vmcb); enable_gif(svm); }
166,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct svc_serv *nfs_callback_create_svc(int minorversion) { struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion]; struct svc_serv *serv; struct svc_serv_ops *sv_ops; /* * Check whether we're already up and running. */ if (cb_info->serv) { /* * Note: increase service usage, because later in case of error * svc_destroy() will be called. */ svc_get(cb_info->serv); return cb_info->serv; } switch (minorversion) { case 0: sv_ops = nfs4_cb_sv_ops[0]; break; default: sv_ops = nfs4_cb_sv_ops[1]; } if (sv_ops == NULL) return ERR_PTR(-ENOTSUPP); /* * Sanity check: if there's no task, * we should be the first user ... */ if (cb_info->users) printk(KERN_WARNING "nfs_callback_create_svc: no kthread, %d users??\n", cb_info->users); serv = svc_create(&nfs4_callback_program, NFS4_CALLBACK_BUFSIZE, sv_ops); if (!serv) { printk(KERN_ERR "nfs_callback_create_svc: create service failed\n"); return ERR_PTR(-ENOMEM); } cb_info->serv = serv; /* As there is only one thread we need to over-ride the * default maximum of 80 connections */ serv->sv_maxconn = 1024; dprintk("nfs_callback_create_svc: service created\n"); return serv; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static struct svc_serv *nfs_callback_create_svc(int minorversion) { struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion]; struct svc_serv *serv; struct svc_serv_ops *sv_ops; /* * Check whether we're already up and running. */ if (cb_info->serv) { /* * Note: increase service usage, because later in case of error * svc_destroy() will be called. */ svc_get(cb_info->serv); return cb_info->serv; } switch (minorversion) { case 0: sv_ops = nfs4_cb_sv_ops[0]; break; default: sv_ops = nfs4_cb_sv_ops[1]; } if (sv_ops == NULL) return ERR_PTR(-ENOTSUPP); /* * Sanity check: if there's no task, * we should be the first user ... */ if (cb_info->users) printk(KERN_WARNING "nfs_callback_create_svc: no kthread, %d users??\n", cb_info->users); serv = svc_create_pooled(&nfs4_callback_program, NFS4_CALLBACK_BUFSIZE, sv_ops); if (!serv) { printk(KERN_ERR "nfs_callback_create_svc: create service failed\n"); return ERR_PTR(-ENOMEM); } cb_info->serv = serv; /* As there is only one thread we need to over-ride the * default maximum of 80 connections */ serv->sv_maxconn = 1024; dprintk("nfs_callback_create_svc: service created\n"); return serv; }
168,139
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::RequestAuthorization( const dbus::ObjectPath& device_path, const ConfirmationCallback& callback) { callback.Run(CANCELLED); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::RequestAuthorization(
171,234
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 AXObject* AXObject::ariaHiddenRoot() const { for (const AXObject* object = this; object; object = object->parentObject()) { if (equalIgnoringCase(object->getAttribute(aria_hiddenAttr), "true")) return object; } return 0; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
const AXObject* AXObject::ariaHiddenRoot() const { for (const AXObject* object = this; object; object = object->parentObject()) { if (equalIgnoringASCIICase(object->getAttribute(aria_hiddenAttr), "true")) return object; } return 0; }
171,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameView::updateLayoutAndStyleForPainting() { RefPtr<FrameView> protector(this); updateLayoutAndStyleIfNeededRecursive(); if (RenderView* view = renderView()) { TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get()); InspectorInstrumentation::willUpdateLayerTree(m_frame.get()); view->compositor()->updateIfNeededRecursive(); if (view->compositor()->inCompositingMode() && m_frame->isLocalRoot()) m_frame->page()->scrollingCoordinator()->updateAfterCompositingChangeIfNeeded(); updateCompositedSelectionBoundsIfNeeded(); InspectorInstrumentation::didUpdateLayerTree(m_frame.get()); invalidateTreeIfNeededRecursive(); } scrollContentsIfNeededRecursive(); ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 [email protected] Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
void FrameView::updateLayoutAndStyleForPainting() { RefPtr<FrameView> protector(this); updateLayoutAndStyleIfNeededRecursive(); updateWidgetPositionsIfNeeded(); if (RenderView* view = renderView()) { TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get()); InspectorInstrumentation::willUpdateLayerTree(m_frame.get()); view->compositor()->updateIfNeededRecursive(); if (view->compositor()->inCompositingMode() && m_frame->isLocalRoot()) m_frame->page()->scrollingCoordinator()->updateAfterCompositingChangeIfNeeded(); updateCompositedSelectionBoundsIfNeeded(); InspectorInstrumentation::didUpdateLayerTree(m_frame.get()); invalidateTreeIfNeededRecursive(); } scrollContentsIfNeededRecursive(); ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean); }
171,636
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 stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { stellaris_enet_state *s = qemu_get_nic_opaque(nc); int n; uint8_t *p; uint32_t crc; if ((s->rctl & SE_RCTL_RXEN) == 0) return -1; if (s->np >= 31) { return 0; } DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; s->np++; s->rx[n].len = size + 6; p = s->rx[n].data; *(p++) = (size + 6); memset(p, 0, (6 - size) & 3); } Commit Message: CWE ID: CWE-20
static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { stellaris_enet_state *s = qemu_get_nic_opaque(nc); int n; uint8_t *p; uint32_t crc; if ((s->rctl & SE_RCTL_RXEN) == 0) return -1; if (s->np >= 31) { return 0; } DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; if (size >= sizeof(s->rx[n].data) - 6) { /* If the packet won't fit into the * emulated 2K RAM, this is reported * as a FIFO overrun error. */ s->ris |= SE_INT_FOV; stellaris_enet_update(s); return -1; } s->np++; s->rx[n].len = size + 6; p = s->rx[n].data; *(p++) = (size + 6); memset(p, 0, (6 - size) & 3); }
165,078
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 DevToolsSession::ReceivedBadMessage() { MojoConnectionDestroyed(); if (process_) { bad_message::ReceivedBadMessage( process_, bad_message::RFH_INCONSISTENT_DEVTOOLS_MESSAGE); } } 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 DevToolsSession::ReceivedBadMessage() { MojoConnectionDestroyed(); RenderProcessHost* process = RenderProcessHost::FromID(process_host_id_); if (process) { bad_message::ReceivedBadMessage( process, bad_message::RFH_INCONSISTENT_DEVTOOLS_MESSAGE); } }
172,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: usage(const char *prog) { /* ANSI C-90 limits strings to 509 characters, so use a string array: */ size_t i; static const char *usage_string[] = { " Tests, optimizes and optionally fixes the zlib header in PNG files.", " Optionally, when fixing, strips ancilliary chunks from the file.", 0, "OPTIONS", " OPERATION", " By default files are just checked for readability with a summary of the", " of zlib issues founds for each compressed chunk and the IDAT stream in", " the file.", " --optimize (-o):", " Find the smallest deflate window size for the compressed data.", " --strip=[none|crc|unsafe|unused|transform|color|all]:", " none (default): Retain all chunks.", " crc: Remove chunks with a bad CRC.", " unsafe: Remove chunks that may be unsafe to retain if the image data", " is modified. This is set automatically if --max is given but", " may be cancelled by a later --strip=none.", " unused: Remove chunks not used by libpng when decoding an image.", " This retains any chunks that might be used by libpng image", " transformations.", " transform: unused+bKGD.", " color: transform+iCCP and cHRM.", " all: color+gAMA and sRGB.", " Only ancillary chunks are ever removed. In addition the tRNS and sBIT", " chunks are never removed as they affect exact interpretation of the", " image pixel values. The following known chunks are treated specially", " by the above options:", " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel", " values.", " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also", " specifies the exact encoding of a pixel value however in practice", " most programs will ignore it.", " bKGD [transform]: This is used by libpng transforms." " --max=<number>:", " Use IDAT chunks sized <number>. If no number is given the the IDAT", " chunks will be the maximum size permitted; 2^31-1 bytes. If the option", " is omitted the original chunk sizes will not be changed. When the", " option is given --strip=unsafe is set automatically, this may be", " cancelled if you know that all unknown unsafe-to-copy chunks really are", " safe to copy across an IDAT size change. This is true of all chunks", " that have ever been formally proposed as PNG extensions.", " MESSAGES", " By default the program only outputs summaries for each file.", " --quiet (-q):", " Do not output the summaries except for files which cannot be read. With", " two --quiets these are not output either.", " --errors (-e):", " Output errors from libpng and the program (except too-far-back).", " --warnings (-w):", " Output warnings from libpng.", " OUTPUT", " By default nothing is written.", " --out=<file>:", " Write the optimized/corrected version of the next PNG to <file>. This", " overrides the following two options", " --suffix=<suffix>:", " Set --out=<name><suffix> for all following files unless overridden on", " a per-file basis by explicit --out.", " --prefix=<prefix>:", " Set --out=<prefix><name> for all the following files unless overridden", " on a per-file basis by explicit --out.", " These two options can be used together to produce a suffix and prefix.", " INTERNAL OPTIONS", #if 0 /*NYI*/ #ifdef PNG_MAXIMUM_INFLATE_WINDOW " --test:", " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables", " output as this would produce a broken file.", #endif #endif 0, "EXIT CODES", " *** SUBJECT TO CHANGE ***", " The program exit code is value in the range 0..127 holding a bit mask of", " the following codes. Notice that the results for each file are combined", " together - check one file at a time to get a meaningful error code!", " 0x01: The zlib too-far-back error existed in at least one chunk.", " 0x02: At least once chunk had a CRC error.", " 0x04: A chunk length was incorrect.", " 0x08: The file was truncated.", " Errors less than 16 are potentially recoverable, for a single file if the", " exit code is less than 16 the file could be read (with corrections if a", " non-zero code is returned).", " 0x10: The file could not be read, even with corrections.", " 0x20: The output file could not be written.", " 0x40: An unexpected, potentially internal, error occured.", " If the command line arguments are incorrect the program exits with exit", " 255. Some older operating systems only support 7-bit exit codes, on those", " systems it is suggested that this program is first tested by supplying", " invalid arguments.", 0, "DESCRIPTION", " " PROGRAM_NAME ":", " checks each PNG file on the command line for errors. By default errors are", " not output and the program just returns an exit code and prints a summary.", " With the --quiet (-q) option the summaries are suppressed too and the", " program only outputs unexpected errors (internal errors and file open", " errors).", " Various known problems in PNG files are fixed while the file is being read", " The exit code says what problems were fixed. In particular the zlib error:", 0, " \"invalid distance too far back\"", 0, " caused by an incorrect optimization of a zlib stream is fixed in any", " compressed chunk in which it is encountered. An integrity problem of the", " PNG stream caused by a bug in libpng which wrote an incorrect chunk length", " is also fixed. Chunk CRC errors are automatically fixed up.", 0, " Setting one of the \"OUTPUT\" options causes the possibly modified file to", " be written to a new file.", 0, " Notice that some PNG files with the zlib optimization problem can still be", " read by libpng under some circumstances. This program will still detect", " and, if requested, correct the error.", 0, " The program will reliably process all files on the command line unless", " either an invalid argument causes the usage message (this message) to be", " produced or the program crashes.", 0, " The summary lines describe issues encountered with the zlib compressed", " stream of a chunk. They have the following format, which is SUBJECT TO", " CHANGE in the future:", 0, " chunk reason comp-level p1 p2 p3 p4 file", 0, " p1 through p4 vary according to the 'reason'. There are always 8 space", " separated fields. Reasons specific formats are:", 0, " chunk ERR status code read-errno write-errno message file", " chunk SKP comp-level file-bits zlib-rc compressed message file", " chunk ??? comp-level file-bits ok-bits compressed uncompress file", 0, " The various fields are", 0, "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem", " is reported by libpng at the start of the IDAT stream.", "$2 reason: One of:", " CHK: A zlib header checksum was detected and fixed.", " TFB: The zlib too far back error was detected and fixed.", " OK : No errors were detected in the zlib stream and optimization", " was not requested, or was not possible.", " OPT: The zlib stream window bits value could be improved (and was).", " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with", " explanation 'message'", " ERR: The read of the file was aborted. The parameters explain why.", "$3 status: For 'ERR' the accumulate status code from 'EXIT CODES' above.", " This is printed as a 2 digit hexadecimal value", " comp-level: The recorded compression level (FLEVEL) of a zlib stream", " expressed as a string {supfast,stdfast,default,maximum}", "$4 code: The file exit code; where stop was called, as a fairly terse", " string {warning,libpng,zlib,invalid,read,write,unexpected}.", " file-bits: The zlib window bits recorded in the file.", "$5 read-errno: A system errno value from a read translated by strerror(3).", " zlib-rc: A zlib return code as a string (see zlib.h).", " ok-bits: The smallest zlib window bits value that works.", "$6 write-errno:A system errno value from a write translated by strerror(3).", " compressed: The count of compressed bytes in the zlib stream, when the", " reason is 'SKP'; this is a count of the bytes read from the", " stream when the fatal error was encountered.", "$7 message: An error message (spaces replaced by _, as in all parameters),", " uncompress: The count of bytes from uncompressing the zlib stream; this", " may not be the same as the number of bytes in the image.", "$8 file: The name of the file (this may contain spaces).", }; fprintf(stderr, "Usage: %s {[options] png-file}\n", prog); for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i) { if (usage_string[i] != 0) fputs(usage_string[i], stderr); fputc('\n', stderr); } exit(255); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
usage(const char *prog) { /* ANSI C-90 limits strings to 509 characters, so use a string array: */ size_t i; static const char *usage_string[] = { " Tests, optimizes and optionally fixes the zlib header in PNG files.", " Optionally, when fixing, strips ancilliary chunks from the file.", 0, "OPTIONS", " OPERATION", " By default files are just checked for readability with a summary of the", " of zlib issues founds for each compressed chunk and the IDAT stream in", " the file.", " --optimize (-o):", " Find the smallest deflate window size for the compressed data.", " --strip=[none|crc|unsafe|unused|transform|color|all]:", " none (default): Retain all chunks.", " crc: Remove chunks with a bad CRC.", " unsafe: Remove chunks that may be unsafe to retain if the image data", " is modified. This is set automatically if --max is given but", " may be cancelled by a later --strip=none.", " unused: Remove chunks not used by libpng when decoding an image.", " This retains any chunks that might be used by libpng image", " transformations.", " transform: unused+bKGD.", " color: transform+iCCP and cHRM.", " all: color+gAMA and sRGB.", " Only ancillary chunks are ever removed. In addition the tRNS and sBIT", " chunks are never removed as they affect exact interpretation of the", " image pixel values. The following known chunks are treated specially", " by the above options:", " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel", " values.", " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also", " specifies the exact encoding of a pixel value; however, in", " practice most programs will ignore it.", " bKGD [transform]: This is used by libpng transforms." " --max=<number>:", " Use IDAT chunks sized <number>. If no number is given the the IDAT", " chunks will be the maximum size permitted; 2^31-1 bytes. If the option", " is omitted the original chunk sizes will not be changed. When the", " option is given --strip=unsafe is set automatically. This may be", " cancelled if you know that all unknown unsafe-to-copy chunks really are", " safe to copy across an IDAT size change. This is true of all chunks", " that have ever been formally proposed as PNG extensions.", " MESSAGES", " By default the program only outputs summaries for each file.", " --quiet (-q):", " Do not output the summaries except for files that cannot be read. With", " two --quiets these are not output either.", " --errors (-e):", " Output errors from libpng and the program (except too-far-back).", " --warnings (-w):", " Output warnings from libpng.", " OUTPUT", " By default nothing is written.", " --out=<file>:", " Write the optimized/corrected version of the next PNG to <file>. This", " overrides the following two options", " --suffix=<suffix>:", " Set --out=<name><suffix> for all following files unless overridden on", " a per-file basis by explicit --out.", " --prefix=<prefix>:", " Set --out=<prefix><name> for all the following files unless overridden", " on a per-file basis by explicit --out.", " These two options can be used together to produce a suffix and prefix.", " INTERNAL OPTIONS", #if 0 /*NYI*/ #ifdef PNG_MAXIMUM_INFLATE_WINDOW " --test:", " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables", " output as this would produce a broken file.", #endif #endif 0, "EXIT CODES", " *** SUBJECT TO CHANGE ***", " The program exit code is value in the range 0..127 holding a bit mask of", " the following codes. Notice that the results for each file are combined", " together - check one file at a time to get a meaningful error code!", " 0x01: The zlib too-far-back error existed in at least one chunk.", " 0x02: At least one chunk had a CRC error.", " 0x04: A chunk length was incorrect.", " 0x08: The file was truncated.", " Errors less than 16 are potentially recoverable, for a single file if the", " exit code is less than 16 the file could be read (with corrections if a", " non-zero code is returned).", " 0x10: The file could not be read, even with corrections.", " 0x20: The output file could not be written.", " 0x40: An unexpected, potentially internal, error occurred.", " If the command line arguments are incorrect the program exits with exit", " 255. Some older operating systems only support 7-bit exit codes, on those", " systems it is suggested that this program is first tested by supplying", " invalid arguments.", 0, "DESCRIPTION", " " PROGRAM_NAME ":", " checks each PNG file on the command line for errors. By default errors are", " not output and the program just returns an exit code and prints a summary.", " With the --quiet (-q) option the summaries are suppressed too and the", " program only outputs unexpected errors (internal errors and file open", " errors).", " Various known problems in PNG files are fixed while the file is being read", " The exit code says what problems were fixed. In particular the zlib error:", 0, " \"invalid distance too far back\"", 0, " caused by an incorrect optimization of a zlib stream is fixed in any", " compressed chunk in which it is encountered. An integrity problem of the", " PNG stream caused by a bug in libpng which wrote an incorrect chunk length", " is also fixed. Chunk CRC errors are automatically fixed up.", 0, " Setting one of the \"OUTPUT\" options causes the possibly modified file to", " be written to a new file.", 0, " Notice that some PNG files with the zlib optimization problem can still be", " read by libpng under some circumstances. This program will still detect", " and, if requested, correct the error.", 0, " The program will reliably process all files on the command line unless", " either an invalid argument causes the usage message (this message) to be", " produced or the program crashes.", 0, " The summary lines describe issues encountered with the zlib compressed", " stream of a chunk. They have the following format, which is SUBJECT TO", " CHANGE in the future:", 0, " chunk reason comp-level p1 p2 p3 p4 file", 0, " p1 through p4 vary according to the 'reason'. There are always 8 space", " separated fields. Reasons specific formats are:", 0, " chunk ERR status code read-errno write-errno message file", " chunk SKP comp-level file-bits zlib-rc compressed message file", " chunk ??? comp-level file-bits ok-bits compressed uncompress file", 0, " The various fields are", 0, "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem", " is reported by libpng at the start of the IDAT stream.", "$2 reason: One of:", " CHK: A zlib header checksum was detected and fixed.", " TFB: The zlib too far back error was detected and fixed.", " OK : No errors were detected in the zlib stream and optimization", " was not requested, or was not possible.", " OPT: The zlib stream window bits value could be improved (and was).", " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with", " explanation 'message'", " ERR: The read of the file was aborted. The parameters explain why.", "$3 status: For 'ERR' the accumulated status code from 'EXIT CODES' above.", " This is printed as a 2 digit hexadecimal value", " comp-level: The recorded compression level (FLEVEL) of a zlib stream", " expressed as a string {supfast,stdfast,default,maximum}", "$4 code: The file exit code; where stop was called, as a fairly terse", " string {warning,libpng,zlib,invalid,read,write,unexpected}.", " file-bits: The zlib window bits recorded in the file.", "$5 read-errno: A system errno value from a read translated by strerror(3).", " zlib-rc: A zlib return code as a string (see zlib.h).", " ok-bits: The smallest zlib window bits value that works.", "$6 write-errno:A system errno value from a write translated by strerror(3).", " compressed: The count of compressed bytes in the zlib stream, when the", " reason is 'SKP'; this is a count of the bytes read from the", " stream when the fatal error was encountered.", "$7 message: An error message (spaces replaced by _, as in all parameters),", " uncompress: The count of bytes from uncompressing the zlib stream; this", " may not be the same as the number of bytes in the image.", "$8 file: The name of the file (this may contain spaces).", }; fprintf(stderr, "Usage: %s {[options] png-file}\n", prog); for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i) { if (usage_string[i] != 0) fputs(usage_string[i], stderr); fputc('\n', stderr); } exit(255); }
173,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: void DownloadRequestLimiter::TabDownloadState::DidStartNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; download_seen_ = false; ui_status_ = DOWNLOAD_UI_DEFAULT; if (navigation_handle->IsRendererInitiated() && (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED)) { return; } if (status_ == DownloadRequestLimiter::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED) { if (!initial_page_host_.empty() && navigation_handle->GetURL().host_piece() == initial_page_host_) { return; } } NotifyCallbacks(false); host_->Remove(this, web_contents()); } Commit Message: Don't reset TabDownloadState on history back/forward Currently performing forward/backward on a tab will reset the TabDownloadState. Which allows javascript code to do trigger multiple downloads. This CL disables that behavior by not resetting the TabDownloadState on forward/back. It is still possible to reset the TabDownloadState through user gesture or using browser initiated download. BUG=848535 Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863 Reviewed-on: https://chromium-review.googlesource.com/1108959 Commit-Queue: Min Qin <[email protected]> Reviewed-by: Xing Liu <[email protected]> Cr-Commit-Position: refs/heads/master@{#574437} CWE ID:
void DownloadRequestLimiter::TabDownloadState::DidStartNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; download_seen_ = false; ui_status_ = DOWNLOAD_UI_DEFAULT; if (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED) { std::string host = navigation_handle->GetURL().host(); // If the navigation is renderer-initiated (but not user-initiated), ensure // that a prompting or blocking limiter state is not reset, so // window.location.href or meta refresh can't be abused to avoid the // limiter. if (navigation_handle->IsRendererInitiated()) { if (!host.empty()) restricted_hosts_.emplace(host); return; } // If this is a forward/back navigation, also don't reset a prompting or // blocking limiter state unless a new host is encounted. This prevents a // page to use history forward/backward to trigger multiple downloads. if (IsNavigationRestricted(navigation_handle)) return; } if (status_ == DownloadRequestLimiter::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED) { if (!initial_page_host_.empty() && navigation_handle->GetURL().host_piece() == initial_page_host_) { return; } } NotifyCallbacks(false); host_->Remove(this, web_contents()); }
173,189
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: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ pcap_close(fp); if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } Commit Message: In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs. CWE ID: CWE-918
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; // Is this a URL rather than a device? // If so, reject it. if (is_url(source)) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string refers to a remote device"); goto error; } if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ pcap_close(fp); if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; }
169,540
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 ExtensionOptionsGuest::DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { if (attached()) { auto guest_zoom_controller = ui_zoom::ZoomController::FromWebContents(web_contents()); guest_zoom_controller->SetZoomMode( ui_zoom::ZoomController::ZOOM_MODE_ISOLATED); SetGuestZoomLevelToMatchEmbedder(); if (params.url.GetOrigin() != options_page_.GetOrigin()) { bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(), bad_message::EOG_BAD_ORIGIN); } } } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
void ExtensionOptionsGuest::DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { if (attached()) { auto guest_zoom_controller = ui_zoom::ZoomController::FromWebContents(web_contents()); guest_zoom_controller->SetZoomMode( ui_zoom::ZoomController::ZOOM_MODE_ISOLATED); SetGuestZoomLevelToMatchEmbedder(); if (!url::IsSameOriginWith(params.url, options_page_)) { bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(), bad_message::EOG_BAD_ORIGIN); } } }
172,282
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 mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; } Commit Message: Staging: sb105x: info leak in mp_get_count() The icount.reserved[] array isn't initialized so it leaks stack information to userspace. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount = {}; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; }
165,961
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 fz_init_cached_color_converter(fz_context *ctx, fz_color_converter *cc, fz_colorspace *is, fz_colorspace *ds, fz_colorspace *ss, const fz_color_params *params) { int n = ss->n; fz_cached_color_converter *cached = fz_malloc_struct(ctx, fz_cached_color_converter); cc->opaque = cached; cc->convert = fz_cached_color_convert; cc->ds = ds ? ds : fz_device_gray(ctx); cc->ss = ss; cc->is = is; fz_try(ctx) { fz_find_color_converter(ctx, &cached->base, is, cc->ds, ss, params); cached->hash = fz_new_hash_table(ctx, 256, n * sizeof(float), -1, fz_free); } fz_catch(ctx) { fz_drop_color_converter(ctx, &cached->base); fz_drop_hash_table(ctx, cached->hash); fz_free(ctx, cached); fz_rethrow(ctx); } } Commit Message: CWE ID: CWE-20
void fz_init_cached_color_converter(fz_context *ctx, fz_color_converter *cc, fz_colorspace *is, fz_colorspace *ds, fz_colorspace *ss, const fz_color_params *params) { int n = ss->n; fz_cached_color_converter *cached = fz_malloc_struct(ctx, fz_cached_color_converter); cc->opaque = cached; cc->convert = fz_cached_color_convert; cc->ds = ds ? ds : fz_device_gray(ctx); cc->ss = ss; cc->is = is; fz_try(ctx) { fz_find_color_converter(ctx, &cached->base, is, cc->ds, ss, params); cached->hash = fz_new_hash_table(ctx, 256, n * sizeof(float), -1, fz_free); } fz_catch(ctx) { fz_drop_color_converter(ctx, &cached->base); fz_drop_hash_table(ctx, cached->hash); fz_free(ctx, cached); cc->opaque = NULL; fz_rethrow(ctx); } }
164,576
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: BlockGroup::BlockGroup( Cluster* pCluster, long idx, long long block_start, long long block_size, long long prev, long long next, long long duration, long long discard_padding) : BlockEntry(pCluster, idx), m_block(block_start, block_size, discard_padding), m_prev(prev), m_next(next), m_duration(duration) { } 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
BlockGroup::BlockGroup(
174,242
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 nr_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; size_t copied; struct sk_buff *skb; int er; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ lock_sock(sk); if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) { release_sock(sk); return er; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (er < 0) { skb_free_datagram(sk, skb); release_sock(sk); return er; } if (sax != NULL) { memset(sax, 0, sizeof(*sax)); sax->sax25_family = AF_NETROM; skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call, AX25_ADDR_LEN); } msg->msg_namelen = sizeof(*sax); skb_free_datagram(sk, skb); release_sock(sk); return copied; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int nr_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; size_t copied; struct sk_buff *skb; int er; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ lock_sock(sk); if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) { release_sock(sk); return er; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (er < 0) { skb_free_datagram(sk, skb); release_sock(sk); return er; } if (sax != NULL) { memset(sax, 0, sizeof(*sax)); sax->sax25_family = AF_NETROM; skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call, AX25_ADDR_LEN); msg->msg_namelen = sizeof(*sax); } skb_free_datagram(sk, skb); release_sock(sk); return copied; }
166,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb) { int i; unsigned char max_level = 0; int unix_sock_count = 0; for (i = scm->fp->count - 1; i >= 0; i--) { struct sock *sk = unix_get_socket(scm->fp->fp[i]); if (sk) { unix_sock_count++; max_level = max(max_level, unix_sk(sk)->recursion_level); } } if (unlikely(max_level > MAX_RECURSION_LEVEL)) return -ETOOMANYREFS; /* * Need to duplicate file references for the sake of garbage * collection. Otherwise a socket in the fps might become a * candidate for GC while the skb is not yet queued. */ UNIXCB(skb).fp = scm_fp_dup(scm->fp); if (!UNIXCB(skb).fp) return -ENOMEM; if (unix_sock_count) { for (i = scm->fp->count - 1; i >= 0; i--) unix_inflight(scm->fp->fp[i]); } return max_level; } Commit Message: unix: properly account for FDs passed over unix sockets It is possible for a process to allocate and accumulate far more FDs than the process' limit by sending them over a unix socket then closing them to keep the process' fd count low. This change addresses this problem by keeping track of the number of FDs in flight per user and preventing non-privileged processes from having more FDs in flight than their configured FD limit. Reported-by: [email protected] Reported-by: Tetsuo Handa <[email protected]> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb) { int i; unsigned char max_level = 0; int unix_sock_count = 0; if (too_many_unix_fds(current)) return -ETOOMANYREFS; for (i = scm->fp->count - 1; i >= 0; i--) { struct sock *sk = unix_get_socket(scm->fp->fp[i]); if (sk) { unix_sock_count++; max_level = max(max_level, unix_sk(sk)->recursion_level); } } if (unlikely(max_level > MAX_RECURSION_LEVEL)) return -ETOOMANYREFS; /* * Need to duplicate file references for the sake of garbage * collection. Otherwise a socket in the fps might become a * candidate for GC while the skb is not yet queued. */ UNIXCB(skb).fp = scm_fp_dup(scm->fp); if (!UNIXCB(skb).fp) return -ENOMEM; for (i = scm->fp->count - 1; i >= 0; i--) unix_inflight(scm->fp->fp[i]); return max_level; }
167,596
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 unsigned int stack_maxrandom_size(void) { unsigned int max = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { max = ((-1U) & STACK_RND_MASK) << PAGE_SHIFT; } return max; } Commit Message: x86, mm/ASLR: Fix stack randomization on 64-bit systems The issue is that the stack for processes is not properly randomized on 64 bit architectures due to an integer overflow. The affected function is randomize_stack_top() in file "fs/binfmt_elf.c": static unsigned long randomize_stack_top(unsigned long stack_top) { unsigned int random_variable = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { random_variable = get_random_int() & STACK_RND_MASK; random_variable <<= PAGE_SHIFT; } return PAGE_ALIGN(stack_top) + random_variable; return PAGE_ALIGN(stack_top) - random_variable; } Note that, it declares the "random_variable" variable as "unsigned int". Since the result of the shifting operation between STACK_RND_MASK (which is 0x3fffff on x86_64, 22 bits) and PAGE_SHIFT (which is 12 on x86_64): random_variable <<= PAGE_SHIFT; then the two leftmost bits are dropped when storing the result in the "random_variable". This variable shall be at least 34 bits long to hold the (22+12) result. These two dropped bits have an impact on the entropy of process stack. Concretely, the total stack entropy is reduced by four: from 2^28 to 2^30 (One fourth of expected entropy). This patch restores back the entropy by correcting the types involved in the operations in the functions randomize_stack_top() and stack_maxrandom_size(). The successful fix can be tested with: $ for i in `seq 1 10`; do cat /proc/self/maps | grep stack; done 7ffeda566000-7ffeda587000 rw-p 00000000 00:00 0 [stack] 7fff5a332000-7fff5a353000 rw-p 00000000 00:00 0 [stack] 7ffcdb7a1000-7ffcdb7c2000 rw-p 00000000 00:00 0 [stack] 7ffd5e2c4000-7ffd5e2e5000 rw-p 00000000 00:00 0 [stack] ... Once corrected, the leading bytes should be between 7ffc and 7fff, rather than always being 7fff. Signed-off-by: Hector Marco-Gisbert <[email protected]> Signed-off-by: Ismael Ripoll <[email protected]> [ Rebased, fixed 80 char bugs, cleaned up commit message, added test example and CVE ] Signed-off-by: Kees Cook <[email protected]> Cc: <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Al Viro <[email protected]> Fixes: CVE-2015-1593 Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Borislav Petkov <[email protected]> CWE ID: CWE-264
static unsigned int stack_maxrandom_size(void) static unsigned long stack_maxrandom_size(void) { unsigned long max = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { max = ((-1UL) & STACK_RND_MASK) << PAGE_SHIFT; } return max; }
166,695
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: add_job(cupsd_client_t *con, /* I - Client connection */ cupsd_printer_t *printer, /* I - Destination printer */ mime_type_t *filetype) /* I - First print file type, if any */ { http_status_t status; /* Policy status */ ipp_attribute_t *attr, /* Current attribute */ *auth_info; /* auth-info attribute */ const char *mandatory; /* Current mandatory job attribute */ const char *val; /* Default option value */ int priority; /* Job priority */ cupsd_job_t *job; /* Current job */ char job_uri[HTTP_MAX_URI]; /* Job URI */ int kbytes; /* Size of print file */ int i; /* Looping var */ int lowerpagerange; /* Page range bound */ int exact; /* Did we have an exact match? */ ipp_attribute_t *media_col, /* media-col attribute */ *media_margin; /* media-*-margin attribute */ ipp_t *unsup_col; /* media-col in unsupported response */ static const char * const readonly[] =/* List of read-only attributes */ { "date-time-at-completed", "date-time-at-creation", "date-time-at-processing", "job-detailed-status-messages", "job-document-access-errors", "job-id", "job-impressions-completed", "job-k-octets-completed", "job-media-sheets-completed", "job-pages-completed", "job-printer-up-time", "job-printer-uri", "job-state", "job-state-message", "job-state-reasons", "job-uri", "number-of-documents", "number-of-intervening-jobs", "output-device-assigned", "time-at-completed", "time-at-creation", "time-at-processing" }; cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))", con, con->number, printer, printer->name, filetype, filetype ? filetype->super : "none", filetype ? filetype->type : "none"); /* * Check remote printing to non-shared printer... */ if (!printer->shared && _cups_strcasecmp(con->http->hostname, "localhost") && _cups_strcasecmp(con->http->hostname, ServerName)) { send_ipp_status(con, IPP_NOT_AUTHORIZED, _("The printer or class is not shared.")); return (NULL); } /* * Check policy... */ auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT); if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK) { send_http_error(con, status, printer); return (NULL); } else if (printer->num_auth_info_required == 1 && !strcmp(printer->auth_info_required[0], "negotiate") && !con->username[0]) { send_http_error(con, HTTP_UNAUTHORIZED, printer); return (NULL); } #ifdef HAVE_SSL else if (auth_info && !con->http->tls && !httpAddrLocalhost(con->http->hostaddr)) { /* * Require encryption of auth-info over non-local connections... */ send_http_error(con, HTTP_UPGRADE_REQUIRED, printer); return (NULL); } #endif /* HAVE_SSL */ /* * See if the printer is accepting jobs... */ if (!printer->accepting) { send_ipp_status(con, IPP_NOT_ACCEPTING, _("Destination \"%s\" is not accepting jobs."), printer->name); return (NULL); } /* * Validate job template attributes; for now just document-format, * copies, job-sheets, number-up, page-ranges, mandatory attributes, and * media... */ for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++) { if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL) { ippDeleteAttribute(con->request, attr); if (StrictConformance) { send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]); return (NULL); } cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]); } } if (printer->pc) { for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory); mandatory; mandatory = (char *)cupsArrayNext(printer->pc->mandatory)) { if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO)) { /* * Missing a required attribute... */ send_ipp_status(con, IPP_CONFLICT, _("The \"%s\" attribute is required for print jobs."), mandatory); return (NULL); } } } if (filetype && printer->filetypes && !cupsArrayFind(printer->filetypes, filetype)) { char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2]; /* MIME media type string */ snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type); send_ipp_status(con, IPP_DOCUMENT_FORMAT, _("Unsupported format \"%s\"."), mimetype); ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE, "document-format", NULL, mimetype); return (NULL); } if ((attr = ippFindAttribute(con->request, "copies", IPP_TAG_INTEGER)) != NULL) { if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."), attr->values[0].integer); ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "copies", attr->values[0].integer); return (NULL); } } if ((attr = ippFindAttribute(con->request, "job-sheets", IPP_TAG_ZERO)) != NULL) { if (attr->value_tag != IPP_TAG_KEYWORD && attr->value_tag != IPP_TAG_NAME) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type.")); return (NULL); } if (attr->num_values > 2) { send_ipp_status(con, IPP_BAD_REQUEST, _("Too many job-sheets values (%d > 2)."), attr->num_values); return (NULL); } for (i = 0; i < attr->num_values; i ++) if (strcmp(attr->values[i].string.text, "none") && !cupsdFindBanner(attr->values[i].string.text)) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."), attr->values[i].string.text); return (NULL); } } if ((attr = ippFindAttribute(con->request, "number-up", IPP_TAG_INTEGER)) != NULL) { if (attr->values[0].integer != 1 && attr->values[0].integer != 2 && attr->values[0].integer != 4 && attr->values[0].integer != 6 && attr->values[0].integer != 9 && attr->values[0].integer != 16) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."), attr->values[0].integer); ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "number-up", attr->values[0].integer); return (NULL); } } if ((attr = ippFindAttribute(con->request, "page-ranges", IPP_TAG_RANGE)) != NULL) { for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++) { if (attr->values[i].range.lower < lowerpagerange || attr->values[i].range.lower > attr->values[i].range.upper) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad page-ranges values %d-%d."), attr->values[i].range.lower, attr->values[i].range.upper); return (NULL); } lowerpagerange = attr->values[i].range.upper + 1; } } /* * Do media selection as needed... */ if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) && !ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) && _ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact)) { if (!exact && (media_col = ippFindAttribute(con->request, "media-col", IPP_TAG_BEGIN_COLLECTION)) != NULL) { send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins.")); unsup_col = ippNew(); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-bottom-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-bottom-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-left-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-left-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-right-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-right-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-top-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-top-margin", media_margin->values[0].integer); ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col", unsup_col); ippDelete(unsup_col); } } /* * Make sure we aren't over our limit... */ if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) cupsdCleanJobs(); if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) { send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs.")); return (NULL); } if ((i = check_quotas(con, printer)) < 0) { send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached.")); return (NULL); } else if (i == 0) { send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print.")); return (NULL); } /* * Create the job and set things up... */ if ((attr = ippFindAttribute(con->request, "job-priority", IPP_TAG_INTEGER)) != NULL) priority = attr->values[0].integer; else { if ((val = cupsGetOption("job-priority", printer->num_options, printer->options)) != NULL) priority = atoi(val); else priority = 50; ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority", priority); } if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL) ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled"); else if ((attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_NAMELANG) || attr->num_values != 1) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: Wrong type or count.")); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } else if (!ippValidateAttribute(attr)) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"), cupsLastErrorString()); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } if ((job = cupsdAddJob(priority, printer->name)) == NULL) { send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to add job for destination \"%s\"."), printer->name); return (NULL); } job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE); job->attrs = con->request; job->dirty = 1; con->request = ippNewRequest(job->attrs->request.op.operation_id); cupsdMarkDirty(CUPSD_DIRTY_JOBS); add_job_uuid(job); apply_printer_defaults(printer, job); attr = ippFindAttribute(job->attrs, "requesting-user-name", IPP_TAG_NAME); if (con->username[0]) { cupsdSetString(&job->username, con->username); if (attr) ippSetString(job->attrs, &attr, 0, con->username); } else if (attr) { cupsdLogMessage(CUPSD_LOG_DEBUG, "add_job: requesting-user-name=\"%s\"", attr->values[0].string.text); cupsdSetString(&job->username, attr->values[0].string.text); } else cupsdSetString(&job->username, "anonymous"); if (!attr) ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-user-name", NULL, job->username); else { ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); ippSetName(job->attrs, &attr, "job-originating-user-name"); } if (con->username[0] || auth_info) { save_auth_info(con, job, auth_info); /* * Remove the auth-info attribute from the attribute data... */ if (auth_info) ippDeleteAttribute(job->attrs, auth_info); } if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL) cupsdSetString(&(job->name), attr->values[0].string.text); if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name", IPP_TAG_ZERO)) != NULL) { /* * Request contains a job-originating-host-name attribute; validate it... */ if (attr->value_tag != IPP_TAG_NAME || attr->num_values != 1 || strcmp(con->http->hostname, "localhost")) { /* * Can't override the value if we aren't connected via localhost. * Also, we can only have 1 value and it must be a name value. */ ippDeleteAttribute(job->attrs, attr); ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname); } else ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); } else { /* * No job-originating-host-name attribute, so use the hostname from * the connection... */ ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname); } ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed"); ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL))); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing"); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed"); ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL)); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing"); /* * Add remaining job attributes... */ ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id); job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", IPP_JOB_STOPPED); job->state_value = (ipp_jstate_t)job->state->values[0].integer; job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-incoming"); job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0); job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-media-sheets-completed", 0); ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL, printer->uri); if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL) attr->values[0].integer = 0; else ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0); if ((attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_KEYWORD)) == NULL) attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME); if (!attr) { if ((val = cupsGetOption("job-hold-until", printer->num_options, printer->options)) == NULL) val = "no-hold"; attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-hold-until", NULL, val); } if (printer->holding_new_jobs) { /* * Hold all new jobs on this printer... */ if (attr && strcmp(attr->values[0].string.text, "no-hold")) cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0); else cupsdSetJobHoldUntil(job, "indefinite", 0); job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create"); } else if (attr && strcmp(attr->values[0].string.text, "no-hold")) { /* * Hold job until specified time... */ cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0); job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified"); } else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB) { job->hold_until = time(NULL) + MultipleOperationTimeout; job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; } else { job->state->values[0].integer = IPP_JOB_PENDING; job->state_value = IPP_JOB_PENDING; ippSetString(job->attrs, &job->reasons, 0, "none"); } if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification) { /* * Add job sheets options... */ if ((attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) == NULL) { cupsdLogMessage(CUPSD_LOG_DEBUG, "Adding default job-sheets values \"%s,%s\"...", printer->job_sheets[0], printer->job_sheets[1]); attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets", 2, NULL, NULL); ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]); ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]); } job->job_sheets = attr; /* * Enforce classification level if set... */ if (Classification) { cupsdLogMessage(CUPSD_LOG_INFO, "Classification=\"%s\", ClassifyOverride=%d", Classification ? Classification : "(null)", ClassifyOverride); if (ClassifyOverride) { if (!strcmp(attr->values[0].string.text, "none") && (attr->num_values == 1 || !strcmp(attr->values[1].string.text, "none"))) { /* * Force the leading banner to have the classification on it... */ ippSetString(job->attrs, &attr, 0, Classification); cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,none\", " "job-originating-user-name=\"%s\"", Classification, job->username); } else if (attr->num_values == 2 && strcmp(attr->values[0].string.text, attr->values[1].string.text) && strcmp(attr->values[0].string.text, "none") && strcmp(attr->values[1].string.text, "none")) { /* * Can't put two different security markings on the same document! */ ippSetString(job->attrs, &attr, 1, attr->values[0].string.text); cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); } else if (strcmp(attr->values[0].string.text, Classification) && strcmp(attr->values[0].string.text, "none") && (attr->num_values == 1 || (strcmp(attr->values[1].string.text, Classification) && strcmp(attr->values[1].string.text, "none")))) { if (attr->num_values == 1) cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION OVERRIDDEN " "job-sheets=\"%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, job->username); else cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION OVERRIDDEN " "job-sheets=\"%s,%s\",fffff " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); } } else if (strcmp(attr->values[0].string.text, Classification) && (attr->num_values == 1 || strcmp(attr->values[1].string.text, Classification))) { /* * Force the banner to have the classification on it... */ if (attr->num_values > 1 && !strcmp(attr->values[0].string.text, attr->values[1].string.text)) { ippSetString(job->attrs, &attr, 0, Classification); ippSetString(job->attrs, &attr, 1, Classification); } else { if (attr->num_values == 1 || strcmp(attr->values[0].string.text, "none")) ippSetString(job->attrs, &attr, 0, Classification); if (attr->num_values > 1 && strcmp(attr->values[1].string.text, "none")) ippSetString(job->attrs, &attr, 1, Classification); } if (attr->num_values > 1) cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); else cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s\", " "job-originating-user-name=\"%s\"", Classification, job->username); } } /* * See if we need to add the starting sheet... */ if (!(printer->type & CUPS_PRINTER_REMOTE)) { cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".", attr->values[0].string.text); if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0) { cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE, "Aborting job because the start banner could not be " "copied."); return (NULL); } cupsdUpdateQuota(printer, job->username, 0, kbytes); } } else if ((attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL) job->job_sheets = attr; /* * Fill in the response info... */ httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL, con->clientname, con->clientport, "/jobs/%d", job->id); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL, job_uri); ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id); ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", job->state_value); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, ""); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, job->reasons->values[0].string.text); con->response->request.status.status_code = IPP_OK; /* * Add any job subscriptions... */ add_job_subscriptions(con, job); /* * Set all but the first two attributes to the job attributes group... */ for (attr = job->attrs->attrs->next->next; attr; attr = attr->next) attr->group_tag = IPP_TAG_JOB; /* * Fire the "job created" event... */ cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created."); /* * Return the new job... */ return (job); } Commit Message: DBUS notifications could crash the scheduler (Issue #5143) - scheduler/ipp.c: Make sure requesting-user-name string is valid UTF-8. CWE ID: CWE-20
add_job(cupsd_client_t *con, /* I - Client connection */ cupsd_printer_t *printer, /* I - Destination printer */ mime_type_t *filetype) /* I - First print file type, if any */ { http_status_t status; /* Policy status */ ipp_attribute_t *attr, /* Current attribute */ *auth_info; /* auth-info attribute */ const char *mandatory; /* Current mandatory job attribute */ const char *val; /* Default option value */ int priority; /* Job priority */ cupsd_job_t *job; /* Current job */ char job_uri[HTTP_MAX_URI]; /* Job URI */ int kbytes; /* Size of print file */ int i; /* Looping var */ int lowerpagerange; /* Page range bound */ int exact; /* Did we have an exact match? */ ipp_attribute_t *media_col, /* media-col attribute */ *media_margin; /* media-*-margin attribute */ ipp_t *unsup_col; /* media-col in unsupported response */ static const char * const readonly[] =/* List of read-only attributes */ { "date-time-at-completed", "date-time-at-creation", "date-time-at-processing", "job-detailed-status-messages", "job-document-access-errors", "job-id", "job-impressions-completed", "job-k-octets-completed", "job-media-sheets-completed", "job-pages-completed", "job-printer-up-time", "job-printer-uri", "job-state", "job-state-message", "job-state-reasons", "job-uri", "number-of-documents", "number-of-intervening-jobs", "output-device-assigned", "time-at-completed", "time-at-creation", "time-at-processing" }; cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))", con, con->number, printer, printer->name, filetype, filetype ? filetype->super : "none", filetype ? filetype->type : "none"); /* * Check remote printing to non-shared printer... */ if (!printer->shared && _cups_strcasecmp(con->http->hostname, "localhost") && _cups_strcasecmp(con->http->hostname, ServerName)) { send_ipp_status(con, IPP_NOT_AUTHORIZED, _("The printer or class is not shared.")); return (NULL); } /* * Check policy... */ auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT); if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK) { send_http_error(con, status, printer); return (NULL); } else if (printer->num_auth_info_required == 1 && !strcmp(printer->auth_info_required[0], "negotiate") && !con->username[0]) { send_http_error(con, HTTP_UNAUTHORIZED, printer); return (NULL); } #ifdef HAVE_SSL else if (auth_info && !con->http->tls && !httpAddrLocalhost(con->http->hostaddr)) { /* * Require encryption of auth-info over non-local connections... */ send_http_error(con, HTTP_UPGRADE_REQUIRED, printer); return (NULL); } #endif /* HAVE_SSL */ /* * See if the printer is accepting jobs... */ if (!printer->accepting) { send_ipp_status(con, IPP_NOT_ACCEPTING, _("Destination \"%s\" is not accepting jobs."), printer->name); return (NULL); } /* * Validate job template attributes; for now just document-format, * copies, job-sheets, number-up, page-ranges, mandatory attributes, and * media... */ for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++) { if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL) { ippDeleteAttribute(con->request, attr); if (StrictConformance) { send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]); return (NULL); } cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]); } } if (printer->pc) { for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory); mandatory; mandatory = (char *)cupsArrayNext(printer->pc->mandatory)) { if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO)) { /* * Missing a required attribute... */ send_ipp_status(con, IPP_CONFLICT, _("The \"%s\" attribute is required for print jobs."), mandatory); return (NULL); } } } if (filetype && printer->filetypes && !cupsArrayFind(printer->filetypes, filetype)) { char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2]; /* MIME media type string */ snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type); send_ipp_status(con, IPP_DOCUMENT_FORMAT, _("Unsupported format \"%s\"."), mimetype); ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE, "document-format", NULL, mimetype); return (NULL); } if ((attr = ippFindAttribute(con->request, "copies", IPP_TAG_INTEGER)) != NULL) { if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."), attr->values[0].integer); ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "copies", attr->values[0].integer); return (NULL); } } if ((attr = ippFindAttribute(con->request, "job-sheets", IPP_TAG_ZERO)) != NULL) { if (attr->value_tag != IPP_TAG_KEYWORD && attr->value_tag != IPP_TAG_NAME) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type.")); return (NULL); } if (attr->num_values > 2) { send_ipp_status(con, IPP_BAD_REQUEST, _("Too many job-sheets values (%d > 2)."), attr->num_values); return (NULL); } for (i = 0; i < attr->num_values; i ++) if (strcmp(attr->values[i].string.text, "none") && !cupsdFindBanner(attr->values[i].string.text)) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."), attr->values[i].string.text); return (NULL); } } if ((attr = ippFindAttribute(con->request, "number-up", IPP_TAG_INTEGER)) != NULL) { if (attr->values[0].integer != 1 && attr->values[0].integer != 2 && attr->values[0].integer != 4 && attr->values[0].integer != 6 && attr->values[0].integer != 9 && attr->values[0].integer != 16) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."), attr->values[0].integer); ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "number-up", attr->values[0].integer); return (NULL); } } if ((attr = ippFindAttribute(con->request, "page-ranges", IPP_TAG_RANGE)) != NULL) { for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++) { if (attr->values[i].range.lower < lowerpagerange || attr->values[i].range.lower > attr->values[i].range.upper) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad page-ranges values %d-%d."), attr->values[i].range.lower, attr->values[i].range.upper); return (NULL); } lowerpagerange = attr->values[i].range.upper + 1; } } /* * Do media selection as needed... */ if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) && !ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) && _ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact)) { if (!exact && (media_col = ippFindAttribute(con->request, "media-col", IPP_TAG_BEGIN_COLLECTION)) != NULL) { send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins.")); unsup_col = ippNew(); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-bottom-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-bottom-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-left-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-left-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-right-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-right-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-top-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-top-margin", media_margin->values[0].integer); ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col", unsup_col); ippDelete(unsup_col); } } /* * Make sure we aren't over our limit... */ if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) cupsdCleanJobs(); if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) { send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs.")); return (NULL); } if ((i = check_quotas(con, printer)) < 0) { send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached.")); return (NULL); } else if (i == 0) { send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print.")); return (NULL); } /* * Create the job and set things up... */ if ((attr = ippFindAttribute(con->request, "job-priority", IPP_TAG_INTEGER)) != NULL) priority = attr->values[0].integer; else { if ((val = cupsGetOption("job-priority", printer->num_options, printer->options)) != NULL) priority = atoi(val); else priority = 50; ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority", priority); } if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL) ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled"); else if ((attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_NAMELANG) || attr->num_values != 1) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: Wrong type or count.")); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } else if (!ippValidateAttribute(attr)) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"), cupsLastErrorString()); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } attr = ippFindAttribute(con->request, "requesting-user-name", IPP_TAG_NAME); if (attr && !ippValidateAttribute(attr)) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad requesting-user-name value: %s"), cupsLastErrorString()); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } if ((job = cupsdAddJob(priority, printer->name)) == NULL) { send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to add job for destination \"%s\"."), printer->name); return (NULL); } job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE); job->attrs = con->request; job->dirty = 1; con->request = ippNewRequest(job->attrs->request.op.operation_id); cupsdMarkDirty(CUPSD_DIRTY_JOBS); add_job_uuid(job); apply_printer_defaults(printer, job); if (con->username[0]) { cupsdSetString(&job->username, con->username); if (attr) ippSetString(job->attrs, &attr, 0, con->username); } else if (attr) { cupsdLogMessage(CUPSD_LOG_DEBUG, "add_job: requesting-user-name=\"%s\"", attr->values[0].string.text); cupsdSetString(&job->username, attr->values[0].string.text); } else cupsdSetString(&job->username, "anonymous"); if (!attr) ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-user-name", NULL, job->username); else { ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); ippSetName(job->attrs, &attr, "job-originating-user-name"); } if (con->username[0] || auth_info) { save_auth_info(con, job, auth_info); /* * Remove the auth-info attribute from the attribute data... */ if (auth_info) ippDeleteAttribute(job->attrs, auth_info); } if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL) cupsdSetString(&(job->name), attr->values[0].string.text); if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name", IPP_TAG_ZERO)) != NULL) { /* * Request contains a job-originating-host-name attribute; validate it... */ if (attr->value_tag != IPP_TAG_NAME || attr->num_values != 1 || strcmp(con->http->hostname, "localhost")) { /* * Can't override the value if we aren't connected via localhost. * Also, we can only have 1 value and it must be a name value. */ ippDeleteAttribute(job->attrs, attr); ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname); } else ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); } else { /* * No job-originating-host-name attribute, so use the hostname from * the connection... */ ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname); } ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed"); ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL))); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing"); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed"); ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL)); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing"); /* * Add remaining job attributes... */ ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id); job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", IPP_JOB_STOPPED); job->state_value = (ipp_jstate_t)job->state->values[0].integer; job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-incoming"); job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0); job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-media-sheets-completed", 0); ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL, printer->uri); if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL) attr->values[0].integer = 0; else ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0); if ((attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_KEYWORD)) == NULL) attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME); if (!attr) { if ((val = cupsGetOption("job-hold-until", printer->num_options, printer->options)) == NULL) val = "no-hold"; attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-hold-until", NULL, val); } if (printer->holding_new_jobs) { /* * Hold all new jobs on this printer... */ if (attr && strcmp(attr->values[0].string.text, "no-hold")) cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0); else cupsdSetJobHoldUntil(job, "indefinite", 0); job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create"); } else if (attr && strcmp(attr->values[0].string.text, "no-hold")) { /* * Hold job until specified time... */ cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0); job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified"); } else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB) { job->hold_until = time(NULL) + MultipleOperationTimeout; job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; } else { job->state->values[0].integer = IPP_JOB_PENDING; job->state_value = IPP_JOB_PENDING; ippSetString(job->attrs, &job->reasons, 0, "none"); } if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification) { /* * Add job sheets options... */ if ((attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) == NULL) { cupsdLogMessage(CUPSD_LOG_DEBUG, "Adding default job-sheets values \"%s,%s\"...", printer->job_sheets[0], printer->job_sheets[1]); attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets", 2, NULL, NULL); ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]); ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]); } job->job_sheets = attr; /* * Enforce classification level if set... */ if (Classification) { cupsdLogMessage(CUPSD_LOG_INFO, "Classification=\"%s\", ClassifyOverride=%d", Classification ? Classification : "(null)", ClassifyOverride); if (ClassifyOverride) { if (!strcmp(attr->values[0].string.text, "none") && (attr->num_values == 1 || !strcmp(attr->values[1].string.text, "none"))) { /* * Force the leading banner to have the classification on it... */ ippSetString(job->attrs, &attr, 0, Classification); cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,none\", " "job-originating-user-name=\"%s\"", Classification, job->username); } else if (attr->num_values == 2 && strcmp(attr->values[0].string.text, attr->values[1].string.text) && strcmp(attr->values[0].string.text, "none") && strcmp(attr->values[1].string.text, "none")) { /* * Can't put two different security markings on the same document! */ ippSetString(job->attrs, &attr, 1, attr->values[0].string.text); cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); } else if (strcmp(attr->values[0].string.text, Classification) && strcmp(attr->values[0].string.text, "none") && (attr->num_values == 1 || (strcmp(attr->values[1].string.text, Classification) && strcmp(attr->values[1].string.text, "none")))) { if (attr->num_values == 1) cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION OVERRIDDEN " "job-sheets=\"%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, job->username); else cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION OVERRIDDEN " "job-sheets=\"%s,%s\",fffff " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); } } else if (strcmp(attr->values[0].string.text, Classification) && (attr->num_values == 1 || strcmp(attr->values[1].string.text, Classification))) { /* * Force the banner to have the classification on it... */ if (attr->num_values > 1 && !strcmp(attr->values[0].string.text, attr->values[1].string.text)) { ippSetString(job->attrs, &attr, 0, Classification); ippSetString(job->attrs, &attr, 1, Classification); } else { if (attr->num_values == 1 || strcmp(attr->values[0].string.text, "none")) ippSetString(job->attrs, &attr, 0, Classification); if (attr->num_values > 1 && strcmp(attr->values[1].string.text, "none")) ippSetString(job->attrs, &attr, 1, Classification); } if (attr->num_values > 1) cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); else cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s\", " "job-originating-user-name=\"%s\"", Classification, job->username); } } /* * See if we need to add the starting sheet... */ if (!(printer->type & CUPS_PRINTER_REMOTE)) { cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".", attr->values[0].string.text); if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0) { cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE, "Aborting job because the start banner could not be " "copied."); return (NULL); } cupsdUpdateQuota(printer, job->username, 0, kbytes); } } else if ((attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL) job->job_sheets = attr; /* * Fill in the response info... */ httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL, con->clientname, con->clientport, "/jobs/%d", job->id); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL, job_uri); ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id); ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", job->state_value); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, ""); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, job->reasons->values[0].string.text); con->response->request.status.status_code = IPP_OK; /* * Add any job subscriptions... */ add_job_subscriptions(con, job); /* * Set all but the first two attributes to the job attributes group... */ for (attr = job->attrs->attrs->next->next; attr; attr = attr->next) attr->group_tag = IPP_TAG_JOB; /* * Fire the "job created" event... */ cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created."); /* * Return the new job... */ return (job); }
169,380
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: GDataFile::GDataFile(GDataDirectory* parent, GDataDirectoryService* directory_service) : GDataEntry(parent, directory_service), kind_(DocumentEntry::UNKNOWN), is_hosted_document_(false) { file_info_.is_directory = false; } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
GDataFile::GDataFile(GDataDirectory* parent, GDataFile::GDataFile(GDataDirectoryService* directory_service) : GDataEntry(directory_service), kind_(DocumentEntry::UNKNOWN), is_hosted_document_(false) { file_info_.is_directory = false; }
171,492
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_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) < 0) errExit("chown"); if (chmod(dest, S_IRUSR | S_IWUSR) < 0) errExit("chmod"); unlink(src); } Commit Message: security fix CWE ID: CWE-269
static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user fs_logger2("clone", dest); unlink(src); }
170,096
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 MediaElementAudioSourceNode::OnCurrentSrcChanged(const KURL& current_src) { GetMediaElementAudioSourceHandler().OnCurrentSrcChanged(current_src); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceNode::OnCurrentSrcChanged(const KURL& current_src) {
173,146
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 InputHandlerProxy::InjectScrollbarGestureScroll( const WebInputEvent::Type type, const blink::WebFloatPoint& position_in_widget, const cc::InputHandlerPointerResult& pointer_result, const LatencyInfo& latency_info, const base::TimeTicks original_timestamp) { gfx::Vector2dF scroll_delta(pointer_result.scroll_offset.x(), pointer_result.scroll_offset.y()); std::unique_ptr<WebGestureEvent> synthetic_gesture_event = GenerateInjectedScrollGesture( type, original_timestamp, blink::WebGestureDevice::kScrollbar, position_in_widget, scroll_delta, pointer_result.scroll_units); WebScopedInputEvent web_scoped_gesture_event( synthetic_gesture_event.release()); LatencyInfo scrollbar_latency_info(latency_info); scrollbar_latency_info.set_source_event_type(ui::SourceEventType::SCROLLBAR); DCHECK(!scrollbar_latency_info.FindLatency( ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_IMPL_COMPONENT, nullptr)); if (type == WebInputEvent::Type::kGestureScrollBegin) { last_injected_gesture_was_begin_ = true; } else { if (type == WebInputEvent::Type::kGestureScrollUpdate) { scrollbar_latency_info.AddLatencyNumberWithTimestamp( (last_injected_gesture_was_begin_) ? ui::INPUT_EVENT_LATENCY_FIRST_SCROLL_UPDATE_ORIGINAL_COMPONENT : ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT, original_timestamp, 1); } last_injected_gesture_was_begin_ = false; } std::unique_ptr<EventWithCallback> gesture_event_with_callback_update = std::make_unique<EventWithCallback>( std::move(web_scoped_gesture_event), scrollbar_latency_info, original_timestamp, original_timestamp, nullptr); bool needs_animate_input = compositor_event_queue_->empty(); compositor_event_queue_->Queue(std::move(gesture_event_with_callback_update), original_timestamp); if (needs_animate_input) input_handler_->SetNeedsAnimateInput(); } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <[email protected]> > Reviewed-by: David Bokan <[email protected]> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281
void InputHandlerProxy::InjectScrollbarGestureScroll( const WebInputEvent::Type type, const blink::WebFloatPoint& position_in_widget, const cc::InputHandlerPointerResult& pointer_result, const LatencyInfo& latency_info, const base::TimeTicks original_timestamp) { gfx::Vector2dF scroll_delta(pointer_result.scroll_offset.x(), pointer_result.scroll_offset.y()); std::unique_ptr<WebGestureEvent> synthetic_gesture_event = GenerateInjectedScrollGesture( type, original_timestamp, blink::WebGestureDevice::kScrollbar, position_in_widget, scroll_delta, pointer_result.scroll_units); WebScopedInputEvent web_scoped_gesture_event( synthetic_gesture_event.release()); LatencyInfo scrollbar_latency_info(latency_info); scrollbar_latency_info.set_source_event_type(ui::SourceEventType::SCROLLBAR); DCHECK(!scrollbar_latency_info.FindLatency( ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_IMPL_COMPONENT, nullptr)); std::unique_ptr<EventWithCallback> gesture_event_with_callback_update = std::make_unique<EventWithCallback>( std::move(web_scoped_gesture_event), scrollbar_latency_info, original_timestamp, original_timestamp, nullptr); bool needs_animate_input = compositor_event_queue_->empty(); compositor_event_queue_->Queue(std::move(gesture_event_with_callback_update), original_timestamp); if (needs_animate_input) input_handler_->SetNeedsAnimateInput(); }
172,432
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 h2_process_demux(struct h2c *h2c) { struct h2s *h2s; if (h2c->st0 >= H2_CS_ERROR) return; if (unlikely(h2c->st0 < H2_CS_FRAME_H)) { if (h2c->st0 == H2_CS_PREFACE) { if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } h2c->max_id = 0; h2c->st0 = H2_CS_SETTINGS1; } if (h2c->st0 == H2_CS_SETTINGS1) { struct h2_fh hdr; /* ensure that what is pending is a valid SETTINGS frame * without an ACK. */ if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } /* that's OK, switch to FRAME_P to process it */ h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; } } /* process as many incoming frames as possible below */ while (h2c->dbuf->i) { int ret = 0; if (h2c->st0 >= H2_CS_ERROR) break; if (h2c->st0 == H2_CS_FRAME_H) { struct h2_fh hdr; if (!h2_peek_frame_hdr(h2c->dbuf, &hdr)) break; if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) { h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR; break; } h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; h2_skip_frame_hdr(h2c->dbuf); } /* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */ h2s = h2c_st_by_id(h2c, h2c->dsi); if (h2c->st0 == H2_CS_FRAME_E) goto strm_err; if (h2s->st == H2_SS_IDLE && h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than HEADERS or PRIORITY in * this state MUST be treated as a connection error */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR; break; } if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE && h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than WU/PRIO/RST in * this state MUST be treated as a stream error */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* Below the management of frames received in closed state is a * bit hackish because the spec makes strong differences between * streams closed by receiving RST, sending RST, and seeing ES * in both directions. In addition to this, the creation of a * new stream reusing the identifier of a closed one will be * detected here. Given that we cannot keep track of all closed * streams forever, we consider that unknown closed streams were * closed on RST received, which allows us to respond with an * RST without breaking the connection (eg: to abort a transfer). * Some frames have to be silently ignored as well. */ if (h2s->st == H2_SS_CLOSED && h2c->dsi) { if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) { /* #5.1.1: The identifier of a newly * established stream MUST be numerically * greater than all streams that the initiating * endpoint has opened or reserved. This * governs streams that are opened using a * HEADERS frame and streams that are reserved * using PUSH_PROMISE. An endpoint that * receives an unexpected stream identifier * MUST respond with a connection error. */ h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } if (h2s->flags & H2_SF_RST_RCVD) { /* RFC7540#5.1:closed: an endpoint that * receives any frame other than PRIORITY after * receiving a RST_STREAM MUST treat that as a * stream error of type STREAM_CLOSED. * * Note that old streams fall into this category * and will lead to an RST being sent. */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* RFC7540#5.1:closed: if this state is reached as a * result of sending a RST_STREAM frame, the peer that * receives the RST_STREAM might have already sent * frames on the stream that cannot be withdrawn. An * endpoint MUST ignore frames that it receives on * closed streams after it has sent a RST_STREAM * frame. An endpoint MAY choose to limit the period * over which it ignores frames and treat frames that * arrive after this time as being in error. */ if (!(h2s->flags & H2_SF_RST_SENT)) { /* RFC7540#5.1:closed: any frame other than * PRIO/WU/RST in this state MUST be treated as * a connection error */ if (h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY && h2c->dft != H2_FT_WINDOW_UPDATE) { h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } } } #if 0 /* graceful shutdown, ignore streams whose ID is higher than * the one advertised in GOAWAY. RFC7540#6.8. */ if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) { ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; goto strm_err; } #endif switch (h2c->dft) { case H2_FT_SETTINGS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_settings(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_settings(h2c); break; case H2_FT_PING: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_ping(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_ping(h2c); break; case H2_FT_WINDOW_UPDATE: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_window_update(h2c, h2s); break; case H2_FT_CONTINUATION: /* we currently don't support CONTINUATION frames since * we have nowhere to store the partial HEADERS frame. * Let's abort the stream on an INTERNAL_ERROR here. */ if (h2c->st0 == H2_CS_FRAME_P) { h2s_error(h2s, H2_ERR_INTERNAL_ERROR); h2c->st0 = H2_CS_FRAME_E; } break; case H2_FT_HEADERS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_headers(h2c, h2s); break; case H2_FT_DATA: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_data(h2c, h2s); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_send_strm_wu(h2c); break; case H2_FT_PRIORITY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_priority(h2c); break; case H2_FT_RST_STREAM: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_rst_stream(h2c, h2s); break; case H2_FT_GOAWAY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_goaway(h2c); break; case H2_FT_PUSH_PROMISE: /* not permitted here, RFC7540#5.1 */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); break; /* implement all extra frame types here */ default: /* drop frames that we ignore. They may be larger than * the buffer so we drain all of their contents until * we reach the end. */ ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; } strm_err: /* We may have to send an RST if not done yet */ if (h2s->st == H2_SS_ERROR) h2c->st0 = H2_CS_FRAME_E; if (h2c->st0 == H2_CS_FRAME_E) ret = h2c_send_rst_stream(h2c, h2s); /* error or missing data condition met above ? */ if (ret <= 0) break; if (h2c->st0 != H2_CS_FRAME_H) { bi_del(h2c->dbuf, h2c->dfl); h2c->st0 = H2_CS_FRAME_H; } } if (h2c->rcvd_c > 0 && !(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM))) h2c_send_conn_wu(h2c); fail: /* we can go here on missing data, blocked response or error */ return; } Commit Message: CWE ID: CWE-119
static void h2_process_demux(struct h2c *h2c) { struct h2s *h2s; if (h2c->st0 >= H2_CS_ERROR) return; if (unlikely(h2c->st0 < H2_CS_FRAME_H)) { if (h2c->st0 == H2_CS_PREFACE) { if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } h2c->max_id = 0; h2c->st0 = H2_CS_SETTINGS1; } if (h2c->st0 == H2_CS_SETTINGS1) { struct h2_fh hdr; /* ensure that what is pending is a valid SETTINGS frame * without an ACK. */ if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } /* that's OK, switch to FRAME_P to process it */ h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; } } /* process as many incoming frames as possible below */ while (h2c->dbuf->i) { int ret = 0; if (h2c->st0 >= H2_CS_ERROR) break; if (h2c->st0 == H2_CS_FRAME_H) { struct h2_fh hdr; if (!h2_peek_frame_hdr(h2c->dbuf, &hdr)) break; if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) { h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR; break; } h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; h2_skip_frame_hdr(h2c->dbuf); } /* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */ h2s = h2c_st_by_id(h2c, h2c->dsi); if (h2c->st0 == H2_CS_FRAME_E) goto strm_err; if (h2s->st == H2_SS_IDLE && h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than HEADERS or PRIORITY in * this state MUST be treated as a connection error */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR; break; } if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE && h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than WU/PRIO/RST in * this state MUST be treated as a stream error */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* Below the management of frames received in closed state is a * bit hackish because the spec makes strong differences between * streams closed by receiving RST, sending RST, and seeing ES * in both directions. In addition to this, the creation of a * new stream reusing the identifier of a closed one will be * detected here. Given that we cannot keep track of all closed * streams forever, we consider that unknown closed streams were * closed on RST received, which allows us to respond with an * RST without breaking the connection (eg: to abort a transfer). * Some frames have to be silently ignored as well. */ if (h2s->st == H2_SS_CLOSED && h2c->dsi) { if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) { /* #5.1.1: The identifier of a newly * established stream MUST be numerically * greater than all streams that the initiating * endpoint has opened or reserved. This * governs streams that are opened using a * HEADERS frame and streams that are reserved * using PUSH_PROMISE. An endpoint that * receives an unexpected stream identifier * MUST respond with a connection error. */ h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } if (h2s->flags & H2_SF_RST_RCVD) { /* RFC7540#5.1:closed: an endpoint that * receives any frame other than PRIORITY after * receiving a RST_STREAM MUST treat that as a * stream error of type STREAM_CLOSED. * * Note that old streams fall into this category * and will lead to an RST being sent. */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* RFC7540#5.1:closed: if this state is reached as a * result of sending a RST_STREAM frame, the peer that * receives the RST_STREAM might have already sent * frames on the stream that cannot be withdrawn. An * endpoint MUST ignore frames that it receives on * closed streams after it has sent a RST_STREAM * frame. An endpoint MAY choose to limit the period * over which it ignores frames and treat frames that * arrive after this time as being in error. */ if (!(h2s->flags & H2_SF_RST_SENT)) { /* RFC7540#5.1:closed: any frame other than * PRIO/WU/RST in this state MUST be treated as * a connection error */ if (h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY && h2c->dft != H2_FT_WINDOW_UPDATE) { h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } } } #if 0 /* graceful shutdown, ignore streams whose ID is higher than * the one advertised in GOAWAY. RFC7540#6.8. */ if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) { ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; goto strm_err; } #endif switch (h2c->dft) { case H2_FT_SETTINGS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_settings(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_settings(h2c); break; case H2_FT_PING: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_ping(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_ping(h2c); break; case H2_FT_WINDOW_UPDATE: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_window_update(h2c, h2s); break; case H2_FT_CONTINUATION: /* we currently don't support CONTINUATION frames since * we have nowhere to store the partial HEADERS frame. * Let's abort the stream on an INTERNAL_ERROR here. */ if (h2c->st0 == H2_CS_FRAME_P) { h2s_error(h2s, H2_ERR_INTERNAL_ERROR); h2c->st0 = H2_CS_FRAME_E; } break; case H2_FT_HEADERS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_headers(h2c, h2s); break; case H2_FT_DATA: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_data(h2c, h2s); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_send_strm_wu(h2c); break; case H2_FT_PRIORITY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_priority(h2c); break; case H2_FT_RST_STREAM: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_rst_stream(h2c, h2s); break; case H2_FT_GOAWAY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_goaway(h2c); break; case H2_FT_PUSH_PROMISE: /* not permitted here, RFC7540#5.1 */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); break; /* implement all extra frame types here */ default: /* drop frames that we ignore. They may be larger than * the buffer so we drain all of their contents until * we reach the end. */ ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; } strm_err: /* We may have to send an RST if not done yet */ if (h2s->st == H2_SS_ERROR) h2c->st0 = H2_CS_FRAME_E; if (h2c->st0 == H2_CS_FRAME_E) ret = h2c_send_rst_stream(h2c, h2s); /* error or missing data condition met above ? */ if (ret <= 0) break; if (h2c->st0 != H2_CS_FRAME_H) { bi_del(h2c->dbuf, h2c->dfl); h2c->st0 = H2_CS_FRAME_H; } } if (h2c->rcvd_c > 0 && !(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM))) h2c_send_conn_wu(h2c); fail: /* we can go here on missing data, blocked response or error */ return; }
164,899
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 ScreenOrientationDispatcherHost::OnUnlockRequest( RenderFrameHost* render_frame_host) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_.get()) return; provider_->UnlockOrientation(); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void ScreenOrientationDispatcherHost::OnUnlockRequest( RenderFrameHost* render_frame_host) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_) return; provider_->UnlockOrientation(); }
171,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 int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cdef_t *cdef = &box->data.cdef; jp2_cdefchan_t *chan; unsigned int channo; if (jp2_getuint16(in, &cdef->numchans)) { return -1; } if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) { return -1; } for (channo = 0; channo < cdef->numchans; ++channo) { chan = &cdef->ents[channo]; if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || jp2_getuint16(in, &chan->assoc)) { return -1; } } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cdef_t *cdef = &box->data.cdef; jp2_cdefchan_t *chan; unsigned int channo; cdef->ents = 0; if (jp2_getuint16(in, &cdef->numchans)) { return -1; } if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) { return -1; } for (channo = 0; channo < cdef->numchans; ++channo) { chan = &cdef->ents[channo]; if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || jp2_getuint16(in, &chan->assoc)) { return -1; } } return 0; }
168,321
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 splice_pipe_to_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, nbuf; bool input_wakeup = false; retry: ret = ipipe_prep(ipipe, flags); if (ret) return ret; ret = opipe_prep(opipe, flags); if (ret) return ret; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } if (!ipipe->nrbufs && !ipipe->writers) break; /* * Cannot make any progress, because either the input * pipe is empty or the output pipe is full. */ if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { /* Already processed some buffers, break */ if (ret) break; if (flags & SPLICE_F_NONBLOCK) { ret = -EAGAIN; break; } /* * We raced with another reader/writer and haven't * managed to process any buffers. A zero return * value means EOF, so retry instead. */ pipe_unlock(ipipe); pipe_unlock(opipe); goto retry; } ibuf = ipipe->bufs + ipipe->curbuf; nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); obuf = opipe->bufs + nbuf; if (len >= ibuf->len) { /* * Simply move the whole buffer from ipipe to opipe */ *obuf = *ibuf; ibuf->ops = NULL; opipe->nrbufs++; ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); ipipe->nrbufs--; input_wakeup = true; } else { /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = len; opipe->nrbufs++; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } ret += obuf->len; len -= obuf->len; } while (len); pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); if (input_wakeup) wakeup_pipe_writers(ipipe); return ret; } Commit Message: fs: prevent page refcount overflow in pipe_buf_get Change pipe_buf_get() to return a bool indicating whether it succeeded in raising the refcount of the page (if the thing in the pipe is a page). This removes another mechanism for overflowing the page refcount. All callers converted to handle a failure. Reported-by: Jann Horn <[email protected]> Signed-off-by: Matthew Wilcox <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-416
static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, nbuf; bool input_wakeup = false; retry: ret = ipipe_prep(ipipe, flags); if (ret) return ret; ret = opipe_prep(opipe, flags); if (ret) return ret; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } if (!ipipe->nrbufs && !ipipe->writers) break; /* * Cannot make any progress, because either the input * pipe is empty or the output pipe is full. */ if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { /* Already processed some buffers, break */ if (ret) break; if (flags & SPLICE_F_NONBLOCK) { ret = -EAGAIN; break; } /* * We raced with another reader/writer and haven't * managed to process any buffers. A zero return * value means EOF, so retry instead. */ pipe_unlock(ipipe); pipe_unlock(opipe); goto retry; } ibuf = ipipe->bufs + ipipe->curbuf; nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); obuf = opipe->bufs + nbuf; if (len >= ibuf->len) { /* * Simply move the whole buffer from ipipe to opipe */ *obuf = *ibuf; ibuf->ops = NULL; opipe->nrbufs++; ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); ipipe->nrbufs--; input_wakeup = true; } else { /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ if (!pipe_buf_get(ipipe, ibuf)) { if (ret == 0) ret = -EFAULT; break; } *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = len; opipe->nrbufs++; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } ret += obuf->len; len -= obuf->len; } while (len); pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); if (input_wakeup) wakeup_pipe_writers(ipipe); return ret; }
170,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id) { int r; struct kvm_vcpu *vcpu, *v; vcpu = kvm_arch_vcpu_create(kvm, id); if (IS_ERR(vcpu)) return PTR_ERR(vcpu); preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops); r = kvm_arch_vcpu_setup(vcpu); if (r) goto vcpu_destroy; mutex_lock(&kvm->lock); if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) { r = -EINVAL; goto unlock_vcpu_destroy; } kvm_for_each_vcpu(r, v, kvm) if (v->vcpu_id == id) { r = -EEXIST; goto unlock_vcpu_destroy; } BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]); /* Now it's all set up, let userspace reach it */ kvm_get_kvm(kvm); r = create_vcpu_fd(vcpu); if (r < 0) { kvm_put_kvm(kvm); goto unlock_vcpu_destroy; } kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu; smp_wmb(); atomic_inc(&kvm->online_vcpus); mutex_unlock(&kvm->lock); return r; unlock_vcpu_destroy: mutex_unlock(&kvm->lock); vcpu_destroy: kvm_arch_vcpu_destroy(vcpu); return r; } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <[email protected]> Signed-off-by: Avi Kivity <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-399
static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id) { int r; struct kvm_vcpu *vcpu, *v; vcpu = kvm_arch_vcpu_create(kvm, id); if (IS_ERR(vcpu)) return PTR_ERR(vcpu); preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops); r = kvm_arch_vcpu_setup(vcpu); if (r) goto vcpu_destroy; mutex_lock(&kvm->lock); if (!kvm_vcpu_compatible(vcpu)) { r = -EINVAL; goto unlock_vcpu_destroy; } if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) { r = -EINVAL; goto unlock_vcpu_destroy; } kvm_for_each_vcpu(r, v, kvm) if (v->vcpu_id == id) { r = -EEXIST; goto unlock_vcpu_destroy; } BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]); /* Now it's all set up, let userspace reach it */ kvm_get_kvm(kvm); r = create_vcpu_fd(vcpu); if (r < 0) { kvm_put_kvm(kvm); goto unlock_vcpu_destroy; } kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu; smp_wmb(); atomic_inc(&kvm->online_vcpus); mutex_unlock(&kvm->lock); return r; unlock_vcpu_destroy: mutex_unlock(&kvm->lock); vcpu_destroy: kvm_arch_vcpu_destroy(vcpu); return r; }
165,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: int sas_smp_get_phy_events(struct sas_phy *phy) { int res; u8 *req; u8 *resp; struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent); struct domain_device *dev = sas_find_dev_by_rphy(rphy); req = alloc_smp_req(RPEL_REQ_SIZE); if (!req) return -ENOMEM; resp = alloc_smp_resp(RPEL_RESP_SIZE); if (!resp) { kfree(req); return -ENOMEM; } req[1] = SMP_REPORT_PHY_ERR_LOG; req[9] = phy->number; res = smp_execute_task(dev, req, RPEL_REQ_SIZE, resp, RPEL_RESP_SIZE); if (!res) goto out; phy->invalid_dword_count = scsi_to_u32(&resp[12]); phy->running_disparity_error_count = scsi_to_u32(&resp[16]); phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]); phy->phy_reset_problem_count = scsi_to_u32(&resp[24]); out: kfree(resp); return res; } Commit Message: scsi: libsas: fix memory leak in sas_smp_get_phy_events() We've got a memory leak with the following producer: while true; do cat /sys/class/sas_phy/phy-1:0:12/invalid_dword_count >/dev/null; done The buffer req is allocated and not freed after we return. Fix it. Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver") Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: chenqilin <[email protected]> CC: chenxiang <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-772
int sas_smp_get_phy_events(struct sas_phy *phy) { int res; u8 *req; u8 *resp; struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent); struct domain_device *dev = sas_find_dev_by_rphy(rphy); req = alloc_smp_req(RPEL_REQ_SIZE); if (!req) return -ENOMEM; resp = alloc_smp_resp(RPEL_RESP_SIZE); if (!resp) { kfree(req); return -ENOMEM; } req[1] = SMP_REPORT_PHY_ERR_LOG; req[9] = phy->number; res = smp_execute_task(dev, req, RPEL_REQ_SIZE, resp, RPEL_RESP_SIZE); if (!res) goto out; phy->invalid_dword_count = scsi_to_u32(&resp[12]); phy->running_disparity_error_count = scsi_to_u32(&resp[16]); phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]); phy->phy_reset_problem_count = scsi_to_u32(&resp[24]); out: kfree(req); kfree(resp); return res; }
169,305
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 jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = splitbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int m; int hstartcol; /* Get a buffer. */ if (bufsize > QMFB_SPLITBUFSIZE) { if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide in this case. */ abort(); } } if (numrows >= 2) { hstartcol = (numrows + 1 - parity) >> 1; m = numrows - hstartcol; /* Save the samples destined for the highpass channel. */ n = m; dstptr = buf; srcptr = &a[(1 - parity) * stride]; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += JPC_QMFB_COLGRPSIZE; srcptr += stride << 1; } /* Copy the appropriate samples into the lowpass channel. */ dstptr = &a[(1 - parity) * stride]; srcptr = &a[(2 - parity) * stride]; n = numrows - m - (!parity); while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartcol * stride]; srcptr = buf; n = m; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += JPC_QMFB_COLGRPSIZE; } } /* If the split buffer was allocated on the heap, free this memory. */ if (buf != splitbuf) { jas_free(buf); } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119
void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = splitbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int m; int hstartrow; /* Get a buffer. */ if (bufsize > QMFB_SPLITBUFSIZE) { if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide in this case. */ abort(); } } if (numrows >= 2) { hstartrow = (numrows + 1 - parity) >> 1; // ORIGINAL (WRONG): m = (parity) ? hstartrow : (numrows - hstartrow); m = numrows - hstartrow; /* Save the samples destined for the highpass channel. */ n = m; dstptr = buf; srcptr = &a[(1 - parity) * stride]; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += JPC_QMFB_COLGRPSIZE; srcptr += stride << 1; } /* Copy the appropriate samples into the lowpass channel. */ dstptr = &a[(1 - parity) * stride]; srcptr = &a[(2 - parity) * stride]; n = numrows - m - (!parity); while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartrow * stride]; srcptr = buf; n = m; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += JPC_QMFB_COLGRPSIZE; } } /* If the split buffer was allocated on the heap, free this memory. */ if (buf != splitbuf) { jas_free(buf); } }
169,446
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: Tracks::~Tracks() { Track** i = m_trackEntries; Track** const j = m_trackEntriesEnd; while (i != j) { Track* const pTrack = *i++; delete pTrack; } delete[] m_trackEntries; } 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
Tracks::~Tracks()
174,473
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: size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) //RAW or within MP4 { mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object)); if (mp4 == NULL) return 0; memset(mp4, 0, sizeof(mp4object)); #ifdef _WINDOWS fopen_s(&mp4->mediafp, filename, "rb"); #else mp4->mediafp = fopen(filename, "rb"); #endif if (mp4->mediafp) { uint32_t qttag, qtsize32, skip, type = 0, subtype = 0, num; size_t len; int32_t nest = 0; uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; uint64_t lastsize = 0, qtsize; do { len = fread(&qtsize32, 1, 4, mp4->mediafp); len += fread(&qttag, 1, 4, mp4->mediafp); if (len == 8) { if (!VALID_FOURCC(qttag)) { LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR); NESTSIZE(lastsize - 8); continue; } qtsize32 = BYTESWAP32(qtsize32); if (qtsize32 == 1) // 64-bit Atom { fread(&qtsize, 1, 8, mp4->mediafp); qtsize = BYTESWAP64(qtsize) - 8; } else qtsize = qtsize32; nest++; if (qtsize < 8) break; if (nest >= MAX_NEST_LEVEL) break; nestsize[nest] = qtsize; lastsize = qtsize; #if PRINT_MP4_STRUCTURE for (int i = 1; i < nest; i++) printf(" "); printf("%c%c%c%c (%lld)\n", (qttag & 0xff), ((qttag >> 8) & 0xff), ((qttag >> 16) & 0xff), ((qttag >> 24) & 0xff), qtsize); if (qttag == MAKEID('m', 'd', 'a', 't') || qttag == MAKEID('f', 't', 'y', 'p') || qttag == MAKEID('u', 'd', 't', 'a')) { LONGSEEK(mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); continue; } #else if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms qttag != MAKEID('m', 'v', 'h', 'd') && qttag != MAKEID('t', 'r', 'a', 'k') && qttag != MAKEID('m', 'd', 'i', 'a') && qttag != MAKEID('m', 'd', 'h', 'd') && qttag != MAKEID('m', 'i', 'n', 'f') && qttag != MAKEID('g', 'm', 'i', 'n') && qttag != MAKEID('d', 'i', 'n', 'f') && qttag != MAKEID('a', 'l', 'i', 's') && qttag != MAKEID('s', 't', 's', 'd') && qttag != MAKEID('a', 'l', 'i', 's') && qttag != MAKEID('a', 'l', 'i', 's') && qttag != MAKEID('s', 't', 'b', 'l') && qttag != MAKEID('s', 't', 't', 's') && qttag != MAKEID('s', 't', 's', 'c') && qttag != MAKEID('s', 't', 's', 'z') && qttag != MAKEID('s', 't', 'c', 'o') && qttag != MAKEID('c', 'o', '6', '4') && qttag != MAKEID('h', 'd', 'l', 'r')) { LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else #endif if (qttag == MAKEID('m', 'v', 'h', 'd')) //mvhd movie header { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&mp4->clockdemon, 1, 4, mp4->mediafp); mp4->clockdemon = BYTESWAP32(mp4->clockdemon); len += fread(&mp4->clockcount, 1, 4, mp4->mediafp); mp4->clockcount = BYTESWAP32(mp4->clockcount); LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over mvhd NESTSIZE(qtsize); } else if (qttag == MAKEID('m', 'd', 'h', 'd')) //mdhd media header { media_header md; len = fread(&md, 1, sizeof(md), mp4->mediafp); if (len == sizeof(md)) { md.creation_time = BYTESWAP32(md.creation_time); md.modification_time = BYTESWAP32(md.modification_time); md.time_scale = BYTESWAP32(md.time_scale); md.duration = BYTESWAP32(md.duration); mp4->trak_clockdemon = md.time_scale; mp4->trak_clockcount = md.duration; if (mp4->videolength == 0.0) // Get the video length from the first track { mp4->videolength = (float)((double)mp4->trak_clockcount / (double)mp4->trak_clockdemon); } } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over mvhd NESTSIZE(qtsize); } else if (qttag == MAKEID('h', 'd', 'l', 'r')) //hldr { uint32_t temp; len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&temp, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak. if (temp != MAKEID('a', 'l', 'i', 's')) type = temp; LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over hldr NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 's', 'd')) //read the sample decription to determine the type of metadata { if (type == traktype) //like meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&subtype, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak. if (len == 16) { if (subtype != traksubtype) // MP4 metadata { type = 0; // MP4 } } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsd } else LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 's', 'c')) // metadata stsc - offset chunks { if (type == traktype) // meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 12 <= qtsize - 8 - len) { mp4->metastsc_count = num; if (mp4->metastsc) free(mp4->metastsc); mp4->metastsc = (SampleToChunk *)malloc(num * 12); if (mp4->metastsc) { uint32_t total_stsc = num; len += fread(mp4->metastsc, 1, num * sizeof(SampleToChunk), mp4->mediafp); do { num--; mp4->metastsc[num].chunk_num = BYTESWAP32(mp4->metastsc[num].chunk_num); mp4->metastsc[num].samples = BYTESWAP32(mp4->metastsc[num].samples); mp4->metastsc[num].id = BYTESWAP32(mp4->metastsc[num].id); } while (num > 0); } if (mp4->metastsc_count == 1 && mp4->metastsc[0].samples == 1) // Simplify if the stsc is not reporting any grouped chunks. { if (mp4->metastsc) free(mp4->metastsc); mp4->metastsc = NULL; mp4->metastsc_count = 0; } } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsx } else LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 's', 'z')) // metadata stsz - sizes { if (type == traktype) // meta { uint32_t equalsamplesize; len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&equalsamplesize, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 4 <= qtsize - 8 - len) { mp4->metasize_count = num; if (mp4->metasizes) free(mp4->metasizes); mp4->metasizes = (uint32_t *)malloc(num * 4); if (mp4->metasizes) { if (equalsamplesize == 0) { len += fread(mp4->metasizes, 1, num * 4, mp4->mediafp); do { num--; mp4->metasizes[num] = BYTESWAP32(mp4->metasizes[num]); } while (num > 0); } else { equalsamplesize = BYTESWAP32(equalsamplesize); do { num--; mp4->metasizes[num] = equalsamplesize; } while (num > 0); } } } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsz } else LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 'c', 'o')) // metadata stco - offsets { if (type == traktype) // meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 4 <= qtsize - 8 - len) { if (mp4->metastsc_count > 0 && num != mp4->metasize_count) { mp4->indexcount = mp4->metasize_count; if (mp4->metaoffsets) free(mp4->metaoffsets); mp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8); if (mp4->metaoffsets) { uint32_t *metaoffsets32 = NULL; metaoffsets32 = (uint32_t *)malloc(num * 4); if (metaoffsets32) { uint64_t fileoffset = 0; int stsc_pos = 0; int stco_pos = 0; int repeat = 1; len += fread(metaoffsets32, 1, num * 4, mp4->mediafp); do { num--; metaoffsets32[num] = BYTESWAP32(metaoffsets32[num]); } while (num > 0); mp4->metaoffsets[0] = fileoffset = metaoffsets32[stco_pos]; num = 1; while (num < mp4->metasize_count) { if (stsc_pos + 1 < (int)mp4->metastsc_count && num == stsc_pos) { stco_pos++; stsc_pos++; fileoffset = (uint64_t)metaoffsets32[stco_pos]; repeat = 1; } else if (repeat == mp4->metastsc[stsc_pos].samples) { stco_pos++; fileoffset = (uint64_t)metaoffsets32[stco_pos]; repeat = 1; } else { fileoffset += (uint64_t)mp4->metasizes[num - 1]; repeat++; } mp4->metaoffsets[num] = fileoffset; num++; } if (mp4->metastsc) free(mp4->metastsc); mp4->metastsc = NULL; mp4->metastsc_count = 0; free(metaoffsets32); } } } else { mp4->indexcount = num; if (mp4->metaoffsets) free(mp4->metaoffsets); mp4->metaoffsets = (uint64_t *)malloc(num * 8); if (mp4->metaoffsets) { uint32_t *metaoffsets32 = NULL; metaoffsets32 = (uint32_t *)malloc(num * 4); if (metaoffsets32) { size_t readlen = fread(metaoffsets32, 1, num * 4, mp4->mediafp); len += readlen; do { num--; mp4->metaoffsets[num] = BYTESWAP32(metaoffsets32[num]); } while (num > 0); free(metaoffsets32); } } } } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco } else LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else if (qttag == MAKEID('c', 'o', '6', '4')) // metadata stco - offsets { if (type == traktype) // meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 8 <= qtsize - 8 - len) { if (mp4->metastsc_count > 0 && num != mp4->metasize_count) { mp4->indexcount = mp4->metasize_count; if (mp4->metaoffsets) free(mp4->metaoffsets); mp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8); if (mp4->metaoffsets) { uint64_t *metaoffsets64 = NULL; metaoffsets64 = (uint64_t *)malloc(num * 8); if (metaoffsets64) { uint64_t fileoffset = 0; int stsc_pos = 0; int stco_pos = 0; len += fread(metaoffsets64, 1, num * 8, mp4->mediafp); do { num--; metaoffsets64[num] = BYTESWAP64(metaoffsets64[num]); } while (num > 0); fileoffset = metaoffsets64[0]; mp4->metaoffsets[0] = fileoffset; num = 1; while (num < mp4->metasize_count) { if (num != mp4->metastsc[stsc_pos].chunk_num - 1 && 0 == (num - (mp4->metastsc[stsc_pos].chunk_num - 1)) % mp4->metastsc[stsc_pos].samples) { stco_pos++; fileoffset = (uint64_t)metaoffsets64[stco_pos]; } else { fileoffset += (uint64_t)mp4->metasizes[num - 1]; } mp4->metaoffsets[num] = fileoffset; num++; } if (mp4->metastsc) free(mp4->metastsc); mp4->metastsc = NULL; mp4->metastsc_count = 0; free(metaoffsets64); } } } else { mp4->indexcount = num; if (mp4->metaoffsets) free(mp4->metaoffsets); mp4->metaoffsets = (uint64_t *)malloc(num * 8); if (mp4->metaoffsets) { len += fread(mp4->metaoffsets, 1, num * 8, mp4->mediafp); do { num--; mp4->metaoffsets[num] = BYTESWAP64(mp4->metaoffsets[num]); } while (num > 0); } } } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco } else LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 't', 's')) // time to samples { if (type == traktype) // meta { uint32_t totaldur = 0, samples = 0; int32_t entries = 0; len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 8 <= qtsize - 8 - len) { entries = num; mp4->meta_clockdemon = mp4->trak_clockdemon; mp4->meta_clockcount = mp4->trak_clockcount; while (entries > 0) { int32_t samplecount; int32_t duration; len += fread(&samplecount, 1, 4, mp4->mediafp); samplecount = BYTESWAP32(samplecount); len += fread(&duration, 1, 4, mp4->mediafp); duration = BYTESWAP32(duration); samples += samplecount; entries--; totaldur += duration; mp4->metadatalength += (double)((double)samplecount * (double)duration / (double)mp4->meta_clockdemon); } mp4->basemetadataduration = mp4->metadatalength * (double)mp4->meta_clockdemon / (double)samples; } LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco } else LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); } else { NESTSIZE(8); } } else { break; } } while (len > 0); } else { free(mp4); mp4 = NULL; } return (size_t)mp4; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) //RAW or within MP4 { mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object)); if (mp4 == NULL) return 0; memset(mp4, 0, sizeof(mp4object)); struct stat64 mp4stat; stat64(filename, &mp4stat); mp4->filesize = mp4stat.st_size; if (mp4->filesize < 64) return 0; #ifdef _WINDOWS fopen_s(&mp4->mediafp, filename, "rb"); #else mp4->mediafp = fopen(filename, "rb"); #endif if (mp4->mediafp) { uint32_t qttag, qtsize32, skip, type = 0, subtype = 0, num; size_t len; int32_t nest = 0; uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; uint64_t lastsize = 0, qtsize; do { len = fread(&qtsize32, 1, 4, mp4->mediafp); len += fread(&qttag, 1, 4, mp4->mediafp); mp4->filepos += len; if (len == 8 && mp4->filepos < mp4->filesize) { if (!VALID_FOURCC(qttag)) { CloseSource((size_t)mp4); mp4 = NULL; break; } qtsize32 = BYTESWAP32(qtsize32); if (qtsize32 == 1) // 64-bit Atom { len = fread(&qtsize, 1, 8, mp4->mediafp); mp4->filepos += len; qtsize = BYTESWAP64(qtsize) - 8; } else qtsize = qtsize32; nest++; if (qtsize < 8) break; if (nest >= MAX_NEST_LEVEL) break; nestsize[nest] = qtsize; lastsize = qtsize; #if PRINT_MP4_STRUCTURE for (int i = 1; i < nest; i++) printf(" "); printf("%c%c%c%c (%lld)\n", (qttag & 0xff), ((qttag >> 8) & 0xff), ((qttag >> 16) & 0xff), ((qttag >> 24) & 0xff), qtsize); if (qttag == MAKEID('m', 'd', 'a', 't') || qttag == MAKEID('f', 't', 'y', 'p') || qttag == MAKEID('u', 'd', 't', 'a') || qttag == MAKEID('f', 'r', 'e', 'e')) { LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); continue; } #else if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms qttag != MAKEID('m', 'v', 'h', 'd') && qttag != MAKEID('t', 'r', 'a', 'k') && qttag != MAKEID('m', 'd', 'i', 'a') && qttag != MAKEID('m', 'd', 'h', 'd') && qttag != MAKEID('m', 'i', 'n', 'f') && qttag != MAKEID('g', 'm', 'i', 'n') && qttag != MAKEID('d', 'i', 'n', 'f') && qttag != MAKEID('a', 'l', 'i', 's') && qttag != MAKEID('s', 't', 's', 'd') && qttag != MAKEID('s', 't', 'b', 'l') && qttag != MAKEID('s', 't', 't', 's') && qttag != MAKEID('s', 't', 's', 'c') && qttag != MAKEID('s', 't', 's', 'z') && qttag != MAKEID('s', 't', 'c', 'o') && qttag != MAKEID('c', 'o', '6', '4') && qttag != MAKEID('h', 'd', 'l', 'r')) { LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else #endif if (qttag == MAKEID('m', 'v', 'h', 'd')) //mvhd movie header { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&mp4->clockdemon, 1, 4, mp4->mediafp); mp4->clockdemon = BYTESWAP32(mp4->clockdemon); len += fread(&mp4->clockcount, 1, 4, mp4->mediafp); mp4->clockcount = BYTESWAP32(mp4->clockcount); mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over mvhd NESTSIZE(qtsize); } else if (qttag == MAKEID('m', 'd', 'h', 'd')) //mdhd media header { media_header md; len = fread(&md, 1, sizeof(md), mp4->mediafp); if (len == sizeof(md)) { md.creation_time = BYTESWAP32(md.creation_time); md.modification_time = BYTESWAP32(md.modification_time); md.time_scale = BYTESWAP32(md.time_scale); md.duration = BYTESWAP32(md.duration); mp4->trak_clockdemon = md.time_scale; mp4->trak_clockcount = md.duration; if (mp4->videolength == 0.0) // Get the video length from the first track { mp4->videolength = (float)((double)mp4->trak_clockcount / (double)mp4->trak_clockdemon); } } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over mvhd NESTSIZE(qtsize); } else if (qttag == MAKEID('h', 'd', 'l', 'r')) //hldr { uint32_t temp; len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&temp, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak. if (temp != MAKEID('a', 'l', 'i', 's') && temp != MAKEID('u', 'r', 'l', ' ')) type = temp; mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over hldr NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 's', 'd')) //read the sample decription to determine the type of metadata { if (type == traktype) //like meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&skip, 1, 4, mp4->mediafp); len += fread(&subtype, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak. if (len == 16) { if (subtype != traksubtype) // MP4 metadata { type = 0; // MP4 } } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over stsd } else LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 's', 'c')) // metadata stsc - offset chunks { if (type == traktype) // meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 12 <= qtsize - 8 - len) { mp4->metastsc_count = num; if (mp4->metastsc) free(mp4->metastsc); if (num > 0) { mp4->metastsc = (SampleToChunk *)malloc(num * sizeof(SampleToChunk)); if (mp4->metastsc) { len += fread(mp4->metastsc, 1, num * sizeof(SampleToChunk), mp4->mediafp); do { num--; mp4->metastsc[num].chunk_num = BYTESWAP32(mp4->metastsc[num].chunk_num); mp4->metastsc[num].samples = BYTESWAP32(mp4->metastsc[num].samples); mp4->metastsc[num].id = BYTESWAP32(mp4->metastsc[num].id); } while (num > 0); } } else { //size of null CloseSource((size_t)mp4); mp4 = NULL; break; } } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over stsx } else LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 's', 'z')) // metadata stsz - sizes { if (type == traktype) // meta { uint32_t equalsamplesize; len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&equalsamplesize, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 4 <= qtsize - 8 - len) { mp4->metasize_count = num; if (mp4->metasizes) free(mp4->metasizes); if(num > 0) { mp4->metasizes = (uint32_t *)malloc(num * 4); if (mp4->metasizes) { if (equalsamplesize == 0) { len += fread(mp4->metasizes, 1, num * 4, mp4->mediafp); do { num--; mp4->metasizes[num] = BYTESWAP32(mp4->metasizes[num]); } while (num > 0); } else { equalsamplesize = BYTESWAP32(equalsamplesize); do { num--; mp4->metasizes[num] = equalsamplesize; } while (num > 0); } } } else { //size of null CloseSource((size_t)mp4); mp4 = NULL; break; } } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over stsz } else LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 'c', 'o')) // metadata stco - offsets { if (type == traktype) // meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 4 <= qtsize - 8 - len) { uint32_t metastco_count = num; if (mp4->metastsc_count > 0 && num != mp4->metasize_count) { mp4->indexcount = num; if (mp4->metaoffsets) free(mp4->metaoffsets); if(num > 0) { mp4->metaoffsets = (uint64_t *)malloc(num * 8); if (mp4->metaoffsets) { uint32_t *metaoffsets32 = NULL; metaoffsets32 = (uint32_t *)malloc(num * 4); if (metaoffsets32) { uint64_t fileoffset = 0; int stsc_pos = 0; int stco_pos = 0; int repeat = 1; len += fread(metaoffsets32, 1, num * 4, mp4->mediafp); do { num--; metaoffsets32[num] = BYTESWAP32(metaoffsets32[num]); } while (num > 0); mp4->metaoffsets[0] = fileoffset = metaoffsets32[stco_pos]; num = 1; while (num < mp4->indexcount) { if ((uint32_t)repeat == mp4->metastsc[stsc_pos].samples) { if ((uint32_t)stco_pos + 1 < metastco_count) { stco_pos++; fileoffset = (uint64_t)metaoffsets32[stco_pos]; } else { fileoffset += (uint64_t)mp4->metasizes[num - 1]; } if ((uint32_t)stsc_pos + 1 < mp4->metastsc_count) if (mp4->metastsc[stsc_pos + 1].chunk_num == (uint32_t)stco_pos + 1) stsc_pos++; repeat = 1; } else { fileoffset += (uint64_t)mp4->metasizes[num - 1]; repeat++; } mp4->metaoffsets[num] = fileoffset; //int delta = metaoffsets[num] - metaoffsets[num - 1]; //printf("%3d:%08x, delta = %08x\n", num, (int)fileoffset, delta); num++; } if (mp4->metastsc) free(mp4->metastsc); mp4->metastsc = NULL; mp4->metastsc_count = 0; free(metaoffsets32); } } } else { //size of null CloseSource((size_t)mp4); mp4 = NULL; break; } } else { mp4->indexcount = num; if (mp4->metaoffsets) free(mp4->metaoffsets); if (num > 0) { mp4->metaoffsets = (uint64_t *)malloc(num * 8); if (mp4->metaoffsets) { uint32_t *metaoffsets32 = NULL; metaoffsets32 = (uint32_t *)malloc(num * 4); if (metaoffsets32) { size_t readlen = fread(metaoffsets32, 1, num * 4, mp4->mediafp); len += readlen; do { num--; mp4->metaoffsets[num] = BYTESWAP32(metaoffsets32[num]); } while (num > 0); free(metaoffsets32); } } } else { //size of null CloseSource((size_t)mp4); mp4 = NULL; break; } } } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over stco } else LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else if (qttag == MAKEID('c', 'o', '6', '4')) // metadata stco - offsets { if (type == traktype) // meta { len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if(num == 0) { //size of null CloseSource((size_t)mp4); mp4 = NULL; break; } if (num * 8 <= qtsize - 8 - len) { if (mp4->metastsc_count > 0 && num != mp4->metasize_count) { mp4->indexcount = mp4->metasize_count; if (mp4->metaoffsets) free(mp4->metaoffsets); if (mp4->metasize_count) { mp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8); if (mp4->metaoffsets) { uint64_t *metaoffsets64 = NULL; metaoffsets64 = (uint64_t *)malloc(num * 8); if (metaoffsets64) { uint64_t fileoffset = 0; int stsc_pos = 0; int stco_pos = 0; len += fread(metaoffsets64, 1, num * 8, mp4->mediafp); do { num--; metaoffsets64[num] = BYTESWAP64(metaoffsets64[num]); } while (num > 0); fileoffset = metaoffsets64[0]; mp4->metaoffsets[0] = fileoffset; //printf("%3d:%08x, delta = %08x\n", 0, (int)fileoffset, 0); num = 1; while (num < mp4->metasize_count) { if (num != mp4->metastsc[stsc_pos].chunk_num - 1 && 0 == (num - (mp4->metastsc[stsc_pos].chunk_num - 1)) % mp4->metastsc[stsc_pos].samples) { stco_pos++; fileoffset = (uint64_t)metaoffsets64[stco_pos]; } else { fileoffset += (uint64_t)mp4->metasizes[num - 1]; } mp4->metaoffsets[num] = fileoffset; //int delta = metaoffsets[num] - metaoffsets[num - 1]; //printf("%3d:%08x, delta = %08x\n", num, (int)fileoffset, delta); num++; } if (mp4->metastsc) free(mp4->metastsc); mp4->metastsc = NULL; mp4->metastsc_count = 0; free(metaoffsets64); } } } else { //size of null CloseSource((size_t)mp4); mp4 = NULL; break; } } else { mp4->indexcount = num; if (mp4->metaoffsets) free(mp4->metaoffsets); mp4->metaoffsets = (uint64_t *)malloc(num * 8); if (mp4->metaoffsets) { len += fread(mp4->metaoffsets, 1, num * 8, mp4->mediafp); do { num--; mp4->metaoffsets[num] = BYTESWAP64(mp4->metaoffsets[num]); } while (num > 0); } } } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over stco } else LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else if (qttag == MAKEID('s', 't', 't', 's')) // time to samples { if (type == traktype) // meta { uint32_t totaldur = 0, samples = 0; int32_t entries = 0; len = fread(&skip, 1, 4, mp4->mediafp); len += fread(&num, 1, 4, mp4->mediafp); num = BYTESWAP32(num); if (num * 8 <= qtsize - 8 - len) { entries = num; mp4->meta_clockdemon = mp4->trak_clockdemon; mp4->meta_clockcount = mp4->trak_clockcount; while (entries > 0) { int32_t samplecount; int32_t duration; len += fread(&samplecount, 1, 4, mp4->mediafp); samplecount = BYTESWAP32(samplecount); len += fread(&duration, 1, 4, mp4->mediafp); duration = BYTESWAP32(duration); samples += samplecount; entries--; totaldur += duration; mp4->metadatalength += (double)((double)samplecount * (double)duration / (double)mp4->meta_clockdemon); } mp4->basemetadataduration = mp4->metadatalength * (double)mp4->meta_clockdemon / (double)samples; } mp4->filepos += len; LongSeek(mp4, qtsize - 8 - len); // skip over stco } else LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); } else { NESTSIZE(8); } } else { break; } } while (len > 0); if (mp4) { if (mp4->metasizes == NULL || mp4->metaoffsets == NULL) { CloseSource((size_t)mp4); mp4 = NULL; } } } else { free(mp4); mp4 = NULL; } return (size_t)mp4; }
169,550
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 read_entry( git_index_entry **out, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return 0; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return 0; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return 0; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return 0; } git__free(tmp_path); return entry_size; } Commit Message: index: convert `read_entry` to return entry size via an out-param The function `read_entry` does not conform to our usual coding style of returning stuff via the out parameter and to use the return value for reporting errors. Due to most of our code conforming to that pattern, it has become quite natural for us to actually return `-1` in case there is any error, which has also slipped in with commit 5625d86b9 (index: support index v4, 2016-05-17). As the function returns an `size_t` only, though, the return value is wrapped around, causing the caller of `read_tree` to continue with an invalid index entry. Ultimately, this can lead to a double-free. Improve code and fix the bug by converting the function to return the index entry size via an out parameter and only using the return value to indicate errors. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-415
static size_t read_entry( static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }
169,300
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 macvlan_common_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; dev->netdev_ops = &macvlan_netdev_ops; dev->destructor = free_netdev; dev->header_ops = &macvlan_hard_header_ops, dev->ethtool_ops = &macvlan_ethtool_ops; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
void macvlan_common_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING); dev->netdev_ops = &macvlan_netdev_ops; dev->destructor = free_netdev; dev->header_ops = &macvlan_hard_header_ops, dev->ethtool_ops = &macvlan_ethtool_ops; }
165,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: cib_connect(gboolean full) { int rc = pcmk_ok; static gboolean need_pass = TRUE; CRM_CHECK(cib != NULL, return -EINVAL); if (getenv("CIB_passwd") != NULL) { need_pass = FALSE; } if(watch_fencing && st == NULL) { st = stonith_api_new(); } if(watch_fencing && st->state == stonith_disconnected) { crm_trace("Connecting to stonith"); rc = st->cmds->connect(st, crm_system_name, NULL); if(rc == pcmk_ok) { crm_trace("Setting up stonith callbacks"); st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback); } } if (cib->state != cib_connected_query && cib->state != cib_connected_command) { crm_trace("Connecting to the CIB"); if (as_console && need_pass && cib->variant == cib_remote) { need_pass = FALSE; print_as("Password:"); } rc = cib->cmds->signon(cib, crm_system_name, cib_query); if (rc != pcmk_ok) { return rc; } current_cib = get_cib_copy(cib); mon_refresh_display(NULL); if (full) { if (rc == pcmk_ok) { rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy); if (rc == -EPROTONOSUPPORT) { print_as("Notification setup failed, won't be able to reconnect after failure"); if (as_console) { sleep(2); } rc = pcmk_ok; } } if (rc == pcmk_ok) { cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); } if (rc != pcmk_ok) { print_as("Notification setup failed, could not monitor CIB actions"); if (as_console) { sleep(2); } clean_up(-rc); } } } return rc; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_connect(gboolean full) { int rc = pcmk_ok; static gboolean need_pass = TRUE; CRM_CHECK(cib != NULL, return -EINVAL); if (getenv("CIB_passwd") != NULL) { need_pass = FALSE; } if(watch_fencing && st == NULL) { st = stonith_api_new(); } if(watch_fencing && st->state == stonith_disconnected) { crm_trace("Connecting to stonith"); rc = st->cmds->connect(st, crm_system_name, NULL); if(rc == pcmk_ok) { crm_trace("Setting up stonith callbacks"); st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback); } } if (cib->state != cib_connected_query && cib->state != cib_connected_command) { crm_trace("Connecting to the CIB"); if (as_console && need_pass && cib->variant == cib_remote) { need_pass = FALSE; print_as("Password:"); } rc = cib->cmds->signon(cib, crm_system_name, cib_query); if (rc != pcmk_ok) { return rc; } current_cib = get_cib_copy(cib); mon_refresh_display(NULL); if (full) { if (rc == pcmk_ok) { rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy); if (rc == -EPROTONOSUPPORT) { print_as("Notification setup not supported, won't be able to reconnect after failure"); if (as_console) { sleep(2); } rc = pcmk_ok; } } if (rc == pcmk_ok) { cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); } if (rc != pcmk_ok) { print_as("Notification setup failed, could not monitor CIB actions"); if (as_console) { sleep(2); } clean_up(-rc); } } } return rc; }
166,165
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: cib_tls_close(cib_t * cib) { cib_remote_opaque_t *private = cib->variant_opaque; shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */ shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */ close(private->command.socket); close(private->callback.socket); #ifdef HAVE_GNUTLS_GNUTLS_H if (private->command.encrypted) { gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->command.session)); gnutls_free(private->command.session); gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->callback.session)); gnutls_free(private->callback.session); gnutls_anon_free_client_credentials(anon_cred_c); gnutls_global_deinit(); } #endif return 0; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_tls_close(cib_t * cib) { cib_remote_opaque_t *private = cib->variant_opaque; #ifdef HAVE_GNUTLS_GNUTLS_H if (private->command.encrypted) { if (private->command.session) { gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->command.session)); gnutls_free(private->command.session); } if (private->callback.session) { gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->callback.session)); gnutls_free(private->callback.session); } private->command.session = NULL; private->callback.session = NULL; if (remote_gnutls_credentials_init) { gnutls_anon_free_client_credentials(anon_cred_c); gnutls_global_deinit(); remote_gnutls_credentials_init = FALSE; } } #endif if (private->command.socket) { shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */ close(private->command.socket); } if (private->callback.socket) { shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */ close(private->callback.socket); } private->command.socket = 0; private->callback.socket = 0; free(private->command.recv_buf); free(private->callback.recv_buf); private->command.recv_buf = NULL; private->callback.recv_buf = NULL; return 0; }
166,155
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 PageHandler::PrintToPDF(Maybe<bool> landscape, Maybe<bool> display_header_footer, Maybe<bool> print_background, Maybe<double> scale, Maybe<double> paper_width, Maybe<double> paper_height, Maybe<double> margin_top, Maybe<double> margin_bottom, Maybe<double> margin_left, Maybe<double> margin_right, Maybe<String> page_ranges, Maybe<bool> ignore_invalid_page_ranges, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
void PageHandler::PrintToPDF(Maybe<bool> landscape, Maybe<bool> display_header_footer, Maybe<bool> print_background, Maybe<double> scale, Maybe<double> paper_width, Maybe<double> paper_height, Maybe<double> margin_top, Maybe<double> margin_bottom, Maybe<double> margin_left, Maybe<double> margin_right, Maybe<String> page_ranges, Maybe<bool> ignore_invalid_page_ranges, Maybe<String> header_template, Maybe<String> footer_template, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return; }
172,900
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 LoadingStatsCollectorTest::TestRedirectStatusHistogram( const std::string& initial_url, const std::string& prediction_url, const std::string& navigation_url, RedirectStatus expected_status) { const std::string& script_url = "https://cdn.google.com/script.js"; PreconnectPrediction prediction = CreatePreconnectPrediction( GURL(prediction_url).host(), initial_url != prediction_url, {{GURL(script_url).GetOrigin(), 1, net::NetworkIsolationKey()}}); EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _)) .WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true))); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back( CreateResourceLoadInfoWithRedirects({initial_url, navigation_url})); resources.push_back( CreateResourceLoadInfo(script_url, content::ResourceType::kScript)); PageRequestSummary summary = CreatePageRequestSummary(navigation_url, initial_url, resources); stats_collector_->RecordPageRequestSummary(summary); histogram_tester_->ExpectUniqueSample( internal::kLoadingPredictorPreconnectLearningRedirectStatus, static_cast<int>(expected_status), 1); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void LoadingStatsCollectorTest::TestRedirectStatusHistogram( const std::string& initial_url, const std::string& prediction_url, const std::string& navigation_url, RedirectStatus expected_status) { const std::string& script_url = "https://cdn.google.com/script.js"; PreconnectPrediction prediction = CreatePreconnectPrediction( GURL(prediction_url).host(), initial_url != prediction_url, {{url::Origin::Create(GURL(script_url)), 1, net::NetworkIsolationKey()}}); EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _)) .WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true))); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back( CreateResourceLoadInfoWithRedirects({initial_url, navigation_url})); resources.push_back( CreateResourceLoadInfo(script_url, content::ResourceType::kScript)); PageRequestSummary summary = CreatePageRequestSummary(navigation_url, initial_url, resources); stats_collector_->RecordPageRequestSummary(summary); histogram_tester_->ExpectUniqueSample( internal::kLoadingPredictorPreconnectLearningRedirectStatus, static_cast<int>(expected_status), 1); }
172,373
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::FocusChanged() { vr_v_sync_provider_.reset(); ConnectVSyncProvider(); } 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::FocusChanged() { DVLOG(1) << __FUNCTION__; vr_v_sync_provider_.reset(); ConnectVSyncProvider(); }
171,993
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 flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; int64_t cur_offset = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { av_free(par->extradata); par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) { par->extradata_size = 0; return AVERROR(ENOMEM); } memcpy(par->extradata, side, side_size); par->extradata_size = side_size; flv_write_codec_header(s, par, pkt->dts); } } if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts; if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, par); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); put_timestamp(pb, ts); avio_wb24(pb, flv->reserved); if (par->codec_type == AVMEDIA_TYPE_DATA || par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_TEXT) { avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (par->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { if (par->extradata_size) avio_w8(pb, par->extradata[0]); else avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | (FFALIGN(par->height, 16) - par->height)); } else if (par->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: flv->videosize += (avio_tell(pb) - cur_offset); flv->lasttimestamp = flv->acurframeindex / flv->framerate; if (pkt->flags & AV_PKT_FLAG_KEY) { double ts = flv->acurframeindex / flv->framerate; int64_t pos = cur_offset; flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; flv->lastkeyframelocation = pos; flv_append_keyframe_info(s, flv, ts, pos); } flv->acurframeindex++; break; case AVMEDIA_TYPE_AUDIO: flv->audiosize += (avio_tell(pb) - cur_offset); break; default: av_log(s, AV_LOG_WARNING, "par->codec_type is type = [%d]\n", par->codec_type); break; } } av_free(data); return pb->error; } Commit Message: avformat/flvenc: Check audio packet size Fixes: Assertion failure Fixes: assert_flvenc.c:941_1.swf Found-by: #CHEN HONGXU# <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-617
static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; int64_t cur_offset = avio_tell(pb); if (par->codec_type == AVMEDIA_TYPE_AUDIO && !pkt->size) { av_log(s, AV_LOG_WARNING, "Empty audio Packet\n"); return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { av_free(par->extradata); par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) { par->extradata_size = 0; return AVERROR(ENOMEM); } memcpy(par->extradata, side, side_size); par->extradata_size = side_size; flv_write_codec_header(s, par, pkt->dts); } } if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts; if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, par); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); put_timestamp(pb, ts); avio_wb24(pb, flv->reserved); if (par->codec_type == AVMEDIA_TYPE_DATA || par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_TEXT) { avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (par->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { if (par->extradata_size) avio_w8(pb, par->extradata[0]); else avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | (FFALIGN(par->height, 16) - par->height)); } else if (par->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: flv->videosize += (avio_tell(pb) - cur_offset); flv->lasttimestamp = flv->acurframeindex / flv->framerate; if (pkt->flags & AV_PKT_FLAG_KEY) { double ts = flv->acurframeindex / flv->framerate; int64_t pos = cur_offset; flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; flv->lastkeyframelocation = pos; flv_append_keyframe_info(s, flv, ts, pos); } flv->acurframeindex++; break; case AVMEDIA_TYPE_AUDIO: flv->audiosize += (avio_tell(pb) - cur_offset); break; default: av_log(s, AV_LOG_WARNING, "par->codec_type is type = [%d]\n", par->codec_type); break; } } av_free(data); return pb->error; }
169,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, delete) { char *fname; size_t fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, delete) { char *fname; size_t fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; }
165,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { // The class is not designed to handle recursive messages. This is not // expected during regular flow. However, during rendering of content for // printing, lower level code may run nested message loop. E.g. PDF may has // script to show message box http://crbug.com/502562. In that moment browser // may receive updated printer capabilities and decide to restart print // preview generation. When this happened message handling function may // choose to ignore message or safely crash process. ++ipc_nesting_level_; bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() --ipc_nesting_level_; return handled; }
171,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: vtp_print (netdissect_options *ndo, const u_char *pptr, u_int length) { int type, len, tlv_len, tlv_value, mgmtd_len; const u_char *tptr; const struct vtp_vlan_ *vtp_vlan; if (length < VTP_HEADER_LEN) goto trunc; tptr = pptr; ND_TCHECK2(*tptr, VTP_HEADER_LEN); type = *(tptr+1); ND_PRINT((ndo, "VTPv%u, Message %s (0x%02x), length %u", *tptr, tok2str(vtp_message_type_values,"Unknown message type", type), type, length)); /* In non-verbose mode, just print version and message type */ if (ndo->ndo_vflag < 1) { return; } /* verbose mode print all fields */ ND_PRINT((ndo, "\n\tDomain name: ")); mgmtd_len = *(tptr + 3); if (mgmtd_len < 1 || mgmtd_len > 32) { ND_PRINT((ndo, " [invalid MgmtD Len %d]", mgmtd_len)); return; } fn_printzp(ndo, tptr + 4, mgmtd_len, NULL); ND_PRINT((ndo, ", %s: %u", tok2str(vtp_header_values, "Unknown", type), *(tptr+2))); tptr += VTP_HEADER_LEN; switch (type) { case VTP_SUMMARY_ADV: /* * SUMMARY ADVERTISEMENT * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Version | Code | Followers | MgmtD Len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Management Domain Name (zero-padded to 32 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Configuration revision number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Updater Identity IP address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Update Timestamp (12 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | MD5 digest (16 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ ND_TCHECK2(*tptr, 8); ND_PRINT((ndo, "\n\t Config Rev %x, Updater %s", EXTRACT_32BITS(tptr), ipaddr_string(ndo, tptr+4))); tptr += 8; ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN); ND_PRINT((ndo, ", Timestamp 0x%08x 0x%08x 0x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8))); tptr += VTP_UPDATE_TIMESTAMP_LEN; ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN); ND_PRINT((ndo, ", MD5 digest: %08x%08x%08x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), EXTRACT_32BITS(tptr + 12))); tptr += VTP_MD5_DIGEST_LEN; break; case VTP_SUBSET_ADV: /* * SUBSET ADVERTISEMENT * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Version | Code | Seq number | MgmtD Len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Management Domain Name (zero-padded to 32 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Configuration revision number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | VLAN info field 1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ................ | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | VLAN info field N | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ ND_TCHECK_32BITS(tptr); ND_PRINT((ndo, ", Config Rev %x", EXTRACT_32BITS(tptr))); /* * VLAN INFORMATION * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | V info len | Status | VLAN type | VLAN name len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ISL vlan id | MTU size | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 802.10 index (SAID) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | VLAN name | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ tptr += 4; while (tptr < (pptr+length)) { ND_TCHECK_8BITS(tptr); len = *tptr; if (len == 0) break; ND_TCHECK2(*tptr, len); vtp_vlan = (const struct vtp_vlan_*)tptr; ND_TCHECK(*vtp_vlan); ND_PRINT((ndo, "\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name ", tok2str(vtp_vlan_status,"Unknown",vtp_vlan->status), tok2str(vtp_vlan_type_values,"Unknown",vtp_vlan->type), EXTRACT_16BITS(&vtp_vlan->vlanid), EXTRACT_16BITS(&vtp_vlan->mtu), EXTRACT_32BITS(&vtp_vlan->index))); fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL); /* * Vlan names are aligned to 32-bit boundaries. */ len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4); tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4); /* TLV information follows */ while (len > 0) { /* * Cisco specs says 2 bytes for type + 2 bytes for length, take only 1 * See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm */ type = *tptr; tlv_len = *(tptr+1); ND_PRINT((ndo, "\n\t\t%s (0x%04x) TLV", tok2str(vtp_vlan_tlv_values, "Unknown", type), type)); /* * infinite loop check */ if (type == 0 || tlv_len == 0) { return; } ND_TCHECK2(*tptr, tlv_len * 2 +2); tlv_value = EXTRACT_16BITS(tptr+2); switch (type) { case VTP_VLAN_STE_HOP_COUNT: ND_PRINT((ndo, ", %u", tlv_value)); break; case VTP_VLAN_PRUNING: ND_PRINT((ndo, ", %s (%u)", tlv_value == 1 ? "Enabled" : "Disabled", tlv_value)); break; case VTP_VLAN_STP_TYPE: ND_PRINT((ndo, ", %s (%u)", tok2str(vtp_stp_type_values, "Unknown", tlv_value), tlv_value)); break; case VTP_VLAN_BRIDGE_TYPE: ND_PRINT((ndo, ", %s (%u)", tlv_value == 1 ? "SRB" : "SRT", tlv_value)); break; case VTP_VLAN_BACKUP_CRF_MODE: ND_PRINT((ndo, ", %s (%u)", tlv_value == 1 ? "Backup" : "Not backup", tlv_value)); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER: case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER: case VTP_VLAN_PARENT_VLAN: case VTP_VLAN_TRANS_BRIDGED_VLAN: case VTP_VLAN_ARP_HOP_COUNT: default: print_unknown_data(ndo, tptr, "\n\t\t ", 2 + tlv_len*2); break; } len -= 2 + tlv_len*2; tptr += 2 + tlv_len*2; } } break; case VTP_ADV_REQUEST: /* * ADVERTISEMENT REQUEST * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Version | Code | Reserved | MgmtD Len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Management Domain Name (zero-padded to 32 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Start value | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\tStart value: %u", EXTRACT_32BITS(tptr))); break; case VTP_JOIN_MESSAGE: /* FIXME - Could not find message format */ break; default: break; } return; trunc: ND_PRINT((ndo, "[|vtp]")); } Commit Message: CVE-2017-13033/VTP: Add more bound and length checks. This fixes a buffer over-read discovered by Bhargava Shastry. 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 another VTP test's .out file for this change. Don't treate a TLV type or length of 0 as invalid; a type of 0 should just be reported as illegal if that type isn't used, and the length is the length of the *value*, not the length of the entire TLV, so if it's zero there won't be an infinite loop. (It's still not *legal*, as the values of all the TLVs we handle are 1 16-bit word long; we added a check for that.) Update some comments while we're at it, to give a new URL for one Cisco page and a non-Cisco URL for another former Cisco page (Cisco's UniverCD pages don't seem to be available any more, and Cisco's robots.txt file didn't allow the Wayback Machine to archive it). CWE ID: CWE-125
vtp_print (netdissect_options *ndo, const u_char *pptr, u_int length) { int type, len, tlv_len, tlv_value, mgmtd_len; const u_char *tptr; const struct vtp_vlan_ *vtp_vlan; if (length < VTP_HEADER_LEN) goto trunc; tptr = pptr; ND_TCHECK2(*tptr, VTP_HEADER_LEN); type = *(tptr+1); ND_PRINT((ndo, "VTPv%u, Message %s (0x%02x), length %u", *tptr, tok2str(vtp_message_type_values,"Unknown message type", type), type, length)); /* In non-verbose mode, just print version and message type */ if (ndo->ndo_vflag < 1) { return; } /* verbose mode print all fields */ ND_PRINT((ndo, "\n\tDomain name: ")); mgmtd_len = *(tptr + 3); if (mgmtd_len < 1 || mgmtd_len > 32) { ND_PRINT((ndo, " [invalid MgmtD Len %d]", mgmtd_len)); return; } fn_printzp(ndo, tptr + 4, mgmtd_len, NULL); ND_PRINT((ndo, ", %s: %u", tok2str(vtp_header_values, "Unknown", type), *(tptr+2))); tptr += VTP_HEADER_LEN; switch (type) { case VTP_SUMMARY_ADV: /* * SUMMARY ADVERTISEMENT * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Version | Code | Followers | MgmtD Len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Management Domain Name (zero-padded to 32 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Configuration revision number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Updater Identity IP address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Update Timestamp (12 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | MD5 digest (16 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ ND_TCHECK2(*tptr, 8); ND_PRINT((ndo, "\n\t Config Rev %x, Updater %s", EXTRACT_32BITS(tptr), ipaddr_string(ndo, tptr+4))); tptr += 8; ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN); ND_PRINT((ndo, ", Timestamp 0x%08x 0x%08x 0x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8))); tptr += VTP_UPDATE_TIMESTAMP_LEN; ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN); ND_PRINT((ndo, ", MD5 digest: %08x%08x%08x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), EXTRACT_32BITS(tptr + 12))); tptr += VTP_MD5_DIGEST_LEN; break; case VTP_SUBSET_ADV: /* * SUBSET ADVERTISEMENT * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Version | Code | Seq number | MgmtD Len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Management Domain Name (zero-padded to 32 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Configuration revision number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | VLAN info field 1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ................ | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | VLAN info field N | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ ND_TCHECK_32BITS(tptr); ND_PRINT((ndo, ", Config Rev %x", EXTRACT_32BITS(tptr))); /* * VLAN INFORMATION * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | V info len | Status | VLAN type | VLAN name len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ISL vlan id | MTU size | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 802.10 index (SAID) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | VLAN name | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ tptr += 4; while (tptr < (pptr+length)) { ND_TCHECK_8BITS(tptr); len = *tptr; if (len == 0) break; ND_TCHECK2(*tptr, len); vtp_vlan = (const struct vtp_vlan_*)tptr; if (len < VTP_VLAN_INFO_FIXED_PART_LEN) goto trunc; ND_TCHECK(*vtp_vlan); ND_PRINT((ndo, "\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name ", tok2str(vtp_vlan_status,"Unknown",vtp_vlan->status), tok2str(vtp_vlan_type_values,"Unknown",vtp_vlan->type), EXTRACT_16BITS(&vtp_vlan->vlanid), EXTRACT_16BITS(&vtp_vlan->mtu), EXTRACT_32BITS(&vtp_vlan->index))); len -= VTP_VLAN_INFO_FIXED_PART_LEN; tptr += VTP_VLAN_INFO_FIXED_PART_LEN; if (len < 4*((vtp_vlan->name_len + 3)/4)) goto trunc; ND_TCHECK2(*tptr, vtp_vlan->name_len); fn_printzp(ndo, tptr, vtp_vlan->name_len, NULL); /* * Vlan names are aligned to 32-bit boundaries. */ len -= 4*((vtp_vlan->name_len + 3)/4); tptr += 4*((vtp_vlan->name_len + 3)/4); /* TLV information follows */ while (len > 0) { /* * Cisco specs say 2 bytes for type + 2 bytes for length; * see http://docstore.mik.ua/univercd/cc/td/doc/product/lan/trsrb/frames.htm * However, actual packets on the wire appear to use 1 * byte for the type and 1 byte for the length, so that's * what we do. */ if (len < 2) goto trunc; ND_TCHECK2(*tptr, 2); type = *tptr; tlv_len = *(tptr+1); ND_PRINT((ndo, "\n\t\t%s (0x%04x) TLV", tok2str(vtp_vlan_tlv_values, "Unknown", type), type)); if (len < tlv_len * 2 + 2) { ND_PRINT((ndo, " (TLV goes past the end of the packet)")); return; } ND_TCHECK2(*tptr, tlv_len * 2 +2); /* * We assume the value is a 2-byte integer; the length is * in units of 16-bit words. */ if (tlv_len != 1) { ND_PRINT((ndo, " (invalid TLV length %u != 1)", tlv_len)); return; } else { tlv_value = EXTRACT_16BITS(tptr+2); switch (type) { case VTP_VLAN_STE_HOP_COUNT: ND_PRINT((ndo, ", %u", tlv_value)); break; case VTP_VLAN_PRUNING: ND_PRINT((ndo, ", %s (%u)", tlv_value == 1 ? "Enabled" : "Disabled", tlv_value)); break; case VTP_VLAN_STP_TYPE: ND_PRINT((ndo, ", %s (%u)", tok2str(vtp_stp_type_values, "Unknown", tlv_value), tlv_value)); break; case VTP_VLAN_BRIDGE_TYPE: ND_PRINT((ndo, ", %s (%u)", tlv_value == 1 ? "SRB" : "SRT", tlv_value)); break; case VTP_VLAN_BACKUP_CRF_MODE: ND_PRINT((ndo, ", %s (%u)", tlv_value == 1 ? "Backup" : "Not backup", tlv_value)); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER: case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER: case VTP_VLAN_PARENT_VLAN: case VTP_VLAN_TRANS_BRIDGED_VLAN: case VTP_VLAN_ARP_HOP_COUNT: default: print_unknown_data(ndo, tptr, "\n\t\t ", 2 + tlv_len*2); break; } } len -= 2 + tlv_len*2; tptr += 2 + tlv_len*2; } } break; case VTP_ADV_REQUEST: /* * ADVERTISEMENT REQUEST * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Version | Code | Reserved | MgmtD Len | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Management Domain Name (zero-padded to 32 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Start value | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\tStart value: %u", EXTRACT_32BITS(tptr))); break; case VTP_JOIN_MESSAGE: /* FIXME - Could not find message format */ break; default: break; } return; trunc: ND_PRINT((ndo, "[|vtp]")); }
167,850
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 flush_end_io(struct request *flush_rq, int error) { struct request_queue *q = flush_rq->q; struct list_head *running; bool queued = false; struct request *rq, *n; unsigned long flags = 0; struct blk_flush_queue *fq = blk_get_flush_queue(q, flush_rq->mq_ctx); if (q->mq_ops) { spin_lock_irqsave(&fq->mq_flush_lock, flags); flush_rq->tag = -1; } running = &fq->flush_queue[fq->flush_running_idx]; BUG_ON(fq->flush_pending_idx == fq->flush_running_idx); /* account completion of the flush request */ fq->flush_running_idx ^= 1; if (!q->mq_ops) elv_completed_request(q, flush_rq); /* and push the waiting requests to the next stage */ list_for_each_entry_safe(rq, n, running, flush.list) { unsigned int seq = blk_flush_cur_seq(rq); BUG_ON(seq != REQ_FSEQ_PREFLUSH && seq != REQ_FSEQ_POSTFLUSH); queued |= blk_flush_complete_seq(rq, fq, seq, error); } /* * Kick the queue to avoid stall for two cases: * 1. Moving a request silently to empty queue_head may stall the * queue. * 2. When flush request is running in non-queueable queue, the * queue is hold. Restart the queue after flush request is finished * to avoid stall. * This function is called from request completion path and calling * directly into request_fn may confuse the driver. Always use * kblockd. */ if (queued || fq->flush_queue_delayed) { WARN_ON(q->mq_ops); blk_run_queue_async(q); } fq->flush_queue_delayed = 0; if (q->mq_ops) spin_unlock_irqrestore(&fq->mq_flush_lock, flags); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362
static void flush_end_io(struct request *flush_rq, int error) { struct request_queue *q = flush_rq->q; struct list_head *running; bool queued = false; struct request *rq, *n; unsigned long flags = 0; struct blk_flush_queue *fq = blk_get_flush_queue(q, flush_rq->mq_ctx); if (q->mq_ops) { struct blk_mq_hw_ctx *hctx; /* release the tag's ownership to the req cloned from */ spin_lock_irqsave(&fq->mq_flush_lock, flags); hctx = q->mq_ops->map_queue(q, flush_rq->mq_ctx->cpu); blk_mq_tag_set_rq(hctx, flush_rq->tag, fq->orig_rq); flush_rq->tag = -1; } running = &fq->flush_queue[fq->flush_running_idx]; BUG_ON(fq->flush_pending_idx == fq->flush_running_idx); /* account completion of the flush request */ fq->flush_running_idx ^= 1; if (!q->mq_ops) elv_completed_request(q, flush_rq); /* and push the waiting requests to the next stage */ list_for_each_entry_safe(rq, n, running, flush.list) { unsigned int seq = blk_flush_cur_seq(rq); BUG_ON(seq != REQ_FSEQ_PREFLUSH && seq != REQ_FSEQ_POSTFLUSH); queued |= blk_flush_complete_seq(rq, fq, seq, error); } /* * Kick the queue to avoid stall for two cases: * 1. Moving a request silently to empty queue_head may stall the * queue. * 2. When flush request is running in non-queueable queue, the * queue is hold. Restart the queue after flush request is finished * to avoid stall. * This function is called from request completion path and calling * directly into request_fn may confuse the driver. Always use * kblockd. */ if (queued || fq->flush_queue_delayed) { WARN_ON(q->mq_ops); blk_run_queue_async(q); } fq->flush_queue_delayed = 0; if (q->mq_ops) spin_unlock_irqrestore(&fq->mq_flush_lock, flags); }
169,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptPromise VRDisplay::exitPresent(ScriptState* script_state) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); if (!is_presenting_) { DOMException* exception = DOMException::Create( kInvalidStateError, "VRDisplay is not presenting."); resolver->Reject(exception); return promise; } if (!display_) { DOMException* exception = DOMException::Create(kInvalidStateError, "VRService is not available."); resolver->Reject(exception); return promise; } display_->ExitPresent(); resolver->Resolve(); StopPresenting(); return promise; } 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:
ScriptPromise VRDisplay::exitPresent(ScriptState* script_state) { DVLOG(1) << __FUNCTION__; ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); if (!is_presenting_) { DOMException* exception = DOMException::Create( kInvalidStateError, "VRDisplay is not presenting."); resolver->Reject(exception); return promise; } if (!display_) { DOMException* exception = DOMException::Create(kInvalidStateError, "VRService is not available."); resolver->Reject(exception); return promise; } display_->ExitPresent(); resolver->Resolve(); StopPresenting(); return promise; }
172,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: DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; DOMArrayBuffer* result = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); if (finished_loading_) { array_buffer_result_ = result; AdjustReportedMemoryUsageToV8( -1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); } return result; } Commit Message: FileReader: Make a copy of the ArrayBuffer when returning partial results. This is to avoid accidentally ending up with multiple references to the same underlying ArrayBuffer. The extra performance overhead of this is minimal as usage of partial results is very rare anyway (as can be seen on https://www.chromestatus.com/metrics/feature/timeline/popularity/2158). Bug: 936448 Change-Id: Icd1081adc1c889829fe7fa4af9cf4440097e8854 Reviewed-on: https://chromium-review.googlesource.com/c/1492873 Commit-Queue: Marijn Kruisselbrink <[email protected]> Reviewed-by: Adam Klein <[email protected]> Cr-Commit-Position: refs/heads/master@{#636251} CWE ID: CWE-416
DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; if (!finished_loading_) { return DOMArrayBuffer::Create( ArrayBuffer::Create(raw_data_->Data(), raw_data_->ByteLength())); } array_buffer_result_ = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); AdjustReportedMemoryUsageToV8(-1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); return array_buffer_result_; }
173,063
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::unique_ptr<JSONObject> EffectPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); json->SetString("localTransformSpace", String::Format("%p", state_.local_transform_space.get())); json->SetString("outputClip", String::Format("%p", state_.output_clip.get())); if (state_.color_filter != kColorFilterNone) json->SetInteger("colorFilter", state_.color_filter); if (!state_.filter.IsEmpty()) json->SetString("filter", state_.filter.ToString()); if (state_.opacity != 1.0f) json->SetDouble("opacity", state_.opacity); if (state_.blend_mode != SkBlendMode::kSrcOver) json->SetString("blendMode", SkBlendMode_Name(state_.blend_mode)); if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } if (state_.compositor_element_id) { json->SetString("compositorElementId", state_.compositor_element_id.ToString().c_str()); } if (state_.paint_offset != FloatPoint()) json->SetString("paintOffset", state_.paint_offset.ToString()); return json; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
std::unique_ptr<JSONObject> EffectPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); json->SetString("localTransformSpace", String::Format("%p", state_.local_transform_space)); json->SetString("outputClip", String::Format("%p", state_.output_clip)); if (state_.color_filter != kColorFilterNone) json->SetInteger("colorFilter", state_.color_filter); if (!state_.filter.IsEmpty()) json->SetString("filter", state_.filter.ToString()); if (state_.opacity != 1.0f) json->SetDouble("opacity", state_.opacity); if (state_.blend_mode != SkBlendMode::kSrcOver) json->SetString("blendMode", SkBlendMode_Name(state_.blend_mode)); if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } if (state_.compositor_element_id) { json->SetString("compositorElementId", state_.compositor_element_id.ToString().c_str()); } if (state_.paint_offset != FloatPoint()) json->SetString("paintOffset", state_.paint_offset.ToString()); return json; }
171,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: static int send_reply_chunks(struct svcxprt_rdma *xprt, struct rpcrdma_write_array *rp_ary, struct rpcrdma_msg *rdma_resp, struct svc_rqst *rqstp, struct svc_rdma_req_map *vec) { u32 xfer_len = rqstp->rq_res.len; int write_len; u32 xdr_off; int chunk_no; int chunk_off; int nchunks; struct rpcrdma_segment *ch; struct rpcrdma_write_array *res_ary; int ret; /* XXX: need to fix when reply lists occur with read-list and or * write-list */ res_ary = (struct rpcrdma_write_array *) &rdma_resp->rm_body.rm_chunks[2]; /* xdr offset starts at RPC message */ nchunks = be32_to_cpu(rp_ary->wc_nchunks); for (xdr_off = 0, chunk_no = 0; xfer_len && chunk_no < nchunks; chunk_no++) { u64 rs_offset; ch = &rp_ary->wc_array[chunk_no].wc_target; write_len = min(xfer_len, be32_to_cpu(ch->rs_length)); /* Prepare the reply chunk given the length actually * written */ xdr_decode_hyper((__be32 *)&ch->rs_offset, &rs_offset); svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no, ch->rs_handle, ch->rs_offset, write_len); chunk_off = 0; while (write_len) { ret = send_write(xprt, rqstp, be32_to_cpu(ch->rs_handle), rs_offset + chunk_off, xdr_off, write_len, vec); if (ret <= 0) goto out_err; chunk_off += ret; xdr_off += ret; xfer_len -= ret; write_len -= ret; } } /* Update the req with the number of chunks actually used */ svc_rdma_xdr_encode_reply_array(res_ary, chunk_no); return rqstp->rq_res.len; out_err: pr_err("svcrdma: failed to send reply chunks, rc=%d\n", ret); return -EIO; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static int send_reply_chunks(struct svcxprt_rdma *xprt, /* The svc_rqst and all resources it owns are released as soon as * svc_rdma_sendto returns. Transfer pages under I/O to the ctxt * so they are released by the Send completion handler. */ static void svc_rdma_save_io_pages(struct svc_rqst *rqstp, struct svc_rdma_op_ctxt *ctxt) { int i, pages = rqstp->rq_next_page - rqstp->rq_respages; ctxt->count += pages; for (i = 0; i < pages; i++) { ctxt->pages[i + 1] = rqstp->rq_respages[i]; rqstp->rq_respages[i] = NULL; } rqstp->rq_next_page = rqstp->rq_respages + 1; } /** * svc_rdma_post_send_wr - Set up and post one Send Work Request * @rdma: controlling transport * @ctxt: op_ctxt for transmitting the Send WR * @num_sge: number of SGEs to send * @inv_rkey: R_key argument to Send With Invalidate, or zero * * Returns: * %0 if the Send* was posted successfully, * %-ENOTCONN if the connection was lost or dropped, * %-EINVAL if there was a problem with the Send we built, * %-ENOMEM if ib_post_send failed. */ int svc_rdma_post_send_wr(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, int num_sge, u32 inv_rkey) { struct ib_send_wr *send_wr = &ctxt->send_wr; dprintk("svcrdma: posting Send WR with %u sge(s)\n", num_sge); send_wr->next = NULL; ctxt->cqe.done = svc_rdma_wc_send; send_wr->wr_cqe = &ctxt->cqe; send_wr->sg_list = ctxt->sge; send_wr->num_sge = num_sge; send_wr->send_flags = IB_SEND_SIGNALED; if (inv_rkey) { send_wr->opcode = IB_WR_SEND_WITH_INV; send_wr->ex.invalidate_rkey = inv_rkey; } else { send_wr->opcode = IB_WR_SEND; } return svc_rdma_send(rdma, send_wr); }
168,168
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 socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284
int socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; }
167,165
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 GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kAccessTokenValue, &access_token_); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); std::string access_token; response_dict->GetString(kAccessTokenValue, &access_token); if (access_token.find("\r\n") != std::string::npos) { LOG(ERROR) << "Gaia response: access token include CRLF"; delegate_->OnOAuthError(); return; } access_token_ = access_token; response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } }
170,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void skcipher_release(void *private) { crypto_free_skcipher(private); } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: [email protected] Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> CWE ID: CWE-476
static void skcipher_release(void *private) { struct skcipher_tfm *tfm = private; crypto_free_skcipher(tfm->skcipher); kfree(tfm); }
167,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mcryptd_create_hash(struct crypto_template *tmpl, struct rtattr **tb, struct mcryptd_queue *queue) { struct hashd_instance_ctx *ctx; struct ahash_instance *inst; struct hash_alg_common *halg; struct crypto_alg *alg; u32 type = 0; u32 mask = 0; int err; mcryptd_check_internal(tb, &type, &mask); halg = ahash_attr_alg(tb[1], type, mask); if (IS_ERR(halg)) return PTR_ERR(halg); alg = &halg->base; pr_debug("crypto: mcryptd hash alg: %s\n", alg->cra_name); inst = mcryptd_alloc_instance(alg, ahash_instance_headroom(), sizeof(*ctx)); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; ctx = ahash_instance_ctx(inst); ctx->queue = queue; err = crypto_init_ahash_spawn(&ctx->spawn, halg, ahash_crypto_instance(inst)); if (err) goto out_free_inst; type = CRYPTO_ALG_ASYNC; if (alg->cra_flags & CRYPTO_ALG_INTERNAL) type |= CRYPTO_ALG_INTERNAL; inst->alg.halg.base.cra_flags = type; inst->alg.halg.digestsize = halg->digestsize; inst->alg.halg.statesize = halg->statesize; inst->alg.halg.base.cra_ctxsize = sizeof(struct mcryptd_hash_ctx); inst->alg.halg.base.cra_init = mcryptd_hash_init_tfm; inst->alg.halg.base.cra_exit = mcryptd_hash_exit_tfm; inst->alg.init = mcryptd_hash_init_enqueue; inst->alg.update = mcryptd_hash_update_enqueue; inst->alg.final = mcryptd_hash_final_enqueue; inst->alg.finup = mcryptd_hash_finup_enqueue; inst->alg.export = mcryptd_hash_export; inst->alg.import = mcryptd_hash_import; inst->alg.setkey = mcryptd_hash_setkey; inst->alg.digest = mcryptd_hash_digest_enqueue; err = ahash_register_instance(tmpl, inst); if (err) { crypto_drop_ahash(&ctx->spawn); out_free_inst: kfree(inst); } out_put_alg: crypto_mod_put(alg); return err; } Commit Message: crypto: mcryptd - Check mcryptd algorithm compatibility Algorithms not compatible with mcryptd could be spawned by mcryptd with a direct crypto_alloc_tfm invocation using a "mcryptd(alg)" name construct. This causes mcryptd to crash the kernel if an arbitrary "alg" is incompatible and not intended to be used with mcryptd. It is an issue if AF_ALG tries to spawn mcryptd(alg) to expose it externally. But such algorithms must be used internally and not be exposed. We added a check to enforce that only internal algorithms are allowed with mcryptd at the time mcryptd is spawning an algorithm. Link: http://marc.info/?l=linux-crypto-vger&m=148063683310477&w=2 Cc: [email protected] Reported-by: Mikulas Patocka <[email protected]> Signed-off-by: Tim Chen <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476
static int mcryptd_create_hash(struct crypto_template *tmpl, struct rtattr **tb, struct mcryptd_queue *queue) { struct hashd_instance_ctx *ctx; struct ahash_instance *inst; struct hash_alg_common *halg; struct crypto_alg *alg; u32 type = 0; u32 mask = 0; int err; if (!mcryptd_check_internal(tb, &type, &mask)) return -EINVAL; halg = ahash_attr_alg(tb[1], type, mask); if (IS_ERR(halg)) return PTR_ERR(halg); alg = &halg->base; pr_debug("crypto: mcryptd hash alg: %s\n", alg->cra_name); inst = mcryptd_alloc_instance(alg, ahash_instance_headroom(), sizeof(*ctx)); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; ctx = ahash_instance_ctx(inst); ctx->queue = queue; err = crypto_init_ahash_spawn(&ctx->spawn, halg, ahash_crypto_instance(inst)); if (err) goto out_free_inst; type = CRYPTO_ALG_ASYNC; if (alg->cra_flags & CRYPTO_ALG_INTERNAL) type |= CRYPTO_ALG_INTERNAL; inst->alg.halg.base.cra_flags = type; inst->alg.halg.digestsize = halg->digestsize; inst->alg.halg.statesize = halg->statesize; inst->alg.halg.base.cra_ctxsize = sizeof(struct mcryptd_hash_ctx); inst->alg.halg.base.cra_init = mcryptd_hash_init_tfm; inst->alg.halg.base.cra_exit = mcryptd_hash_exit_tfm; inst->alg.init = mcryptd_hash_init_enqueue; inst->alg.update = mcryptd_hash_update_enqueue; inst->alg.final = mcryptd_hash_final_enqueue; inst->alg.finup = mcryptd_hash_finup_enqueue; inst->alg.export = mcryptd_hash_export; inst->alg.import = mcryptd_hash_import; inst->alg.setkey = mcryptd_hash_setkey; inst->alg.digest = mcryptd_hash_digest_enqueue; err = ahash_register_instance(tmpl, inst); if (err) { crypto_drop_ahash(&ctx->spawn); out_free_inst: kfree(inst); } out_put_alg: crypto_mod_put(alg); return err; }
168,521
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 cg_rmdir(const char *path) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *cgdir = NULL, *controller; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { ret = -EINVAL; goto out; } fprintf(stderr, "rmdir: verifying access to %s:%s (req path %s)\n", controller, cgdir, path); if (!fc_may_access(fc, controller, cgdir, NULL, O_WRONLY)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { ret = -EACCES; goto out; } if (!cgfs_remove(controller, cgroup)) { ret = -EINVAL; goto out; } ret = 0; out: free(cgdir); return ret; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static int cg_rmdir(const char *path) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *cgdir = NULL, *controller, *next = NULL; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { ret = -EINVAL; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, &next)) { if (!fpath || strcmp(next, fpath) == 0) ret = -EBUSY; else ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, cgdir, NULL, O_WRONLY)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { ret = -EACCES; goto out; } if (!cgfs_remove(controller, cgroup)) { ret = -EINVAL; goto out; } ret = 0; out: free(cgdir); free(next); return ret; }
166,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool parse_notify(struct pool *pool, json_t *val) { char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime, *header; size_t cb1_len, cb2_len, alloc_len; unsigned char *cb1, *cb2; bool clean, ret = false; int merkles, i; json_t *arr; arr = json_array_get(val, 4); if (!arr || !json_is_array(arr)) goto out; merkles = json_array_size(arr); job_id = json_array_string(val, 0); prev_hash = json_array_string(val, 1); coinbase1 = json_array_string(val, 2); coinbase2 = json_array_string(val, 3); bbversion = json_array_string(val, 5); nbit = json_array_string(val, 6); ntime = json_array_string(val, 7); clean = json_is_true(json_array_get(val, 8)); if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) { /* Annoying but we must not leak memory */ if (job_id) free(job_id); if (prev_hash) free(prev_hash); if (coinbase1) free(coinbase1); if (coinbase2) free(coinbase2); if (bbversion) free(bbversion); if (nbit) free(nbit); if (ntime) free(ntime); goto out; } cg_wlock(&pool->data_lock); free(pool->swork.job_id); free(pool->swork.prev_hash); free(pool->swork.bbversion); free(pool->swork.nbit); free(pool->swork.ntime); pool->swork.job_id = job_id; pool->swork.prev_hash = prev_hash; cb1_len = strlen(coinbase1) / 2; cb2_len = strlen(coinbase2) / 2; pool->swork.bbversion = bbversion; pool->swork.nbit = nbit; pool->swork.ntime = ntime; pool->swork.clean = clean; alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len; pool->nonce2_offset = cb1_len + pool->n1_len; for (i = 0; i < pool->swork.merkles; i++) free(pool->swork.merkle_bin[i]); if (merkles) { pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin, sizeof(char *) * merkles + 1); for (i = 0; i < merkles; i++) { char *merkle = json_array_string(arr, i); pool->swork.merkle_bin[i] = (unsigned char *)malloc(32); if (unlikely(!pool->swork.merkle_bin[i])) quit(1, "Failed to malloc pool swork merkle_bin"); hex2bin(pool->swork.merkle_bin[i], merkle, 32); free(merkle); } } pool->swork.merkles = merkles; if (clean) pool->nonce2 = 0; pool->merkle_offset = strlen(pool->swork.bbversion) + strlen(pool->swork.prev_hash); pool->swork.header_len = pool->merkle_offset + /* merkle_hash */ 32 + strlen(pool->swork.ntime) + strlen(pool->swork.nbit) + /* nonce */ 8 + /* workpadding */ 96; pool->merkle_offset /= 2; pool->swork.header_len = pool->swork.header_len * 2 + 1; align_len(&pool->swork.header_len); header = (char *)alloca(pool->swork.header_len); snprintf(header, pool->swork.header_len, "%s%s%s%s%s%s%s", pool->swork.bbversion, pool->swork.prev_hash, blank_merkel, pool->swork.ntime, pool->swork.nbit, "00000000", /* nonce */ workpadding); if (unlikely(!hex2bin(pool->header_bin, header, 128))) quit(1, "Failed to convert header to header_bin in parse_notify"); cb1 = (unsigned char *)calloc(cb1_len, 1); if (unlikely(!cb1)) quithere(1, "Failed to calloc cb1 in parse_notify"); hex2bin(cb1, coinbase1, cb1_len); cb2 = (unsigned char *)calloc(cb2_len, 1); if (unlikely(!cb2)) quithere(1, "Failed to calloc cb2 in parse_notify"); hex2bin(cb2, coinbase2, cb2_len); free(pool->coinbase); align_len(&alloc_len); pool->coinbase = (unsigned char *)calloc(alloc_len, 1); if (unlikely(!pool->coinbase)) quit(1, "Failed to calloc pool coinbase in parse_notify"); memcpy(pool->coinbase, cb1, cb1_len); memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len); memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len); cg_wunlock(&pool->data_lock); if (opt_protocol) { applog(LOG_DEBUG, "job_id: %s", job_id); applog(LOG_DEBUG, "prev_hash: %s", prev_hash); applog(LOG_DEBUG, "coinbase1: %s", coinbase1); applog(LOG_DEBUG, "coinbase2: %s", coinbase2); applog(LOG_DEBUG, "bbversion: %s", bbversion); applog(LOG_DEBUG, "nbit: %s", nbit); applog(LOG_DEBUG, "ntime: %s", ntime); applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no"); } free(coinbase1); free(coinbase2); free(cb1); free(cb2); /* A notify message is the closest stratum gets to a getwork */ pool->getwork_requested++; total_getworks++; ret = true; if (pool == current_pool()) opt_work_update = true; out: return ret; } Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime. Might have introduced a memory leak, don't have time to check. :( Should the other hex2bin()'s be checked? Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this. CWE ID: CWE-20
static bool parse_notify(struct pool *pool, json_t *val) { char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime, *header; size_t cb1_len, cb2_len, alloc_len; unsigned char *cb1, *cb2; bool clean, ret = false; int merkles, i; json_t *arr; arr = json_array_get(val, 4); if (!arr || !json_is_array(arr)) goto out; merkles = json_array_size(arr); job_id = json_array_string(val, 0); prev_hash = json_array_string(val, 1); coinbase1 = json_array_string(val, 2); coinbase2 = json_array_string(val, 3); bbversion = json_array_string(val, 5); nbit = json_array_string(val, 6); ntime = json_array_string(val, 7); clean = json_is_true(json_array_get(val, 8)); if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) { /* Annoying but we must not leak memory */ if (job_id) free(job_id); if (prev_hash) free(prev_hash); if (coinbase1) free(coinbase1); if (coinbase2) free(coinbase2); if (bbversion) free(bbversion); if (nbit) free(nbit); if (ntime) free(ntime); goto out; } cg_wlock(&pool->data_lock); free(pool->swork.job_id); free(pool->swork.prev_hash); free(pool->swork.bbversion); free(pool->swork.nbit); free(pool->swork.ntime); pool->swork.job_id = job_id; pool->swork.prev_hash = prev_hash; cb1_len = strlen(coinbase1) / 2; cb2_len = strlen(coinbase2) / 2; pool->swork.bbversion = bbversion; pool->swork.nbit = nbit; pool->swork.ntime = ntime; pool->swork.clean = clean; alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len; pool->nonce2_offset = cb1_len + pool->n1_len; for (i = 0; i < pool->swork.merkles; i++) free(pool->swork.merkle_bin[i]); if (merkles) { pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin, sizeof(char *) * merkles + 1); for (i = 0; i < merkles; i++) { char *merkle = json_array_string(arr, i); pool->swork.merkle_bin[i] = (unsigned char *)malloc(32); if (unlikely(!pool->swork.merkle_bin[i])) quit(1, "Failed to malloc pool swork merkle_bin"); hex2bin(pool->swork.merkle_bin[i], merkle, 32); free(merkle); } } pool->swork.merkles = merkles; if (clean) pool->nonce2 = 0; pool->merkle_offset = strlen(pool->swork.bbversion) + strlen(pool->swork.prev_hash); pool->swork.header_len = pool->merkle_offset + /* merkle_hash */ 32 + strlen(pool->swork.ntime) + strlen(pool->swork.nbit) + /* nonce */ 8 + /* workpadding */ 96; pool->merkle_offset /= 2; pool->swork.header_len = pool->swork.header_len * 2 + 1; align_len(&pool->swork.header_len); header = (char *)alloca(pool->swork.header_len); snprintf(header, pool->swork.header_len, "%s%s%s%s%s%s%s", pool->swork.bbversion, pool->swork.prev_hash, blank_merkel, pool->swork.ntime, pool->swork.nbit, "00000000", /* nonce */ workpadding); if (unlikely(!hex2bin(pool->header_bin, header, 128))) { applog(LOG_WARNING, "%s: Failed to convert header to header_bin, got %s", __func__, header); pool_failed(pool); // TODO: memory leaks? goto out, clean up there? return false; } cb1 = (unsigned char *)calloc(cb1_len, 1); if (unlikely(!cb1)) quithere(1, "Failed to calloc cb1 in parse_notify"); hex2bin(cb1, coinbase1, cb1_len); cb2 = (unsigned char *)calloc(cb2_len, 1); if (unlikely(!cb2)) quithere(1, "Failed to calloc cb2 in parse_notify"); hex2bin(cb2, coinbase2, cb2_len); free(pool->coinbase); align_len(&alloc_len); pool->coinbase = (unsigned char *)calloc(alloc_len, 1); if (unlikely(!pool->coinbase)) quit(1, "Failed to calloc pool coinbase in parse_notify"); memcpy(pool->coinbase, cb1, cb1_len); memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len); // NOTE: gap for nonce2, filled at work generation time memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len); cg_wunlock(&pool->data_lock); if (opt_protocol) { applog(LOG_DEBUG, "job_id: %s", job_id); applog(LOG_DEBUG, "prev_hash: %s", prev_hash); applog(LOG_DEBUG, "coinbase1: %s", coinbase1); applog(LOG_DEBUG, "coinbase2: %s", coinbase2); applog(LOG_DEBUG, "bbversion: %s", bbversion); applog(LOG_DEBUG, "nbit: %s", nbit); applog(LOG_DEBUG, "ntime: %s", ntime); applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no"); } free(coinbase1); free(coinbase2); free(cb1); free(cb2); /* A notify message is the closest stratum gets to a getwork */ pool->getwork_requested++; total_getworks++; ret = true; if (pool == current_pool()) opt_work_update = true; out: return ret; }
166,303
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 do_remount_sb(struct super_block *sb, int flags, void *data, int force) { int retval; int remount_ro; if (sb->s_writers.frozen != SB_UNFROZEN) return -EBUSY; #ifdef CONFIG_BLOCK if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev)) return -EACCES; #endif if (flags & MS_RDONLY) acct_auto_close(sb); shrink_dcache_sb(sb); sync_filesystem(sb); remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY); /* If we are remounting RDONLY and current sb is read/write, make sure there are no rw files opened */ if (remount_ro) { if (force) { mark_files_ro(sb); } else { retval = sb_prepare_remount_readonly(sb); if (retval) return retval; } } if (sb->s_op->remount_fs) { retval = sb->s_op->remount_fs(sb, &flags, data); if (retval) { if (!force) goto cancel_readonly; /* If forced remount, go ahead despite any errors */ WARN(1, "forced remount of a %s fs returned %i\n", sb->s_type->name, retval); } } sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK); /* Needs to be ordered wrt mnt_is_readonly() */ smp_wmb(); sb->s_readonly_remount = 0; /* * Some filesystems modify their metadata via some other path than the * bdev buffer cache (eg. use a private mapping, or directories in * pagecache, etc). Also file data modifications go via their own * mappings. So If we try to mount readonly then copy the filesystem * from bdev, we could get stale data, so invalidate it to give a best * effort at coherency. */ if (remount_ro && sb->s_bdev) invalidate_bdev(sb->s_bdev); return 0; cancel_readonly: sb->s_readonly_remount = 0; return retval; } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
int do_remount_sb(struct super_block *sb, int flags, void *data, int force) { int retval; int remount_ro; if (sb->s_writers.frozen != SB_UNFROZEN) return -EBUSY; #ifdef CONFIG_BLOCK if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev)) return -EACCES; #endif if (flags & MS_RDONLY) acct_auto_close(sb); shrink_dcache_sb(sb); sync_filesystem(sb); remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY); /* If we are remounting RDONLY and current sb is read/write, make sure there are no rw files opened */ if (remount_ro) { if (force) { sb->s_readonly_remount = 1; smp_wmb(); } else { retval = sb_prepare_remount_readonly(sb); if (retval) return retval; } } if (sb->s_op->remount_fs) { retval = sb->s_op->remount_fs(sb, &flags, data); if (retval) { if (!force) goto cancel_readonly; /* If forced remount, go ahead despite any errors */ WARN(1, "forced remount of a %s fs returned %i\n", sb->s_type->name, retval); } } sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK); /* Needs to be ordered wrt mnt_is_readonly() */ smp_wmb(); sb->s_readonly_remount = 0; /* * Some filesystems modify their metadata via some other path than the * bdev buffer cache (eg. use a private mapping, or directories in * pagecache, etc). Also file data modifications go via their own * mappings. So If we try to mount readonly then copy the filesystem * from bdev, we could get stale data, so invalidate it to give a best * effort at coherency. */ if (remount_ro && sb->s_bdev) invalidate_bdev(sb->s_bdev); return 0; cancel_readonly: sb->s_readonly_remount = 0; return retval; }
166,808
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_int32_le(QEMUFile *f, void *pv, size_t size) { int32_t loaded; int32_t loaded; qemu_get_sbe32s(f, &loaded); if (loaded <= *cur) { *cur = loaded; return 0; } } Commit Message: CWE ID: CWE-119
static int get_int32_le(QEMUFile *f, void *pv, size_t size) { int32_t loaded; int32_t loaded; qemu_get_sbe32s(f, &loaded); if (loaded >= 0 && loaded <= *cur) { *cur = loaded; return 0; } }
165,359
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 store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ int remaining = s->icy_metaint - s->icy_data_read; if (remaining < 0) return AVERROR_INVALIDDATA; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119
static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ uint64_t remaining; if (s->icy_metaint < s->icy_data_read) return AVERROR_INVALIDDATA; remaining = s->icy_metaint - s->icy_data_read; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); }
168,505
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 big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_instantiated(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_positive(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); }
167,693
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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if (0 == u2_width || 0 == u2_height) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_FRM_HDR_DECODE_ERR; return e_error; } if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width); } } else { if (0 == ps_dec->i4_pic_count) { /* Decoder has not decoded a single frame since the last * reset/init. This implies that we have two headers in the * input stream. So, do not indicate a resolution change, since * this can take the decoder into an infinite loop. */ return (IMPEG2D_ERROR_CODES_T) IMPEG2D_FRM_HDR_DECODE_ERR; } else if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size; ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size; return e_error; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Adding check for min_width and min_height Add check for min_wd and min_ht. Stride is updated if header decode is done. Bug: 74078669 Change-Id: Ided95395e1138335dbb4b05131a8551f6f7bbfcd (cherry picked from commit 84eba4863dd50083951db83ea3cc81e015bf51da) CWE ID: CWE-787
IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if (0 == u2_width || 0 == u2_height) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_FRM_HDR_DECODE_ERR; return e_error; } if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; } else { if (0 == ps_dec->i4_pic_count) { /* Decoder has not decoded a single frame since the last * reset/init. This implies that we have two headers in the * input stream. So, do not indicate a resolution change, since * this can take the decoder into an infinite loop. */ return (IMPEG2D_ERROR_CODES_T) IMPEG2D_FRM_HDR_DECODE_ERR; } else if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else if((ps_dec->u2_horizontal_size < MIN_WIDTH) || (ps_dec->u2_vertical_size < MIN_HEIGHT)) { return IMPEG2D_UNSUPPORTED_DIMENSIONS; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size; ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size; return e_error; } if((ps_dec->u2_horizontal_size < MIN_WIDTH) || (ps_dec->u2_vertical_size < MIN_HEIGHT)) { return IMPEG2D_UNSUPPORTED_DIMENSIONS; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
174,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: 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_autoupdate = Cvar_Get( "cl_autoupdate", "0", CVAR_ARCHIVE ); cl_timeout = Cvar_Get( "cl_timeout", "200", 0 ); cl_wavefilerecord = Cvar_Get( "cl_wavefilerecord", "0", CVAR_TEMP ); cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP ); cl_shownuments = Cvar_Get( "cl_shownuments", "0", CVAR_TEMP ); cl_visibleClients = Cvar_Get( "cl_visibleClients", "0", CVAR_TEMP ); cl_showServerCommands = Cvar_Get( "cl_showServerCommands", "0", 0 ); 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_showPing = Cvar_Get( "cl_showPing", "0", 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", "1", CVAR_ARCHIVE ); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE); #endif Cvar_Get( "cg_autoswitch", "0", 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 ); cl_bypassMouseInput = Cvar_Get( "cl_bypassMouseInput", "0", 0 ); //CVAR_ROM ); // NERVE - SMF 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_guid = Cvar_Get( "cl_guid", "unknown", CVAR_USERINFO | CVAR_ROM ); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get( "cg_drawCompass", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_drawNotifyText", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_quickMessageAlt", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_popupLimboMenu", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_descriptiveText", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_drawTeamOverlay", "2", CVAR_ARCHIVE ); Cvar_Get( "cg_uselessNostalgia", "0", CVAR_ARCHIVE ); // JPW NERVE Cvar_Get( "cg_drawGun", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_cursorHints", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_voiceSpriteTime", "6000", CVAR_ARCHIVE ); Cvar_Get( "cg_teamChatsOnly", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_noVoiceChats", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_noVoiceText", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_crosshairSize", "48", CVAR_ARCHIVE ); Cvar_Get( "cg_drawCrosshair", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_zoomDefaultSniper", "20", CVAR_ARCHIVE ); Cvar_Get( "cg_zoomstepsniper", "2", CVAR_ARCHIVE ); Cvar_Get( "mp_playerType", "0", 0 ); Cvar_Get( "mp_currentPlayerType", "0", 0 ); Cvar_Get( "mp_weapon", "0", 0 ); Cvar_Get( "mp_team", "0", 0 ); Cvar_Get( "mp_currentTeam", "0", 0 ); 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", "multi", 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_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); Cvar_Get( "cg_autoReload", "1", CVAR_ARCHIVE | CVAR_USERINFO ); 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 ); cl_updateavailable = Cvar_Get( "cl_updateavailable", "0", CVAR_ROM ); cl_updatefiles = Cvar_Get( "cl_updatefiles", "", CVAR_ROM ); Q_strncpyz( cls.autoupdateServerNames[0], AUTOUPDATE_SERVER1_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[1], AUTOUPDATE_SERVER2_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[2], AUTOUPDATE_SERVER3_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[3], AUTOUPDATE_SERVER4_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[4], AUTOUPDATE_SERVER5_NAME, MAX_QPATH ); 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( "ui_restart", CL_UI_Restart_f ); // NERVE - SMF 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( "SaveTranslations", CL_SaveTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "SaveNewTranslations", CL_SaveNewTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "LoadTranslations", CL_LoadTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "startSingleplayer", CL_startSingleplayer_f ); // NERVE - SMF Cmd_AddCommand( "setRecommended", CL_SetRecommended_f ); CL_InitRef(); SCR_Init(); Cvar_Set( "cl_running", "1" ); autoupdateChecked = qfalse; autoupdateStarted = qfalse; CL_InitTranslation(); // NERVE - SMF - localization CL_GenerateQKey(); 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_autoupdate = Cvar_Get( "cl_autoupdate", "0", CVAR_ARCHIVE ); cl_timeout = Cvar_Get( "cl_timeout", "200", 0 ); cl_wavefilerecord = Cvar_Get( "cl_wavefilerecord", "0", CVAR_TEMP ); cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP ); cl_shownuments = Cvar_Get( "cl_shownuments", "0", CVAR_TEMP ); cl_visibleClients = Cvar_Get( "cl_visibleClients", "0", CVAR_TEMP ); cl_showServerCommands = Cvar_Get( "cl_showServerCommands", "0", 0 ); 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_showPing = Cvar_Get( "cl_showPing", "0", 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", "1", CVAR_ARCHIVE ); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED); #endif Cvar_Get( "cg_autoswitch", "0", 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 ); cl_bypassMouseInput = Cvar_Get( "cl_bypassMouseInput", "0", 0 ); //CVAR_ROM ); // NERVE - SMF 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_guid = Cvar_Get( "cl_guid", "unknown", CVAR_USERINFO | CVAR_ROM ); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get( "cg_drawCompass", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_drawNotifyText", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_quickMessageAlt", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_popupLimboMenu", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_descriptiveText", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_drawTeamOverlay", "2", CVAR_ARCHIVE ); Cvar_Get( "cg_uselessNostalgia", "0", CVAR_ARCHIVE ); // JPW NERVE Cvar_Get( "cg_drawGun", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_cursorHints", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_voiceSpriteTime", "6000", CVAR_ARCHIVE ); Cvar_Get( "cg_teamChatsOnly", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_noVoiceChats", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_noVoiceText", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_crosshairSize", "48", CVAR_ARCHIVE ); Cvar_Get( "cg_drawCrosshair", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_zoomDefaultSniper", "20", CVAR_ARCHIVE ); Cvar_Get( "cg_zoomstepsniper", "2", CVAR_ARCHIVE ); Cvar_Get( "mp_playerType", "0", 0 ); Cvar_Get( "mp_currentPlayerType", "0", 0 ); Cvar_Get( "mp_weapon", "0", 0 ); Cvar_Get( "mp_team", "0", 0 ); Cvar_Get( "mp_currentTeam", "0", 0 ); 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", "multi", 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_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); Cvar_Get( "cg_autoReload", "1", CVAR_ARCHIVE | CVAR_USERINFO ); 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 ); cl_updateavailable = Cvar_Get( "cl_updateavailable", "0", CVAR_ROM ); cl_updatefiles = Cvar_Get( "cl_updatefiles", "", CVAR_ROM ); Q_strncpyz( cls.autoupdateServerNames[0], AUTOUPDATE_SERVER1_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[1], AUTOUPDATE_SERVER2_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[2], AUTOUPDATE_SERVER3_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[3], AUTOUPDATE_SERVER4_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[4], AUTOUPDATE_SERVER5_NAME, MAX_QPATH ); 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( "ui_restart", CL_UI_Restart_f ); // NERVE - SMF 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( "SaveTranslations", CL_SaveTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "SaveNewTranslations", CL_SaveNewTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "LoadTranslations", CL_LoadTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "startSingleplayer", CL_startSingleplayer_f ); // NERVE - SMF Cmd_AddCommand( "setRecommended", CL_SetRecommended_f ); CL_InitRef(); SCR_Init(); Cvar_Set( "cl_running", "1" ); autoupdateChecked = qfalse; autoupdateStarted = qfalse; CL_InitTranslation(); // NERVE - SMF - localization CL_GenerateQKey(); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); }
170,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: Chapters::Display::~Display() { } 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
Chapters::Display::~Display()
174,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMXNodeInstance::OMXNodeInstance( OMX *owner, const sp<IOMXObserver> &observer, const char *name) : mOwner(owner), mNodeID(0), mHandle(NULL), mObserver(observer), mDying(false), mBufferIDCount(0) { mName = ADebug::GetDebugName(name); DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug"); ALOGV("debug level for %s is %d", name, DEBUG); DEBUG_BUMP = DEBUG; mNumPortBuffers[0] = 0; mNumPortBuffers[1] = 0; mDebugLevelBumpPendingBuffers[0] = 0; mDebugLevelBumpPendingBuffers[1] = 0; mMetadataType[0] = kMetadataBufferTypeInvalid; mMetadataType[1] = kMetadataBufferTypeInvalid; mSecureBufferType[0] = kSecureBufferTypeUnknown; mSecureBufferType[1] = kSecureBufferTypeUnknown; mIsSecure = AString(name).endsWith(".secure"); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
OMXNodeInstance::OMXNodeInstance( OMX *owner, const sp<IOMXObserver> &observer, const char *name) : mOwner(owner), mNodeID(0), mHandle(NULL), mObserver(observer), mDying(false), mSailed(false), mQueriedProhibitedExtensions(false), mBufferIDCount(0) { mName = ADebug::GetDebugName(name); DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug"); ALOGV("debug level for %s is %d", name, DEBUG); DEBUG_BUMP = DEBUG; mNumPortBuffers[0] = 0; mNumPortBuffers[1] = 0; mDebugLevelBumpPendingBuffers[0] = 0; mDebugLevelBumpPendingBuffers[1] = 0; mMetadataType[0] = kMetadataBufferTypeInvalid; mMetadataType[1] = kMetadataBufferTypeInvalid; mSecureBufferType[0] = kSecureBufferTypeUnknown; mSecureBufferType[1] = kSecureBufferTypeUnknown; mIsSecure = AString(name).endsWith(".secure"); }
174,129
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void hugetlb_put_quota(struct address_space *mapping, long delta) { struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(mapping->host->i_sb); if (sbinfo->free_blocks > -1) { spin_lock(&sbinfo->stat_lock); sbinfo->free_blocks += delta; spin_unlock(&sbinfo->stat_lock); } } Commit Message: hugepages: fix use after free bug in "quota" handling hugetlbfs_{get,put}_quota() are badly named. They don't interact with the general quota handling code, and they don't much resemble its behaviour. Rather than being about maintaining limits on on-disk block usage by particular users, they are instead about maintaining limits on in-memory page usage (including anonymous MAP_PRIVATE copied-on-write pages) associated with a particular hugetlbfs filesystem instance. Worse, they work by having callbacks to the hugetlbfs filesystem code from the low-level page handling code, in particular from free_huge_page(). This is a layering violation of itself, but more importantly, if the kernel does a get_user_pages() on hugepages (which can happen from KVM amongst others), then the free_huge_page() can be delayed until after the associated inode has already been freed. If an unmount occurs at the wrong time, even the hugetlbfs superblock where the "quota" limits are stored may have been freed. Andrew Barry proposed a patch to fix this by having hugepages, instead of storing a pointer to their address_space and reaching the superblock from there, had the hugepages store pointers directly to the superblock, bumping the reference count as appropriate to avoid it being freed. Andrew Morton rejected that version, however, on the grounds that it made the existing layering violation worse. This is a reworked version of Andrew's patch, which removes the extra, and some of the existing, layering violation. It works by introducing the concept of a hugepage "subpool" at the lower hugepage mm layer - that is a finite logical pool of hugepages to allocate from. hugetlbfs now creates a subpool for each filesystem instance with a page limit set, and a pointer to the subpool gets added to each allocated hugepage, instead of the address_space pointer used now. The subpool has its own lifetime and is only freed once all pages in it _and_ all other references to it (i.e. superblocks) are gone. subpools are optional - a NULL subpool pointer is taken by the code to mean that no subpool limits are in effect. Previous discussion of this bug found in: "Fix refcounting in hugetlbfs quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or http://marc.info/?l=linux-mm&m=126928970510627&w=1 v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to alloc_huge_page() - since it already takes the vma, it is not necessary. Signed-off-by: Andrew Barry <[email protected]> Signed-off-by: David Gibson <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Minchan Kim <[email protected]> Cc: Hillf Danton <[email protected]> Cc: Paul Mackerras <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
void hugetlb_put_quota(struct address_space *mapping, long delta)
165,604
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: error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) { TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram"); SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime"); api()->glLinkProgramFn(GetProgramServiceID(program, resources_)); ExitCommandProcessingEarly(); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) { TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram"); SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime"); GLuint program_service_id = GetProgramServiceID(program, resources_); api()->glLinkProgramFn(program_service_id); ExitCommandProcessingEarly(); linking_program_service_id_ = program_service_id; return error::kNoError; }
172,534
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: MagickExport int LocaleUppercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l(c,c_locale)); #endif return(toupper(c)); } Commit Message: ... CWE ID: CWE-125
MagickExport int LocaleUppercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l((int) ((unsigned char) c),c_locale)); #endif return(toupper((int) ((unsigned char) c))); }
170,234
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionAddEventListener(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() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->addEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)), exec->argument(2).toBoolean(exec)); 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
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionAddEventListener(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() < 2) return throwVMError(exec, createNotEnoughArgumentsError(exec)); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->addEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); }
170,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 fr_add_pvc(struct net_device *frad, unsigned int dlci, int type) { hdlc_device *hdlc = dev_to_hdlc(frad); pvc_device *pvc; struct net_device *dev; int used; if ((pvc = add_pvc(frad, dlci)) == NULL) { netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n"); return -ENOBUFS; } if (*get_dev_p(pvc, type)) return -EEXIST; used = pvc_is_used(pvc); if (type == ARPHRD_ETHER) dev = alloc_netdev(0, "pvceth%d", ether_setup); else dev = alloc_netdev(0, "pvc%d", pvc_setup); if (!dev) { netdev_warn(frad, "Memory squeeze on fr_pvc()\n"); delete_unused_pvcs(hdlc); return -ENOBUFS; } if (type == ARPHRD_ETHER) random_ether_addr(dev->dev_addr); else { *(__be16*)dev->dev_addr = htons(dlci); dlci_to_q922(dev->broadcast, dlci); } dev->netdev_ops = &pvc_ops; dev->mtu = HDLC_MAX_MTU; dev->tx_queue_len = 0; dev->ml_priv = pvc; if (register_netdevice(dev) != 0) { free_netdev(dev); delete_unused_pvcs(hdlc); return -EIO; } dev->destructor = free_netdev; *get_dev_p(pvc, type) = dev; if (!used) { state(hdlc)->dce_changed = 1; state(hdlc)->dce_pvc_count++; } return 0; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type) { hdlc_device *hdlc = dev_to_hdlc(frad); pvc_device *pvc; struct net_device *dev; int used; if ((pvc = add_pvc(frad, dlci)) == NULL) { netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n"); return -ENOBUFS; } if (*get_dev_p(pvc, type)) return -EEXIST; used = pvc_is_used(pvc); if (type == ARPHRD_ETHER) { dev = alloc_netdev(0, "pvceth%d", ether_setup); dev->priv_flags &= ~IFF_TX_SKB_SHARING; } else dev = alloc_netdev(0, "pvc%d", pvc_setup); if (!dev) { netdev_warn(frad, "Memory squeeze on fr_pvc()\n"); delete_unused_pvcs(hdlc); return -ENOBUFS; } if (type == ARPHRD_ETHER) random_ether_addr(dev->dev_addr); else { *(__be16*)dev->dev_addr = htons(dlci); dlci_to_q922(dev->broadcast, dlci); } dev->netdev_ops = &pvc_ops; dev->mtu = HDLC_MAX_MTU; dev->tx_queue_len = 0; dev->ml_priv = pvc; if (register_netdevice(dev) != 0) { free_netdev(dev); delete_unused_pvcs(hdlc); return -EIO; } dev->destructor = free_netdev; *get_dev_p(pvc, type) = dev; if (!used) { state(hdlc)->dce_changed = 1; state(hdlc)->dce_pvc_count++; } return 0; }
165,732
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_object(JsonLexContext *lex, JsonSemAction *sem) { /* * an object is a possibly empty sequence of object fields, separated by * commas and surrounded by curly braces. */ json_struct_action ostart = sem->object_start; json_struct_action oend = sem->object_end; JsonTokenType tok; if (ostart != NULL) (*ostart) (sem->semstate); * itself. Note that we increment this after we call the semantic routine * for the object start and restore it before we call the routine for the * object end. */ lex->lex_level++; /* we know this will succeeed, just clearing the token */ lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START); tok = lex_peek(lex); switch (tok) { case JSON_TOKEN_STRING: parse_object_field(lex, sem); while (lex_accept(lex, JSON_TOKEN_COMMA, NULL)) parse_object_field(lex, sem); break; case JSON_TOKEN_OBJECT_END: break; default: /* case of an invalid initial token inside the object */ report_parse_error(JSON_PARSE_OBJECT_START, lex); } lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END); lex->lex_level--; if (oend != NULL) (*oend) (sem->semstate); } Commit Message: CWE ID: CWE-119
parse_object(JsonLexContext *lex, JsonSemAction *sem) { /* * an object is a possibly empty sequence of object fields, separated by * commas and surrounded by curly braces. */ json_struct_action ostart = sem->object_start; json_struct_action oend = sem->object_end; JsonTokenType tok; check_stack_depth(); if (ostart != NULL) (*ostart) (sem->semstate); * itself. Note that we increment this after we call the semantic routine * for the object start and restore it before we call the routine for the * object end. */ lex->lex_level++; /* we know this will succeeed, just clearing the token */ lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START); tok = lex_peek(lex); switch (tok) { case JSON_TOKEN_STRING: parse_object_field(lex, sem); while (lex_accept(lex, JSON_TOKEN_COMMA, NULL)) parse_object_field(lex, sem); break; case JSON_TOKEN_OBJECT_END: break; default: /* case of an invalid initial token inside the object */ report_parse_error(JSON_PARSE_OBJECT_START, lex); } lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END); lex->lex_level--; if (oend != NULL) (*oend) (sem->semstate); }
164,680