instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SavePayload(size_t handle, uint32_t *payload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp && payload) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fwrite(payload, 1, mp4->metasizes[index], mp4->mediafp); } return; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
void SavePayload(size_t handle, uint32_t *payload, uint32_t index) void LongSeek(mp4object *mp4, int64_t offset) { if (mp4 && offset) { if (mp4->filepos + offset < mp4->filesize) { LONGSEEK(mp4->mediafp, offset, SEEK_CUR); mp4->filepos += offset; } else { mp4->filepos = mp4->filesize; } } }
169,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_mmx_bitdepth_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0: 0); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_mmx_bitdepth_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ PNG_UNUSED(png_ptr) return 0L; }
172,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vrrp_print(netdissect_options *ndo, register const u_char *bp, register u_int len, register const u_char *bp2, int ttl) { int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */ const char *type_s; ND_TCHECK(bp[0]); version = (bp[0] & 0xf0) >> 4; type = bp[0] & 0x0f; type_s = tok2str(type2str, "unknown type (%u)", type); ND_PRINT((ndo, "VRRPv%u, %s", version, type_s)); if (ttl != 255) ND_PRINT((ndo, ", (ttl %u)", ttl)); if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT) return; ND_TCHECK(bp[2]); ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2])); ND_TCHECK(bp[5]); if (version == 2) { auth_type = bp[4]; ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type))); ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len)); } else { /* version == 3 */ uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5]; ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len)); } if (ndo->ndo_vflag) { int naddrs = bp[3]; int i; char c; if (version == 2 && ND_TTEST2(bp[0], len)) { struct cksum_vec vec[1]; vec[0].ptr = bp; vec[0].len = len; if (in_cksum(vec, 1)) ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } if (version == 3 && ND_TTEST2(bp[0], len)) { uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp, len, len, IPPROTO_VRRP); if (cksum) ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } ND_PRINT((ndo, ", addrs")); if (naddrs > 1) ND_PRINT((ndo, "(%d)", naddrs)); ND_PRINT((ndo, ":")); c = ' '; bp += 8; for (i = 0; i < naddrs; i++) { ND_TCHECK(bp[3]); ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp))); c = ','; bp += 4; } if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */ ND_TCHECK(bp[7]); ND_PRINT((ndo, " auth \"")); if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); } } return; trunc: ND_PRINT((ndo, "[|vrrp]")); } Commit Message: (for 4.9.3) CVE-2018-14463/VRRP: Add a missing bounds check In vrrp_print(). This fixes a buffer over-read discovered by Bhargava Shastry. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
vrrp_print(netdissect_options *ndo, register const u_char *bp, register u_int len, register const u_char *bp2, int ttl) { int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */ const char *type_s; ND_TCHECK(bp[0]); version = (bp[0] & 0xf0) >> 4; type = bp[0] & 0x0f; type_s = tok2str(type2str, "unknown type (%u)", type); ND_PRINT((ndo, "VRRPv%u, %s", version, type_s)); if (ttl != 255) ND_PRINT((ndo, ", (ttl %u)", ttl)); if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT) return; ND_TCHECK(bp[2]); ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2])); ND_TCHECK(bp[5]); if (version == 2) { auth_type = bp[4]; ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type))); ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len)); } else { /* version == 3 */ uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5]; ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len)); } if (ndo->ndo_vflag) { int naddrs = bp[3]; int i; char c; if (version == 2 && ND_TTEST2(bp[0], len)) { struct cksum_vec vec[1]; vec[0].ptr = bp; vec[0].len = len; if (in_cksum(vec, 1)) { ND_TCHECK_16BITS(&bp[6]); ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } } if (version == 3 && ND_TTEST2(bp[0], len)) { uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp, len, len, IPPROTO_VRRP); if (cksum) ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } ND_PRINT((ndo, ", addrs")); if (naddrs > 1) ND_PRINT((ndo, "(%d)", naddrs)); ND_PRINT((ndo, ":")); c = ' '; bp += 8; for (i = 0; i < naddrs; i++) { ND_TCHECK(bp[3]); ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp))); c = ','; bp += 4; } if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */ ND_TCHECK(bp[7]); ND_PRINT((ndo, " auth \"")); if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); } } return; trunc: ND_PRINT((ndo, "[|vrrp]")); }
169,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) { if (isMainThread()) blobRegistry().registerBlobURL(url, blobData); else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData)); callOnMainThread(&registerBlobURLTask, context.leakPtr()); } } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) void BlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) { if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) { WebBlobData webBlobData(blobData); registry->registerBlobURL(url, webBlobData); } } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData)); callOnMainThread(&registerBlobURLTask, context.leakPtr()); } }
170,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen - 1) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, "%s=", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, "", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, "/", option + 4); break; case OPTION_U8: dest += sprintf(dest, "%u", *option); break; case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, "%u", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, "bad", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2" */ const char *pfx = ""; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = " "; dest += sprintf(dest, "/%u ", mask); /* print router */ dest += sprint_nip(dest, "", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..." * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value ("optname=") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* "", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* "+ 4" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, " ", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., "optname=") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return "optname=" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = ""; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = " "; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\0'; } /* while */ return ret; } Commit Message: CWE ID: CWE-119
static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, "%s=", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, "", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, "/", option + 4); break; case OPTION_U8: dest += sprintf(dest, "%u", *option); break; case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, "%u", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, "bad", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2" */ const char *pfx = ""; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = " "; dest += sprintf(dest, "/%u ", mask); /* print router */ dest += sprint_nip(dest, "", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..." * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value ("optname=") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* "", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* "+ 4" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, " ", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., "optname=") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return "optname=" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = ""; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = " "; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\0'; } /* while */ return ret; }
165,349
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); smart_str_appendl(soap_headers, (char*)buf, len); smart_str_append_const(soap_headers, "\r\n"); efree(buf); smart_str_free(&auth); return 1; } return 0; } Commit Message: CWE ID:
int proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS && Z_TYPE_PP(login) == IS_STRING) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS && Z_TYPE_PP(password) == IS_STRING) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); smart_str_appendl(soap_headers, (char*)buf, len); smart_str_append_const(soap_headers, "\r\n"); efree(buf); smart_str_free(&auth); return 1; } return 0; }
165,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } Commit Message: Fix OOB reads of the TGA decompression buffer It is possible to craft TGA files which will overflow the decompression buffer, but not the image's bitmap. Therefore we also have to check for potential decompression buffer overflows. This issue had been reported by Ibrahim El-Sayed to security@libgd.org; a modified case exposing an off-by-one error of the first patch had been provided by Konrad Beckmann. This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906 as well. CWE ID: CWE-125
int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if (buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; }
170,120
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __init proc_root_init(void) { struct vfsmount *mnt; int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; mnt = kern_mount_data(&proc_fs_type, &init_pid_ns); if (IS_ERR(mnt)) { unregister_filesystem(&proc_fs_type); return; } init_pid_ns.proc_mnt = mnt; proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_mkdir("openprom", NULL); #endif proc_tty_init(); #ifdef CONFIG_PROC_DEVICETREE proc_device_tree_init(); #endif proc_mkdir("bus", NULL); proc_sys_init(); } Commit Message: procfs: fix a vfsmount longterm reference leak kern_mount() doesn't pair with plain mntput()... Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-119
void __init proc_root_init(void) { int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; err = pid_ns_prepare_proc(&init_pid_ns); if (err) { unregister_filesystem(&proc_fs_type); return; } proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_mkdir("openprom", NULL); #endif proc_tty_init(); #ifdef CONFIG_PROC_DEVICETREE proc_device_tree_init(); #endif proc_mkdir("bus", NULL); proc_sys_init(); }
165,615
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::sendCommand( OMX_COMMANDTYPE cmd, OMX_S32 param) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && cmd == OMX_CommandStateSet) { if (param == OMX_StateIdle) { bufferSource->omxIdle(); } else if (param == OMX_StateLoaded) { bufferSource->omxLoaded(); setGraphicBufferSource(NULL); } } Mutex::Autolock autoLock(mLock); { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } const char *paramString = cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param); CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL); CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); return StatusFromOMXError(err); } 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
status_t OMXNodeInstance::sendCommand( OMX_COMMANDTYPE cmd, OMX_S32 param) { if (cmd == OMX_CommandStateSet) { // We do not support returning from unloaded state, so there are no configurations past // first StateSet command. mSailed = true; } const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && cmd == OMX_CommandStateSet) { if (param == OMX_StateIdle) { bufferSource->omxIdle(); } else if (param == OMX_StateLoaded) { bufferSource->omxLoaded(); setGraphicBufferSource(NULL); } } Mutex::Autolock autoLock(mLock); { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } const char *paramString = cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param); CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL); CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); return StatusFromOMXError(err); }
174,137
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: e1000e_ring_empty(E1000ECore *core, const E1000E_RingInfo *r) { return core->mac[r->dh] == core->mac[r->dt]; } Commit Message: CWE ID: CWE-835
e1000e_ring_empty(E1000ECore *core, const E1000E_RingInfo *r) { return core->mac[r->dh] == core->mac[r->dt] || core->mac[r->dt] >= core->mac[r->dlen] / E1000_RING_DESC_LEN; }
164,799
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long do_io_submit(aio_context_t ctx_id, long nr, struct iocb __user *__user *iocbpp, bool compat) { struct kioctx *ctx; long ret = 0; int i = 0; struct blk_plug plug; struct kiocb_batch batch; if (unlikely(nr < 0)) return -EINVAL; if (unlikely(nr > LONG_MAX/sizeof(*iocbpp))) nr = LONG_MAX/sizeof(*iocbpp); if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp))))) return -EFAULT; ctx = lookup_ioctx(ctx_id); if (unlikely(!ctx)) { pr_debug("EINVAL: io_submit: invalid context id\n"); return -EINVAL; } kiocb_batch_init(&batch, nr); blk_start_plug(&plug); /* * AKPM: should this return a partial result if some of the IOs were * successfully submitted? */ for (i=0; i<nr; i++) { struct iocb __user *user_iocb; struct iocb tmp; if (unlikely(__get_user(user_iocb, iocbpp + i))) { ret = -EFAULT; break; } if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) { ret = -EFAULT; break; } ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat); if (ret) break; } blk_finish_plug(&plug); kiocb_batch_free(&batch); put_ioctx(ctx); return i ? i : ret; } Commit Message: Unused iocbs in a batch should not be accounted as active. commit 69e4747ee9727d660b88d7e1efe0f4afcb35db1b upstream. Since commit 080d676de095 ("aio: allocate kiocbs in batches") iocbs are allocated in a batch during processing of first iocbs. All iocbs in a batch are automatically added to ctx->active_reqs list and accounted in ctx->reqs_active. If one (not the last one) of iocbs submitted by an user fails, further iocbs are not processed, but they are still present in ctx->active_reqs and accounted in ctx->reqs_active. This causes process to stuck in a D state in wait_for_all_aios() on exit since ctx->reqs_active will never go down to zero. Furthermore since kiocb_batch_free() frees iocb without removing it from active_reqs list the list become corrupted which may cause oops. Fix this by removing iocb from ctx->active_reqs and updating ctx->reqs_active in kiocb_batch_free(). Signed-off-by: Gleb Natapov <gleb@redhat.com> Reviewed-by: Jeff Moyer <jmoyer@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de> CWE ID: CWE-399
long do_io_submit(aio_context_t ctx_id, long nr, struct iocb __user *__user *iocbpp, bool compat) { struct kioctx *ctx; long ret = 0; int i = 0; struct blk_plug plug; struct kiocb_batch batch; if (unlikely(nr < 0)) return -EINVAL; if (unlikely(nr > LONG_MAX/sizeof(*iocbpp))) nr = LONG_MAX/sizeof(*iocbpp); if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp))))) return -EFAULT; ctx = lookup_ioctx(ctx_id); if (unlikely(!ctx)) { pr_debug("EINVAL: io_submit: invalid context id\n"); return -EINVAL; } kiocb_batch_init(&batch, nr); blk_start_plug(&plug); /* * AKPM: should this return a partial result if some of the IOs were * successfully submitted? */ for (i=0; i<nr; i++) { struct iocb __user *user_iocb; struct iocb tmp; if (unlikely(__get_user(user_iocb, iocbpp + i))) { ret = -EFAULT; break; } if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) { ret = -EFAULT; break; } ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat); if (ret) break; } blk_finish_plug(&plug); kiocb_batch_free(ctx, &batch); put_ioctx(ctx); return i ? i : ret; }
165,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dispatch_discard_io(struct xen_blkif *blkif, struct blkif_request *req) { int err = 0; int status = BLKIF_RSP_OKAY; struct block_device *bdev = blkif->vbd.bdev; unsigned long secure; blkif->st_ds_req++; xen_blkif_get(blkif); secure = (blkif->vbd.discard_secure && (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ? BLKDEV_DISCARD_SECURE : 0; err = blkdev_issue_discard(bdev, req->u.discard.sector_number, req->u.discard.nr_sectors, GFP_KERNEL, secure); if (err == -EOPNOTSUPP) { pr_debug(DRV_PFX "discard op failed, not supported\n"); status = BLKIF_RSP_EOPNOTSUPP; } else if (err) status = BLKIF_RSP_ERROR; make_response(blkif, req->u.discard.id, req->operation, status); xen_blkif_put(blkif); return err; } Commit Message: xen/blkback: Check device permissions before allowing OP_DISCARD We need to make sure that the device is not RO or that the request is not past the number of sectors we want to issue the DISCARD operation for. This fixes CVE-2013-2140. Cc: stable@vger.kernel.org Acked-by: Jan Beulich <JBeulich@suse.com> Acked-by: Ian Campbell <Ian.Campbell@citrix.com> [v1: Made it pr_warn instead of pr_debug] Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> CWE ID: CWE-20
static int dispatch_discard_io(struct xen_blkif *blkif, struct blkif_request *req) { int err = 0; int status = BLKIF_RSP_OKAY; struct block_device *bdev = blkif->vbd.bdev; unsigned long secure; struct phys_req preq; preq.sector_number = req->u.discard.sector_number; preq.nr_sects = req->u.discard.nr_sectors; err = xen_vbd_translate(&preq, blkif, WRITE); if (err) { pr_warn(DRV_PFX "access denied: DISCARD [%llu->%llu] on dev=%04x\n", preq.sector_number, preq.sector_number + preq.nr_sects, blkif->vbd.pdevice); goto fail_response; } blkif->st_ds_req++; xen_blkif_get(blkif); secure = (blkif->vbd.discard_secure && (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ? BLKDEV_DISCARD_SECURE : 0; err = blkdev_issue_discard(bdev, req->u.discard.sector_number, req->u.discard.nr_sectors, GFP_KERNEL, secure); fail_response: if (err == -EOPNOTSUPP) { pr_debug(DRV_PFX "discard op failed, not supported\n"); status = BLKIF_RSP_EOPNOTSUPP; } else if (err) status = BLKIF_RSP_ERROR; make_response(blkif, req->u.discard.id, req->operation, status); xen_blkif_put(blkif); return err; }
166,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxInterface *decoder = NULL; const VpxVideoInfo *info = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame."); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { vpx_img_write(img, outfile); ++frame_cnt; } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec"); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxInterface *decoder = NULL; const VpxVideoInfo *info = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface())); if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame."); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { vpx_img_write(img, outfile); ++frame_cnt; } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec"); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; }
174,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static byte parseHexByte(const char * &str) { byte b = parseHexChar(str[0]); if (str[1] == ':' || str[1] == '\0') { str += 2; return b; } else { b = b << 4 | parseHexChar(str[1]); str += 3; return b; } } Commit Message: Deal correctly with short strings The parseMacAddress function anticipates only properly formed MAC addresses (6 hexadecimal octets separated by ":"). This change properly deals with situations where the string is shorter than expected, making sure that the passed in char* reference in parseHexByte never exceeds the end of the string. BUG: 28164077 TEST: Added a main function: int main(int argc, char **argv) { unsigned char addr[6]; if (argc > 1) { memset(addr, 0, sizeof(addr)); parseMacAddress(argv[1], addr); printf("Result: %02x:%02x:%02x:%02x:%02x:%02x\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); } } Tested with "", "a" "ab" "ab:c" "abxc". Change-Id: I0db8d0037e48b62333d475296a45b22ab0efe386 CWE ID: CWE-200
static byte parseHexByte(const char * &str) { if (str[0] == '\0') { ALOGE("Passed an empty string"); return 0; } byte b = parseHexChar(str[0]); if (str[1] == '\0' || str[1] == ':') { str ++; } else { b = b << 4 | parseHexChar(str[1]); str += 2; } // Skip trailing delimiter if not at the end of the string. if (str[0] != '\0') { str++; } return b; }
173,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int override_release(char __user *release, int len) { int ret = 0; char buf[65]; if (current->personality & UNAME26) { char *rest = UTS_RELEASE; int ndots = 0; unsigned v; while (*rest) { if (*rest == '.' && ++ndots >= 3) break; if (!isdigit(*rest) && *rest != '.') break; rest++; } v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40; snprintf(buf, len, "2.6.%u%s", v, rest); ret = copy_to_user(release, buf, len); } return ret; } Commit Message: kernel/sys.c: fix stack memory content leak via UNAME26 Calling uname() with the UNAME26 personality set allows a leak of kernel stack contents. This fixes it by defensively calculating the length of copy_to_user() call, making the len argument unsigned, and initializing the stack buffer to zero (now technically unneeded, but hey, overkill). CVE-2012-0957 Reported-by: PaX Team <pageexec@freemail.hu> Signed-off-by: Kees Cook <keescook@chromium.org> Cc: Andi Kleen <ak@linux.intel.com> Cc: PaX Team <pageexec@freemail.hu> Cc: Brad Spengler <spender@grsecurity.net> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-16
static int override_release(char __user *release, int len) static int override_release(char __user *release, size_t len) { int ret = 0; if (current->personality & UNAME26) { const char *rest = UTS_RELEASE; char buf[65] = { 0 }; int ndots = 0; unsigned v; size_t copy; while (*rest) { if (*rest == '.' && ++ndots >= 3) break; if (!isdigit(*rest) && *rest != '.') break; rest++; } v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40; copy = min(sizeof(buf), max_t(size_t, 1, len)); copy = scnprintf(buf, copy, "2.6.%u%s", v, rest); ret = copy_to_user(release, buf, copy + 1); } return ret; }
165,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv; unsigned ii; const unsigned char *tag = NULL; unsigned char ops_DF[8] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; unsigned char ops_EF[8] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); if (!file->sec_attr_len) { sc_log_hex(ctx, "ACLs not found in data", buf, buflen); sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type); if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) { file->type = SC_FILE_TYPE_DF; } else { LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } } sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len); for (ii = 0; ii < file->sec_attr_len / 2; ii++) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; unsigned char acl = *(file->sec_attr + ii*2); unsigned char cred_id = *(file->sec_attr + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id); if (op == 0xFF) ; else if (!acl && !cred_id) sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); else if (acl == 0xFF) sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); else if (acl & AUTHENTIC_AC_SM_MASK) sc_file_add_acl_entry(file, op, SC_AC_SCB, sc); else if (cred_id) sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id); else sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } LOG_FUNC_RETURN(ctx, 0); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv; unsigned ii; const unsigned char *tag = NULL; unsigned char ops_DF[8] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; unsigned char ops_EF[8] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); if (!file->sec_attr_len) { sc_log_hex(ctx, "ACLs not found in data", buf, buflen); sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type); if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) { file->type = SC_FILE_TYPE_DF; } else { LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } } sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len); for (ii = 0; ii < file->sec_attr_len / 2 && ii < sizeof ops_DF; ii++) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; unsigned char acl = *(file->sec_attr + ii*2); unsigned char cred_id = *(file->sec_attr + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id); if (op == 0xFF) ; else if (!acl && !cred_id) sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); else if (acl == 0xFF) sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); else if (acl & AUTHENTIC_AC_SM_MASK) sc_file_add_acl_entry(file, op, SC_AC_SCB, sc); else if (cred_id) sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id); else sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } LOG_FUNC_RETURN(ctx, 0); }
169,048
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec) { dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm; dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; WORD32 j; UWORD8 u1_buf_mode; struct MMCParams *ps_mmc_params; UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst; ps_slice->u1_mmco_equalto5 = 0; { if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { ps_slice->u1_no_output_of_prior_pics_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: no_output_of_prior_pics_flag", ps_slice->u1_no_output_of_prior_pics_flag); ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: long_term_reference_flag", ps_slice->u1_long_term_reference_flag); ps_dpb_cmds->u1_idr_pic = 1; ps_dpb_cmds->u1_no_output_of_prior_pics_flag = ps_slice->u1_no_output_of_prior_pics_flag; ps_dpb_cmds->u1_long_term_reference_flag = ps_slice->u1_long_term_reference_flag; } else { u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode); ps_dpb_cmds->u1_buf_mode = u1_buf_mode; j = 0; if(u1_buf_mode == 1) { UWORD32 u4_mmco; UWORD32 u4_diff_pic_num; UWORD32 u4_lt_idx, u4_max_lt_idx; u4_mmco = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); while(u4_mmco != END_OF_MMCO) { ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j]; ps_mmc_params->u4_mmco = u4_mmco; switch(u4_mmco) { case MARK_ST_PICNUM_AS_NONREF: u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; break; case MARK_LT_INDEX_AS_NONREF: u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; case MARK_ST_PICNUM_AS_LT_INDEX: u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; case SET_MAX_LT_INDEX: { u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx; break; } case RESET_REF_PICTURES: { ps_slice->u1_mmco_equalto5 = 1; break; } case SET_LT_INDEX: u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; default: break; } u4_mmco = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); j++; } ps_dpb_cmds->u1_num_of_commands = j; } } ps_dpb_cmds->u1_dpb_commands_read = 1; ps_dpb_cmds->u1_dpb_commands_read_slc = 1; } u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst; return u4_bit_ofst; } Commit Message: Return error when there are more mmco params than allocated size Bug: 25818142 Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d CWE ID: CWE-119
WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec) { dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm; dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; WORD32 j; UWORD8 u1_buf_mode; struct MMCParams *ps_mmc_params; UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst; ps_slice->u1_mmco_equalto5 = 0; { if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { ps_slice->u1_no_output_of_prior_pics_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: no_output_of_prior_pics_flag", ps_slice->u1_no_output_of_prior_pics_flag); ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: long_term_reference_flag", ps_slice->u1_long_term_reference_flag); ps_dpb_cmds->u1_idr_pic = 1; ps_dpb_cmds->u1_no_output_of_prior_pics_flag = ps_slice->u1_no_output_of_prior_pics_flag; ps_dpb_cmds->u1_long_term_reference_flag = ps_slice->u1_long_term_reference_flag; } else { u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode); ps_dpb_cmds->u1_buf_mode = u1_buf_mode; j = 0; if(u1_buf_mode == 1) { UWORD32 u4_mmco; UWORD32 u4_diff_pic_num; UWORD32 u4_lt_idx, u4_max_lt_idx; u4_mmco = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); while(u4_mmco != END_OF_MMCO) { if (j >= MAX_REF_BUFS) { ALOGE("b/25818142"); android_errorWriteLog(0x534e4554, "25818142"); ps_dpb_cmds->u1_num_of_commands = 0; return -1; } ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j]; ps_mmc_params->u4_mmco = u4_mmco; switch(u4_mmco) { case MARK_ST_PICNUM_AS_NONREF: u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; break; case MARK_LT_INDEX_AS_NONREF: u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; case MARK_ST_PICNUM_AS_LT_INDEX: u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; case SET_MAX_LT_INDEX: { u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx; break; } case RESET_REF_PICTURES: { ps_slice->u1_mmco_equalto5 = 1; break; } case SET_LT_INDEX: u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; default: break; } u4_mmco = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); j++; } ps_dpb_cmds->u1_num_of_commands = j; } } ps_dpb_cmds->u1_dpb_commands_read = 1; ps_dpb_cmds->u1_dpb_commands_read_slc = 1; } u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst; return u4_bit_ofst; }
173,907
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ospf6_decode_v3(netdissect_options *ndo, register const struct ospf6hdr *op, register const u_char *dataend) { register const rtrid_t *ap; register const struct lsr6 *lsrp; register const struct lsa6_hdr *lshp; register const struct lsa6 *lsap; register int i; switch (op->ospf6_type) { case OSPF_TYPE_HELLO: { register const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&hellop->hello_options)))); ND_TCHECK(hellop->hello_deadint); ND_PRINT((ndo, "\n\t Hello Timer %us, Dead Timer %us, Interface-ID %s, Priority %u", EXTRACT_16BITS(&hellop->hello_helloint), EXTRACT_16BITS(&hellop->hello_deadint), ipaddr_string(ndo, &hellop->hello_ifid), hellop->hello_priority)); ND_TCHECK(hellop->hello_dr); if (EXTRACT_32BITS(&hellop->hello_dr) != 0) ND_PRINT((ndo, "\n\t Designated Router %s", ipaddr_string(ndo, &hellop->hello_dr))); ND_TCHECK(hellop->hello_bdr); if (EXTRACT_32BITS(&hellop->hello_bdr) != 0) ND_PRINT((ndo, ", Backup Designated Router %s", ipaddr_string(ndo, &hellop->hello_bdr))); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "\n\t Neighbor List:")); ap = hellop->hello_neighbor; while ((const u_char *)ap < dataend) { ND_TCHECK(*ap); ND_PRINT((ndo, "\n\t %s", ipaddr_string(ndo, ap))); ++ap; } } break; /* HELLO */ } case OSPF_TYPE_DD: { register const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(ddp->db_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&ddp->db_options)))); ND_TCHECK(ddp->db_flags); ND_PRINT((ndo, ", DD Flags [%s]", bittok2str(ospf6_dd_flag_values,"none",ddp->db_flags))); ND_TCHECK(ddp->db_seq); ND_PRINT((ndo, ", MTU %u, DD-Sequence 0x%08x", EXTRACT_16BITS(&ddp->db_mtu), EXTRACT_32BITS(&ddp->db_seq))); if (ndo->ndo_vflag > 1) { /* Print all the LS adv's */ lshp = ddp->db_lshdr; while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; } case OSPF_TYPE_LS_REQ: if (ndo->ndo_vflag > 1) { lsrp = (const struct lsr6 *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lsrp < dataend) { ND_TCHECK(*lsrp); ND_PRINT((ndo, "\n\t Advertising Router %s", ipaddr_string(ndo, &lsrp->ls_router))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsrp->ls_type), &lsrp->ls_stateid); ++lsrp; } } break; case OSPF_TYPE_LS_UPDATE: if (ndo->ndo_vflag > 1) { register const struct lsu6 *lsup = (const struct lsu6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(lsup->lsu_count); i = EXTRACT_32BITS(&lsup->lsu_count); lsap = lsup->lsu_lsa; while ((const u_char *)lsap < dataend && i--) { if (ospf6_print_lsa(ndo, lsap, dataend)) goto trunc; lsap = (const struct lsa6 *)((const u_char *)lsap + EXTRACT_16BITS(&lsap->ls_hdr.ls_length)); } } break; case OSPF_TYPE_LS_ACK: if (ndo->ndo_vflag > 1) { lshp = (const struct lsa6_hdr *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; default: break; } return (0); trunc: return (1); } Commit Message: CVE-2017-13036/OSPFv3: Add a bounds check before fetching data This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
ospf6_decode_v3(netdissect_options *ndo, register const struct ospf6hdr *op, register const u_char *dataend) { register const rtrid_t *ap; register const struct lsr6 *lsrp; register const struct lsa6_hdr *lshp; register const struct lsa6 *lsap; register int i; switch (op->ospf6_type) { case OSPF_TYPE_HELLO: { register const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK_32BITS(&hellop->hello_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&hellop->hello_options)))); ND_TCHECK(hellop->hello_deadint); ND_PRINT((ndo, "\n\t Hello Timer %us, Dead Timer %us, Interface-ID %s, Priority %u", EXTRACT_16BITS(&hellop->hello_helloint), EXTRACT_16BITS(&hellop->hello_deadint), ipaddr_string(ndo, &hellop->hello_ifid), hellop->hello_priority)); ND_TCHECK(hellop->hello_dr); if (EXTRACT_32BITS(&hellop->hello_dr) != 0) ND_PRINT((ndo, "\n\t Designated Router %s", ipaddr_string(ndo, &hellop->hello_dr))); ND_TCHECK(hellop->hello_bdr); if (EXTRACT_32BITS(&hellop->hello_bdr) != 0) ND_PRINT((ndo, ", Backup Designated Router %s", ipaddr_string(ndo, &hellop->hello_bdr))); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "\n\t Neighbor List:")); ap = hellop->hello_neighbor; while ((const u_char *)ap < dataend) { ND_TCHECK(*ap); ND_PRINT((ndo, "\n\t %s", ipaddr_string(ndo, ap))); ++ap; } } break; /* HELLO */ } case OSPF_TYPE_DD: { register const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(ddp->db_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&ddp->db_options)))); ND_TCHECK(ddp->db_flags); ND_PRINT((ndo, ", DD Flags [%s]", bittok2str(ospf6_dd_flag_values,"none",ddp->db_flags))); ND_TCHECK(ddp->db_seq); ND_PRINT((ndo, ", MTU %u, DD-Sequence 0x%08x", EXTRACT_16BITS(&ddp->db_mtu), EXTRACT_32BITS(&ddp->db_seq))); if (ndo->ndo_vflag > 1) { /* Print all the LS adv's */ lshp = ddp->db_lshdr; while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; } case OSPF_TYPE_LS_REQ: if (ndo->ndo_vflag > 1) { lsrp = (const struct lsr6 *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lsrp < dataend) { ND_TCHECK(*lsrp); ND_PRINT((ndo, "\n\t Advertising Router %s", ipaddr_string(ndo, &lsrp->ls_router))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsrp->ls_type), &lsrp->ls_stateid); ++lsrp; } } break; case OSPF_TYPE_LS_UPDATE: if (ndo->ndo_vflag > 1) { register const struct lsu6 *lsup = (const struct lsu6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(lsup->lsu_count); i = EXTRACT_32BITS(&lsup->lsu_count); lsap = lsup->lsu_lsa; while ((const u_char *)lsap < dataend && i--) { if (ospf6_print_lsa(ndo, lsap, dataend)) goto trunc; lsap = (const struct lsa6 *)((const u_char *)lsap + EXTRACT_16BITS(&lsap->ls_hdr.ls_length)); } } break; case OSPF_TYPE_LS_ACK: if (ndo->ndo_vflag > 1) { lshp = (const struct lsa6_hdr *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; default: break; } return (0); trunc: return (1); }
167,847
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32, unsigned int size_left, enum compat_mwt type, struct ebt_entries_buf_state *state, const void *base) { int growth = 0; char *buf; if (size_left == 0) return 0; buf = (char *) match32; while (size_left >= sizeof(*match32)) { struct ebt_entry_match *match_kern; int ret; match_kern = (struct ebt_entry_match *) state->buf_kern_start; if (match_kern) { char *tmp; tmp = state->buf_kern_start + state->buf_kern_offset; match_kern = (struct ebt_entry_match *) tmp; } ret = ebt_buf_add(state, buf, sizeof(*match32)); if (ret < 0) return ret; size_left -= sizeof(*match32); /* add padding before match->data (if any) */ ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize()); if (ret < 0) return ret; if (match32->match_size > size_left) return -EINVAL; size_left -= match32->match_size; ret = compat_mtw_from_user(match32, type, state, base); if (ret < 0) return ret; if (WARN_ON(ret < match32->match_size)) return -EINVAL; growth += ret - match32->match_size; growth += ebt_compat_entry_padsize(); buf += sizeof(*match32); buf += match32->match_size; if (match_kern) match_kern->match_size = ret; WARN_ON(type == EBT_COMPAT_TARGET && size_left); match32 = (struct compat_ebt_entry_mwt *) buf; } return growth; } Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets We need to make sure the offsets are not out of range of the total size. Also check that they are in ascending order. The WARN_ON triggered by syzkaller (it sets panic_on_warn) is changed to also bail out, no point in continuing parsing. Briefly tested with simple ruleset of -A INPUT --limit 1/s' --log plus jump to custom chains using 32bit ebtables binary. Reported-by: <syzbot+845a53d13171abf8bf29@syzkaller.appspotmail.com> Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-787
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32, unsigned int size_left, enum compat_mwt type, struct ebt_entries_buf_state *state, const void *base) { int growth = 0; char *buf; if (size_left == 0) return 0; buf = (char *) match32; while (size_left >= sizeof(*match32)) { struct ebt_entry_match *match_kern; int ret; match_kern = (struct ebt_entry_match *) state->buf_kern_start; if (match_kern) { char *tmp; tmp = state->buf_kern_start + state->buf_kern_offset; match_kern = (struct ebt_entry_match *) tmp; } ret = ebt_buf_add(state, buf, sizeof(*match32)); if (ret < 0) return ret; size_left -= sizeof(*match32); /* add padding before match->data (if any) */ ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize()); if (ret < 0) return ret; if (match32->match_size > size_left) return -EINVAL; size_left -= match32->match_size; ret = compat_mtw_from_user(match32, type, state, base); if (ret < 0) return ret; if (WARN_ON(ret < match32->match_size)) return -EINVAL; growth += ret - match32->match_size; growth += ebt_compat_entry_padsize(); buf += sizeof(*match32); buf += match32->match_size; if (match_kern) match_kern->match_size = ret; if (WARN_ON(type == EBT_COMPAT_TARGET && size_left)) return -EINVAL; match32 = (struct compat_ebt_entry_mwt *) buf; } return growth; }
169,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350 CWE ID: CWE-787
static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); }
168,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { uint32_t end = readU16(data, kEndCountOffset + 2 * i); uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i)); if (end < start) { return false; } uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (uint32_t j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (uint32_t j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { continue; } uint32_t glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; } Commit Message: Add error logging on invalid cmap - DO NOT MERGE This patch logs instances of fonts with invalid cmap tables. Bug: 25645298 Bug: 26413177 Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e CWE ID: CWE-20
static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { uint32_t end = readU16(data, kEndCountOffset + 2 * i); uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i)); if (end < start) { android_errorWriteLog(0x534e4554, "26413177"); return false; } uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (uint32_t j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (uint32_t j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { continue; } uint32_t glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; }
173,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SendNotImplementedError(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { std::string body = base::StringPrintf( "{\"status\":%d,\"value\":{\"message\":" "\"Command has not been implemented yet: %s %s\"}}", kUnknownCommand, request_info->request_method, request_info->uri); std::string header = base::StringPrintf( "HTTP/1.1 501 Not Implemented\r\n" "Content-Type:application/json\r\n" "Content-Length:%" PRIuS "\r\n" "\r\n", body.length()); LOG(ERROR) << header << body; mg_write(connection, header.data(), header.length()); mg_write(connection, body.data(), body.length()); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SendNotImplementedError(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { std::string body = base::StringPrintf( "{\"status\":%d,\"value\":{\"message\":" "\"Command has not been implemented yet: %s %s\"}}", kUnknownCommand, request_info->request_method, request_info->uri); std::string header = base::StringPrintf( "HTTP/1.1 501 Not Implemented\r\n" "Content-Type:application/json\r\n" "Content-Length:%" PRIuS "\r\n" "\r\n", body.length()); mg_write(connection, header.data(), header.length()); mg_write(connection, body.data(), body.length()); }
170,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *curl_easy_unescape(CURL *handle, const char *string, int length, int *olen) { int alloc = (length?length:(int)strlen(string))+1; char *ns = malloc(alloc); unsigned char in; int strindex=0; unsigned long hex; CURLcode res; if(!ns) return NULL; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(handle, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return NULL; } string+=2; alloc-=2; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; return ns; } Commit Message: URL sanitize: reject URLs containing bad data Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a decoded manner now use the new Curl_urldecode() function to reject URLs with embedded control codes (anything that is or decodes to a byte value less than 32). URLs containing such codes could easily otherwise be used to do harm and allow users to do unintended actions with otherwise innocent tools and applications. Like for example using a URL like pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get a mail and instead this would delete one. This flaw is considered a security vulnerability: CVE-2012-0036 Security advisory at: http://curl.haxx.se/docs/adv_20120124.html Reported by: Dan Fandrich CWE ID: CWE-89
char *curl_easy_unescape(CURL *handle, const char *string, int length, CURLcode Curl_urldecode(struct SessionHandle *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) { size_t alloc = (length?length:strlen(string))+1; char *ns = malloc(alloc); unsigned char in; size_t strindex=0; unsigned long hex; CURLcode res; if(!ns) return CURLE_OUT_OF_MEMORY; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(data, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return res; } string+=2; alloc-=2; } if(reject_ctrl && (in < 0x20)) { free(ns); return CURLE_URL_MALFORMAT; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; if(ostring) /* store output string */ *ostring = ns; return CURLE_OK; } /* * Unescapes the given URL escaped string of given length. Returns a * pointer to a malloced string with length given in *olen. * If length == 0, the length is assumed to be strlen(string). * If olen == NULL, no output length is stored. */ char *curl_easy_unescape(CURL *handle, const char *string, int length, int *olen) { char *str = NULL; size_t inputlen = length; size_t outputlen; CURLcode res = Curl_urldecode(handle, string, inputlen, &str, &outputlen, FALSE); if(res) return NULL; if(olen) *olen = curlx_uztosi(outputlen); return str; }
165,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: build_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap) { krb5_error_code retval = 0; char *r = NULL; krb5_data *data = NULL; krb5_int32 count = 0; krb5_int32 size = 2; /* initial guess at needed space */ char *component = NULL; data = malloc(size * sizeof(krb5_data)); if (!data) { retval = ENOMEM; } if (!retval) { r = strdup(realm); if (!r) { retval = ENOMEM; } } while (!retval && (component = va_arg(ap, char *))) { if (count == size) { krb5_data *new_data = NULL; size *= 2; new_data = realloc(data, size * sizeof(krb5_data)); if (new_data) { data = new_data; } else { retval = ENOMEM; } } if (!retval) { data[count].length = strlen(component); data[count].data = strdup(component); if (!data[count].data) { retval = ENOMEM; } count++; } } if (!retval) { princ->type = KRB5_NT_UNKNOWN; princ->magic = KV5M_PRINCIPAL; princ->realm = make_data(r, rlen); princ->data = data; princ->length = count; r = NULL; /* take ownership */ data = NULL; /* take ownership */ } if (data) { while (--count >= 0) { free(data[count].data); } free(data); } free(r); return retval; } Commit Message: Fix build_principal memory bug [CVE-2015-2697] In build_principal_va(), use k5memdup0() instead of strdup() to make a copy of the realm, to ensure that we allocate the correct number of bytes and do not read past the end of the input string. This bug affects krb5_build_principal(), krb5_build_principal_va(), and krb5_build_principal_alloc_va(). krb5_build_principal_ext() is not affected. CVE-2015-2697: In MIT krb5 1.7 and later, an authenticated attacker may be able to cause a KDC to crash using a TGS request with a large realm field beginning with a null byte. If the KDC attempts to find a referral to answer the request, it constructs a principal name for lookup using krb5_build_principal() with the requested realm. Due to a bug in this function, the null byte causes only one byte be allocated for the realm field of the constructed principal, far less than its length. Subsequent operations on the lookup principal may cause a read beyond the end of the mapped memory region, causing the KDC process to crash. CVSSv2: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8252 (new) target_version: 1.14 tags: pullup CWE ID: CWE-119
build_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap) { krb5_error_code retval = 0; char *r = NULL; krb5_data *data = NULL; krb5_int32 count = 0; krb5_int32 size = 2; /* initial guess at needed space */ char *component = NULL; data = malloc(size * sizeof(krb5_data)); if (!data) { retval = ENOMEM; } if (!retval) r = k5memdup0(realm, rlen, &retval); while (!retval && (component = va_arg(ap, char *))) { if (count == size) { krb5_data *new_data = NULL; size *= 2; new_data = realloc(data, size * sizeof(krb5_data)); if (new_data) { data = new_data; } else { retval = ENOMEM; } } if (!retval) { data[count].length = strlen(component); data[count].data = strdup(component); if (!data[count].data) { retval = ENOMEM; } count++; } } if (!retval) { princ->type = KRB5_NT_UNKNOWN; princ->magic = KV5M_PRINCIPAL; princ->realm = make_data(r, rlen); princ->data = data; princ->length = count; r = NULL; /* take ownership */ data = NULL; /* take ownership */ } if (data) { while (--count >= 0) { free(data[count].data); } free(data); } free(r); return retval; }
166,641
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( const VideoFrame* const src_frame, const VideoFrameLayout& dst_layout) { LOG_ASSERT(src_frame->IsMappable()); LOG_ASSERT(src_frame->format() == dst_layout.format()); auto dst_frame = VideoFrame::CreateFrameWithLayout( dst_layout, src_frame->visible_rect(), src_frame->natural_size(), src_frame->timestamp(), false /* zero_initialize_memory*/); if (!dst_frame) { LOG(ERROR) << "Failed to create VideoFrame"; return nullptr; } const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format()); LOG_ASSERT(dst_layout.planes().size() == num_planes); LOG_ASSERT(src_frame->layout().planes().size() == num_planes); for (size_t i = 0; i < num_planes; ++i) { libyuv::CopyPlane( src_frame->data(i), src_frame->layout().planes()[i].stride, dst_frame->data(i), dst_frame->layout().planes()[i].stride, VideoFrame::Columns(i, dst_frame->format(), dst_frame->natural_size().width()), VideoFrame::Rows(i, dst_frame->format(), dst_frame->natural_size().height())); } return dst_frame; } Commit Message: media/gpu/test: ImageProcessorClient: Use bytes for width and height in libyuv::CopyPlane() |width| is in bytes in libyuv::CopyPlane(). We formerly pass width in pixels. This should matter when a pixel format is used whose pixel is composed of more than one bytes. Bug: None Test: image_processor_test Change-Id: I98e90be70c8d0128319172d4d19f3a8017b65d78 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1553129 Commit-Queue: Hirokazu Honda <hiroh@chromium.org> Reviewed-by: Alexandre Courbot <acourbot@chromium.org> Cr-Commit-Position: refs/heads/master@{#648117} CWE ID: CWE-20
scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( const VideoFrame* const src_frame, const VideoFrameLayout& dst_layout) { LOG_ASSERT(src_frame->IsMappable()); LOG_ASSERT(src_frame->format() == dst_layout.format()); auto dst_frame = VideoFrame::CreateFrameWithLayout( dst_layout, src_frame->visible_rect(), src_frame->natural_size(), src_frame->timestamp(), false /* zero_initialize_memory*/); if (!dst_frame) { LOG(ERROR) << "Failed to create VideoFrame"; return nullptr; } const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format()); LOG_ASSERT(dst_layout.planes().size() == num_planes); LOG_ASSERT(src_frame->layout().planes().size() == num_planes); for (size_t i = 0; i < num_planes; ++i) { // |width| in libyuv::CopyPlane() is in bytes, not pixels. gfx::Size plane_size = VideoFrame::PlaneSize(dst_frame->format(), i, dst_frame->natural_size()); libyuv::CopyPlane( src_frame->data(i), src_frame->layout().planes()[i].stride, dst_frame->data(i), dst_frame->layout().planes()[i].stride, plane_size.width(), plane_size.height()); } return dst_frame; }
172,397
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Cluster::Cluster() : m_pSegment(NULL), m_element_start(0), m_index(0), m_pos(0), m_element_size(0), m_timecode(0), m_entries(NULL), m_entries_size(0), m_entries_count(0) //means "no entries" { } 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
Cluster::Cluster() :
174,248
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadCALSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent], header[MagickPathExtent], message[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register ssize_t i; unsigned long density, direction, height, orientation, pel_path, type, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CALS header. */ (void) memset(header,0,sizeof(header)); density=0; direction=0; orientation=1; pel_path=0; type=1; width=0; height=0; for (i=0; i < 16; i++) { if (ReadBlob(image,128,(unsigned char *) header) != 128) break; switch (*header) { case 'R': case 'r': { if (LocaleNCompare(header,"rdensty:",8) == 0) { (void) sscanf(header+8,"%lu",&density); break; } if (LocaleNCompare(header,"rpelcnt:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&width,&height); break; } if (LocaleNCompare(header,"rorient:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction); if (pel_path == 90) orientation=5; else if (pel_path == 180) orientation=3; else if (pel_path == 270) orientation=7; if (direction == 90) orientation++; break; } if (LocaleNCompare(header,"rtype:",6) == 0) { (void) sscanf(header+6,"%lu",&type); break; } break; } } } /* Read CALS pixels. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); while ((c=ReadBlobByte(image)) != EOF) (void) fputc(c,file); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"group4:%s", filename); (void) FormatLocaleString(message,MagickPathExtent,"%lux%lu",width,height); (void) CloneString(&read_info->size,message); (void) FormatLocaleString(message,MagickPathExtent,"%lu",density); (void) CloneString(&read_info->density,message); read_info->orientation=(OrientationType) orientation; image=ReadImage(read_info,exception); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"CALS",MagickPathExtent); } read_info=DestroyImageInfo(read_info); (void) RelinquishUniqueFileResource(filename); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199 CWE ID: CWE-20
static Image *ReadCALSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent], header[MagickPathExtent], message[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register ssize_t i; unsigned long density, direction, height, orientation, pel_path, type, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CALS header. */ (void) memset(header,0,sizeof(header)); density=0; direction=0; orientation=1; pel_path=0; type=1; width=0; height=0; for (i=0; i < 16; i++) { if (ReadBlob(image,128,(unsigned char *) header) != 128) break; switch (*header) { case 'R': case 'r': { if (LocaleNCompare(header,"rdensty:",8) == 0) { (void) sscanf(header+8,"%lu",&density); break; } if (LocaleNCompare(header,"rpelcnt:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&width,&height); break; } if (LocaleNCompare(header,"rorient:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction); if (pel_path == 90) orientation=5; else if (pel_path == 180) orientation=3; else if (pel_path == 270) orientation=7; if (direction == 90) orientation++; break; } if (LocaleNCompare(header,"rtype:",6) == 0) { (void) sscanf(header+6,"%lu",&type); break; } break; } } } /* Read CALS pixels. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); while ((c=ReadBlobByte(image)) != EOF) if (fputc(c,file) != c) break; (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"group4:%s", filename); (void) FormatLocaleString(message,MagickPathExtent,"%lux%lu",width,height); (void) CloneString(&read_info->size,message); (void) FormatLocaleString(message,MagickPathExtent,"%lu",density); (void) CloneString(&read_info->density,message); read_info->orientation=(OrientationType) orientation; image=ReadImage(read_info,exception); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"CALS",MagickPathExtent); } read_info=DestroyImageInfo(read_info); (void) RelinquishUniqueFileResource(filename); return(image); }
169,038
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } Commit Message: CWE ID: CWE-125
static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; if (off_pitch < 0) { off_begin -= bytesperline - 1; } for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; assert(off_cur_end >= off_cur); memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; }
165,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, true); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; }
173,525
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: init_ext2_xattr(void) { ext2_xattr_cache = mb_cache_create("ext2_xattr", 6); if (!ext2_xattr_cache) return -ENOMEM; return 0; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
init_ext2_xattr(void) #define HASH_BUCKET_BITS 10 struct mb2_cache *ext2_xattr_create_cache(void) { return mb2_cache_create(HASH_BUCKET_BITS); }
169,985
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */ { time_t timestamp = 0; php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; assert(ms != NULL); memset(ssb, 0, sizeof(php_stream_statbuf)); /* read-only across the board */ ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666; ssb->sb.st_size = ms->fsize; ssb->sb.st_mode |= S_IFREG; /* regular file */ #ifdef NETWARE ssb->sb.st_mtime.tv_sec = timestamp; ssb->sb.st_atime.tv_sec = timestamp; ssb->sb.st_ctime.tv_sec = timestamp; #else ssb->sb.st_mtime = timestamp; ssb->sb.st_atime = timestamp; ssb->sb.st_ctime = timestamp; #endif ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; /* this is only for APC, so use /dev/null device - no chance of conflict there! */ ssb->sb.st_dev = 0xC; /* generate unique inode number for alias/filename, so no phars will conflict */ ssb->sb.st_ino = 0; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; #endif #if !defined(PHP_WIN32) && !defined(__BEOS__) ssb->sb.st_blocks = -1; #endif return 0; } /* }}} */ Commit Message: CWE ID: CWE-20
static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */ { time_t timestamp = 0; php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; assert(ms != NULL); memset(ssb, 0, sizeof(php_stream_statbuf)); /* read-only across the board */ ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666; ssb->sb.st_size = ms->fsize; ssb->sb.st_mode |= S_IFREG; /* regular file */ #ifdef NETWARE ssb->sb.st_mtime.tv_sec = timestamp; ssb->sb.st_atime.tv_sec = timestamp; ssb->sb.st_ctime.tv_sec = timestamp; #else ssb->sb.st_mtime = timestamp; ssb->sb.st_atime = timestamp; ssb->sb.st_ctime = timestamp; #endif ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; /* this is only for APC, so use /dev/null device - no chance of conflict there! */ ssb->sb.st_dev = 0xC; /* generate unique inode number for alias/filename, so no phars will conflict */ ssb->sb.st_ino = 0; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; #endif #if !defined(PHP_WIN32) && !defined(__BEOS__) ssb->sb.st_blocks = -1; #endif return 0; } /* }}} */
165,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { return dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { int err; struct inode *inode = file_inode(vma->vm_file); sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); err = __dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(inode->i_sb); return err; } /* * Handle write fault for VM_MIXEDMAP mappings. Similarly to ext4_dax_mkwrite() * handler we check for races agaist truncate. Note that since we cycle through * i_mmap_sem, we are sure that also any hole punching that began before we * were called is finished by now and so if it included part of the file we * are working on, our pte will get unmapped and the check for pte_same() in * wp_pfn_shared() fails. Thus fault gets retried and things work out as * desired. */ static int ext4_dax_pfn_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; int ret = VM_FAULT_NOPAGE; loff_t size; sb_start_pagefault(sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); size = (i_size_read(inode) + PAGE_SIZE - 1) >> PAGE_SHIFT; if (vmf->pgoff >= size) ret = VM_FAULT_SIGBUS; up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(sb); return ret; }
167,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __init acpi_initrd_override(void *data, size_t size) { int sig, no, table_nr = 0, total_offset = 0; long offset = 0; struct acpi_table_header *table; char cpio_path[32] = "kernel/firmware/acpi/"; struct cpio_data file; if (data == NULL || size == 0) return; for (no = 0; no < ACPI_OVERRIDE_TABLES; no++) { file = find_cpio_data(cpio_path, data, size, &offset); if (!file.data) break; data += offset; size -= offset; if (file.size < sizeof(struct acpi_table_header)) { pr_err("ACPI OVERRIDE: Table smaller than ACPI header [%s%s]\n", cpio_path, file.name); continue; } table = file.data; for (sig = 0; table_sigs[sig]; sig++) if (!memcmp(table->signature, table_sigs[sig], 4)) break; if (!table_sigs[sig]) { pr_err("ACPI OVERRIDE: Unknown signature [%s%s]\n", cpio_path, file.name); continue; } if (file.size != table->length) { pr_err("ACPI OVERRIDE: File length does not match table length [%s%s]\n", cpio_path, file.name); continue; } if (acpi_table_checksum(file.data, table->length)) { pr_err("ACPI OVERRIDE: Bad table checksum [%s%s]\n", cpio_path, file.name); continue; } pr_info("%4.4s ACPI table found in initrd [%s%s][0x%x]\n", table->signature, cpio_path, file.name, table->length); all_tables_size += table->length; acpi_initrd_files[table_nr].data = file.data; acpi_initrd_files[table_nr].size = file.size; table_nr++; } if (table_nr == 0) return; acpi_tables_addr = memblock_find_in_range(0, max_low_pfn_mapped << PAGE_SHIFT, all_tables_size, PAGE_SIZE); if (!acpi_tables_addr) { WARN_ON(1); return; } /* * Only calling e820_add_reserve does not work and the * tables are invalid (memory got used) later. * memblock_reserve works as expected and the tables won't get modified. * But it's not enough on X86 because ioremap will * complain later (used by acpi_os_map_memory) that the pages * that should get mapped are not marked "reserved". * Both memblock_reserve and e820_add_region (via arch_reserve_mem_area) * works fine. */ memblock_reserve(acpi_tables_addr, all_tables_size); arch_reserve_mem_area(acpi_tables_addr, all_tables_size); /* * early_ioremap only can remap 256k one time. If we map all * tables one time, we will hit the limit. Need to map chunks * one by one during copying the same as that in relocate_initrd(). */ for (no = 0; no < table_nr; no++) { unsigned char *src_p = acpi_initrd_files[no].data; phys_addr_t size = acpi_initrd_files[no].size; phys_addr_t dest_addr = acpi_tables_addr + total_offset; phys_addr_t slop, clen; char *dest_p; total_offset += size; while (size) { slop = dest_addr & ~PAGE_MASK; clen = size; if (clen > MAP_CHUNK_SIZE - slop) clen = MAP_CHUNK_SIZE - slop; dest_p = early_ioremap(dest_addr & PAGE_MASK, clen + slop); memcpy(dest_p + slop, src_p, clen); early_iounmap(dest_p, clen + slop); src_p += clen; dest_addr += clen; size -= clen; } } } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <linn@hpe.com> CWE ID: CWE-264
void __init acpi_initrd_override(void *data, size_t size) { int sig, no, table_nr = 0, total_offset = 0; long offset = 0; struct acpi_table_header *table; char cpio_path[32] = "kernel/firmware/acpi/"; struct cpio_data file; if (data == NULL || size == 0) return; for (no = 0; no < ACPI_OVERRIDE_TABLES; no++) { file = find_cpio_data(cpio_path, data, size, &offset); if (!file.data) break; data += offset; size -= offset; if (file.size < sizeof(struct acpi_table_header)) { pr_err("ACPI OVERRIDE: Table smaller than ACPI header [%s%s]\n", cpio_path, file.name); continue; } table = file.data; for (sig = 0; table_sigs[sig]; sig++) if (!memcmp(table->signature, table_sigs[sig], 4)) break; if (!table_sigs[sig]) { pr_err("ACPI OVERRIDE: Unknown signature [%s%s]\n", cpio_path, file.name); continue; } if (file.size != table->length) { pr_err("ACPI OVERRIDE: File length does not match table length [%s%s]\n", cpio_path, file.name); continue; } if (acpi_table_checksum(file.data, table->length)) { pr_err("ACPI OVERRIDE: Bad table checksum [%s%s]\n", cpio_path, file.name); continue; } pr_info("%4.4s ACPI table found in initrd [%s%s][0x%x]\n", table->signature, cpio_path, file.name, table->length); all_tables_size += table->length; acpi_initrd_files[table_nr].data = file.data; acpi_initrd_files[table_nr].size = file.size; table_nr++; } if (table_nr == 0) return; if (get_securelevel() > 0) { pr_notice(PREFIX "securelevel enabled, ignoring table override\n"); return; } acpi_tables_addr = memblock_find_in_range(0, max_low_pfn_mapped << PAGE_SHIFT, all_tables_size, PAGE_SIZE); if (!acpi_tables_addr) { WARN_ON(1); return; } /* * Only calling e820_add_reserve does not work and the * tables are invalid (memory got used) later. * memblock_reserve works as expected and the tables won't get modified. * But it's not enough on X86 because ioremap will * complain later (used by acpi_os_map_memory) that the pages * that should get mapped are not marked "reserved". * Both memblock_reserve and e820_add_region (via arch_reserve_mem_area) * works fine. */ memblock_reserve(acpi_tables_addr, all_tables_size); arch_reserve_mem_area(acpi_tables_addr, all_tables_size); /* * early_ioremap only can remap 256k one time. If we map all * tables one time, we will hit the limit. Need to map chunks * one by one during copying the same as that in relocate_initrd(). */ for (no = 0; no < table_nr; no++) { unsigned char *src_p = acpi_initrd_files[no].data; phys_addr_t size = acpi_initrd_files[no].size; phys_addr_t dest_addr = acpi_tables_addr + total_offset; phys_addr_t slop, clen; char *dest_p; total_offset += size; while (size) { slop = dest_addr & ~PAGE_MASK; clen = size; if (clen > MAP_CHUNK_SIZE - slop) clen = MAP_CHUNK_SIZE - slop; dest_p = early_ioremap(dest_addr & PAGE_MASK, clen + slop); memcpy(dest_p + slop, src_p, clen); early_iounmap(dest_p, clen + slop); src_p += clen; dest_addr += clen; size -= clen; } } }
167,347
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); }
167,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } Commit Message: ... CWE ID: CWE-754
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); }
167,812
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GLboolean WebGL2RenderingContextBase::isTransformFeedback( WebGLTransformFeedback* feedback) { if (isContextLost() || !feedback) return 0; if (!feedback->HasEverBeenBound()) return 0; return ContextGL()->IsTransformFeedback(feedback->Object()); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <kainino@chromium.org> Reviewed-by: Antoine Labour <piman@chromium.org> Commit-Queue: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#565016} CWE ID: CWE-119
GLboolean WebGL2RenderingContextBase::isTransformFeedback( WebGLTransformFeedback* feedback) { if (isContextLost() || !feedback || !feedback->Validate(ContextGroup(), this)) return 0; if (!feedback->HasEverBeenBound()) return 0; return ContextGL()->IsTransformFeedback(feedback->Object()); }
173,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu) CWE ID: CWE-119
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1); (void) SetImageType(image,BilevelType); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); }
168,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FormAssociatedElement::formRemovedFromTree(const Node* formRoot) { ASSERT(m_form); if (toHTMLElement(this)->highestAncestor() != formRoot) setForm(0); } Commit Message: Fix a crash when a form control is in a past naems map of a demoted form element. Note that we wanted to add the protector in FormAssociatedElement::setForm(), but we couldn't do it because it is called from the constructor. BUG=326854 TEST=automated. Review URL: https://codereview.chromium.org/105693013 git-svn-id: svn://svn.chromium.org/blink/trunk@163680 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-287
void FormAssociatedElement::formRemovedFromTree(const Node* formRoot) { ASSERT(m_form); if (toHTMLElement(this)->highestAncestor() == formRoot) return; RefPtr<HTMLElement> protector(toHTMLElement(this)); setForm(0); }
171,718
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: avio_seek(s->pb, current_pos, SEEK_SET); return ret; } Commit Message: avformat/asfdec: Fix DoS in asf_build_simple_index() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-399
static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (avio_feof(s->pb)) { ret = AVERROR_INVALIDDATA; goto end; } if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: avio_seek(s->pb, current_pos, SEEK_SET); return ret; }
167,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char* Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) //should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len+1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
int Track::Info::CopyStr(char* Info::*str, Info& dst_) const if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len + 1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; }
174,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_object( cJSON *item, int depth, int fmt ) { char **entries = 0, **names = 0; char *out = 0, *ptr, *ret, *str; int len = 7, i = 0, j; cJSON *child = item->child; int numentries = 0, fail = 0; /* Count the number of entries. */ while ( child ) { ++numentries; child = child->next; } /* Allocate space for the names and the objects. */ if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) return 0; if ( ! ( names = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) { cJSON_free( entries ); return 0; } memset( entries, 0, sizeof(char*) * numentries ); memset( names, 0, sizeof(char*) * numentries ); /* Collect all the results into our arrays. */ child = item->child; ++depth; if ( fmt ) len += depth; while ( child ) { names[i] = str = print_string_ptr( child->string ); entries[i++] = ret = print_value( child, depth, fmt ); if ( str && ret ) len += strlen( ret ) + strlen( str ) + 2 + ( fmt ? 2 + depth : 0 ); else fail = 1; child = child->next; } /* Try to allocate the output string. */ if ( ! fail ) { out = (char*) cJSON_malloc( len ); if ( ! out ) fail = 1; } /* Handle failure. */ if ( fail ) { for ( i = 0; i < numentries; ++i ) { if ( names[i] ) cJSON_free( names[i] ); if ( entries[i] ) cJSON_free( entries[i] ); } cJSON_free( names ); cJSON_free( entries ); return 0; } /* Compose the output. */ *out = '{'; ptr = out + 1; if ( fmt ) *ptr++ = '\n'; *ptr = 0; for ( i = 0; i < numentries; ++i ) { if ( fmt ) for ( j = 0; j < depth; ++j ) *ptr++ = '\t'; strcpy( ptr, names[i] ); ptr += strlen( names[i] ); *ptr++ = ':'; if ( fmt ) *ptr++ = '\t'; strcpy( ptr, entries[i] ); ptr += strlen( entries[i] ); if ( i != numentries - 1 ) *ptr++ = ','; if ( fmt ) *ptr++ = '\n'; *ptr = 0; cJSON_free( names[i] ); cJSON_free( entries[i] ); } cJSON_free( names ); cJSON_free( entries ); if ( fmt ) for ( i = 0; i < depth - 1; ++i ) *ptr++ = '\t'; *ptr++ = '}'; *ptr++ = 0; return out; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
static char *print_object( cJSON *item, int depth, int fmt ) static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p) { char **entries=0,**names=0; char *out=0,*ptr,*ret,*str;int len=7,i=0,j; cJSON *child=item->child; int numentries=0,fail=0; size_t tmplen=0; /* Count the number of entries. */ while (child) numentries++,child=child->next; /* Explicitly handle empty object case */ if (!numentries) { if (p) out=ensure(p,fmt?depth+4:3); else out=(char*)cJSON_malloc(fmt?depth+4:3); if (!out) return 0; ptr=out;*ptr++='{'; if (fmt) {*ptr++='\n';for (i=0;i<depth;i++) *ptr++='\t';} *ptr++='}';*ptr++=0; return out; } if (p) { /* Compose the output: */ i=p->offset; len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0; *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len; child=item->child;depth++; while (child) { if (fmt) { ptr=ensure(p,depth); if (!ptr) return 0; for (j=0;j<depth;j++) *ptr++='\t'; p->offset+=depth; } print_string_ptr(child->string,p); p->offset=update(p); len=fmt?2:1; ptr=ensure(p,len); if (!ptr) return 0; *ptr++=':';if (fmt) *ptr++='\t'; p->offset+=len; print_value(child,depth,fmt,p); p->offset=update(p); len=(fmt?1:0)+(child->next?1:0); ptr=ensure(p,len+1); if (!ptr) return 0; if (child->next) *ptr++=','; if (fmt) *ptr++='\n';*ptr=0; p->offset+=len; child=child->next; } ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0; if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t'; *ptr++='}';*ptr=0; out=(p->buffer)+i; } else { /* Allocate space for the names and the objects */ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!entries) return 0; names=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!names) {cJSON_free(entries);return 0;} memset(entries,0,sizeof(char*)*numentries); memset(names,0,sizeof(char*)*numentries); /* Collect all the results into our arrays: */ child=item->child;depth++;if (fmt) len+=depth; while (child && !fail) { names[i]=str=print_string_ptr(child->string,0); entries[i++]=ret=print_value(child,depth,fmt,0); if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; child=child->next; } /* Try to allocate the output string */ if (!fail) out=(char*)cJSON_malloc(len); if (!out) fail=1; /* Handle failure */ if (fail) { for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);} cJSON_free(names);cJSON_free(entries); return 0; } /* Compose the output: */ *out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0; for (i=0;i<numentries;i++) { if (fmt) for (j=0;j<depth;j++) *ptr++='\t'; tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen; *ptr++=':';if (fmt) *ptr++='\t'; strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if (i!=numentries-1) *ptr++=','; if (fmt) *ptr++='\n';*ptr=0; cJSON_free(names[i]);cJSON_free(entries[i]); } cJSON_free(names);cJSON_free(entries); if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t'; *ptr++='}';*ptr++=0; } return out; }
167,308
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; }
168,441
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator( media::VideoDecodeAccelerator::Client* client, base::ProcessHandle renderer_process) : client_(client), egl_config_(NULL), state_(kUninitialized), pictures_requested_(false), renderer_process_(renderer_process), last_input_buffer_id_(-1), inputs_before_decode_(0) { memset(&input_stream_info_, 0, sizeof(input_stream_info_)); memset(&output_stream_info_, 0, sizeof(output_stream_info_)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator( media::VideoDecodeAccelerator::Client* client) : client_(client), egl_config_(NULL), state_(kUninitialized), pictures_requested_(false), last_input_buffer_id_(-1), inputs_before_decode_(0) { memset(&input_stream_info_, 0, sizeof(input_stream_info_)); memset(&output_stream_info_, 0, sizeof(output_stream_info_)); }
170,940
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void array_cleanup( char* arr[] , int arr_size) { int i=0; for( i=0; i< arr_size; i++ ){ if( arr[i*2] ){ efree( arr[i*2]); } } efree(arr); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static void array_cleanup( char* arr[] , int arr_size) { int i=0; for( i=0; i< arr_size; i++ ){ if( arr[i*2] ){ efree( arr[i*2]); } } efree(arr); }
167,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool __net_get_random_once(void *buf, int nbytes, bool *done, struct static_key *done_key) { static DEFINE_SPINLOCK(lock); unsigned long flags; spin_lock_irqsave(&lock, flags); if (*done) { spin_unlock_irqrestore(&lock, flags); return false; } get_random_bytes(buf, nbytes); *done = true; spin_unlock_irqrestore(&lock, flags); __net_random_once_disable_jump(done_key); return true; } Commit Message: net: avoid dependency of net_get_random_once on nop patching net_get_random_once depends on the static keys infrastructure to patch up the branch to the slow path during boot. This was realized by abusing the static keys api and defining a new initializer to not enable the call site while still indicating that the branch point should get patched up. This was needed to have the fast path considered likely by gcc. The static key initialization during boot up normally walks through all the registered keys and either patches in ideal nops or enables the jump site but omitted that step on x86 if ideal nops where already placed at static_key branch points. Thus net_get_random_once branches not always became active. This patch switches net_get_random_once to the ordinary static_key api and thus places the kernel fast path in the - by gcc considered - unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that the unlikely path actually beats the likely path in terms of cycle cost and that different nop patterns did not make much difference, thus this switch should not be noticeable. Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once") Reported-by: Tuomas Räsänen <tuomasjjrasanen@tjjr.fi> Cc: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
bool __net_get_random_once(void *buf, int nbytes, bool *done, struct static_key *once_key) { static DEFINE_SPINLOCK(lock); unsigned long flags; spin_lock_irqsave(&lock, flags); if (*done) { spin_unlock_irqrestore(&lock, flags); return false; } get_random_bytes(buf, nbytes); *done = true; spin_unlock_irqrestore(&lock, flags); __net_random_once_disable_jump(once_key); return true; }
166,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { if (requested_pos < 0) return 0; Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { if (requested_pos < 0) return 0; Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); if (pCluster == NULL) return NULL; const ptrdiff_t idx = i - m_clusters; if (!PreloadCluster(pCluster, idx)) { delete pCluster; return NULL; } assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; }
173,812
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 TBR=apatrick@chromium.org Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void AddExpectationsForSimulatedAttrib0( void AddExpectationsForSimulatedAttrib0WithError( GLsizei num_vertices, GLuint buffer_id, GLenum error) { if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) { return; } EXPECT_CALL(*gl_, GetError()) .WillOnce(Return(GL_NO_ERROR)) .WillOnce(Return(error)) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); if (error == GL_NO_ERROR) { EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } } void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { AddExpectationsForSimulatedAttrib0WithError( num_vertices, buffer_id, GL_NO_ERROR); }
170,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_DeleteItemFromArray( cJSON *array, int which ) { cJSON_Delete( cJSON_DetachItemFromArray( array, which ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_DeleteItemFromArray( cJSON *array, int which )
167,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int http_read_stream(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int err, new_location, read_ret; int64_t seek_ret; if (!s->hd) return AVERROR_EOF; if (s->end_chunked_post && !s->end_header) { err = http_read_header(h, &new_location); if (err < 0) return err; } if (s->chunksize >= 0) { if (!s->chunksize) { char line[32]; do { if ((err = http_get_line(s, line, sizeof(line))) < 0) return err; } while (!*line); /* skip CR LF from last chunk */ s->chunksize = strtoll(line, NULL, 16); av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n", s->chunksize); if (!s->chunksize) return 0; } size = FFMIN(size, s->chunksize); } #if CONFIG_ZLIB if (s->compressed) return http_buf_read_compressed(h, buf, size); #endif /* CONFIG_ZLIB */ read_ret = http_buf_read(h, buf, size); if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize) || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) { int64_t target = h->is_streamed ? 0 : s->off; if (s->reconnect_delay > s->reconnect_delay_max) return AVERROR(EIO); av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64" error=%s.\n", s->off, av_err2str(read_ret)); av_usleep(1000U*1000*s->reconnect_delay); s->reconnect_delay = 1 + 2*s->reconnect_delay; seek_ret = http_seek_internal(h, target, SEEK_SET, 1); if (seek_ret != target) { av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", target); return read_ret; } read_ret = http_buf_read(h, buf, size); } else s->reconnect_delay = 0; return read_ret; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>. CWE ID: CWE-119
static int http_read_stream(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int err, new_location, read_ret; int64_t seek_ret; if (!s->hd) return AVERROR_EOF; if (s->end_chunked_post && !s->end_header) { err = http_read_header(h, &new_location); if (err < 0) return err; } if (s->chunksize != UINT64_MAX) { if (!s->chunksize) { char line[32]; do { if ((err = http_get_line(s, line, sizeof(line))) < 0) return err; } while (!*line); /* skip CR LF from last chunk */ s->chunksize = strtoull(line, NULL, 16); av_log(h, AV_LOG_TRACE, "Chunked encoding data size: %"PRIu64"'\n", s->chunksize); if (!s->chunksize) return 0; else if (s->chunksize == UINT64_MAX) { av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n", s->chunksize); return AVERROR(EINVAL); } } size = FFMIN(size, s->chunksize); } #if CONFIG_ZLIB if (s->compressed) return http_buf_read_compressed(h, buf, size); #endif /* CONFIG_ZLIB */ read_ret = http_buf_read(h, buf, size); if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize) || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) { uint64_t target = h->is_streamed ? 0 : s->off; if (s->reconnect_delay > s->reconnect_delay_max) return AVERROR(EIO); av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret)); av_usleep(1000U*1000*s->reconnect_delay); s->reconnect_delay = 1 + 2*s->reconnect_delay; seek_ret = http_seek_internal(h, target, SEEK_SET, 1); if (seek_ret != target) { av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target); return read_ret; } read_ret = http_buf_read(h, buf, size); } else s->reconnect_delay = 0; return read_ret; }
168,501
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image) { pdf_gstate *gstate = pr->gstate + pr->gtop; fz_matrix image_ctm; fz_rect bbox; softmask_save softmask = { NULL }; if (pr->super.hidden) return; break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); bbox = fz_unit_rect; fz_transform_rect(&bbox, &image_ctm); if (image->mask) { /* apply blend group even though we skip the soft mask */ if (gstate->blendmode) fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1); fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); } else gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (!image->colorspace) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_image_mask(ctx, pr->dev, image, &image_ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } else { fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params); } if (image->mask) { fz_pop_clip(ctx, pr->dev); if (gstate->blendmode) fz_end_group(ctx, pr->dev); } else pdf_end_group(ctx, pr, &softmask); } static void if (pr->clip) { gstate->clip_depth++; fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox); pr->clip = 0; } if (pr->super.hidden) dostroke = dofill = 0; if (dofill || dostroke) gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (dofill && dostroke) { /* We may need to push a knockout group */ if (gstate->stroke.alpha == 0) { /* No need for group, as stroke won't do anything */ } else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL) { /* No need for group, as stroke won't show up */ } else { knockout_group = 1; fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1); } } if (dofill) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); /* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */ fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (dostroke) { switch (gstate->stroke.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params); break; case PDF_MAT_PATTERN: if (gstate->stroke.pattern) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->stroke.shade) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (knockout_group) fz_end_group(ctx, pr->dev); if (dofill || dostroke) pdf_end_group(ctx, pr, &softmask); } Commit Message: CWE ID: CWE-20
pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image) { pdf_gstate *gstate = pr->gstate + pr->gtop; fz_matrix image_ctm; fz_rect bbox; if (pr->super.hidden) return; break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); bbox = fz_unit_rect; fz_transform_rect(&bbox, &image_ctm); if (image->mask && gstate->blendmode) { /* apply blend group even though we skip the soft mask */ fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1); fz_try(ctx) fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); fz_catch(ctx) { fz_end_group(ctx, pr->dev); fz_rethrow(ctx); } fz_try(ctx) pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox); fz_always(ctx) { fz_pop_clip(ctx, pr->dev); fz_end_group(ctx, pr->dev); } fz_catch(ctx) fz_rethrow(ctx); } else if (image->mask) { fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); fz_try(ctx) pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox); fz_always(ctx) fz_pop_clip(ctx, pr->dev); fz_catch(ctx) fz_rethrow(ctx); } else { softmask_save softmask = { NULL }; gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); fz_try(ctx) pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox); fz_always(ctx) pdf_end_group(ctx, pr, &softmask); fz_catch(ctx) fz_rethrow(ctx); } } static void if (pr->clip) { gstate->clip_depth++; fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox); pr->clip = 0; } if (pr->super.hidden) dostroke = dofill = 0; if (dofill || dostroke) gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (dofill && dostroke) { /* We may need to push a knockout group */ if (gstate->stroke.alpha == 0) { /* No need for group, as stroke won't do anything */ } else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL) { /* No need for group, as stroke won't show up */ } else { knockout_group = 1; fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1); } } if (dofill) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); /* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */ fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (dostroke) { switch (gstate->stroke.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params); break; case PDF_MAT_PATTERN: if (gstate->stroke.pattern) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->stroke.shade) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (knockout_group) fz_end_group(ctx, pr->dev); if (dofill || dostroke) pdf_end_group(ctx, pr, &softmask); }
164,580
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcXFixesCopyRegion(ClientPtr client) { RegionPtr pSource, pDestination; REQUEST(xXFixesCopyRegionReq); VERIFY_REGION(pSource, stuff->source, client, DixReadAccess); VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess); if (!RegionCopy(pDestination, pSource)) return BadAlloc; return Success; } Commit Message: CWE ID: CWE-20
ProcXFixesCopyRegion(ClientPtr client) { RegionPtr pSource, pDestination; REQUEST(xXFixesCopyRegionReq); REQUEST_SIZE_MATCH(xXFixesCopyRegionReq); VERIFY_REGION(pSource, stuff->source, client, DixReadAccess); VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess); if (!RegionCopy(pDestination, pSource)) return BadAlloc; return Success; }
165,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void coroutine_fn v9fs_write(void *opaque) { ssize_t err; int32_t fid; uint64_t off; uint32_t count; int32_t len = 0; int32_t total = 0; size_t offset = 7; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; QEMUIOVector qiov_full; QEMUIOVector qiov; err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count); if (err < 0) { pdu_complete(pdu, err); return; } offset += err; v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true); trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (fidp->fid_type == P9_FID_FILE) { if (fidp->fs.fd == -1) { err = -EINVAL; goto out; } } else if (fidp->fid_type == P9_FID_XATTR) { /* * setxattr operation */ err = v9fs_xattr_write(s, pdu, fidp, off, count, qiov_full.iov, qiov_full.niov); goto out; } else { err = -EINVAL; goto out; } qemu_iovec_init(&qiov, qiov_full.niov); do { qemu_iovec_reset(&qiov); qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total); if (0) { print_sg(qiov.iov, qiov.niov); } /* Loop in case of EINTR */ do { len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off); if (len >= 0) { off += len; total += len; } } while (len == -EINTR && !pdu->cancelled); if (len < 0) { /* IO error return the error */ err = len; goto out_qiov; } } while (total < count && len > 0); offset = 7; err = pdu_marshal(pdu, offset, "d", total); if (err < 0) { goto out; } err += offset; trace_v9fs_write_return(pdu->tag, pdu->id, total, err); out_qiov: qemu_iovec_destroy(&qiov); out: put_fid(pdu, fidp); out_nofid: qemu_iovec_destroy(&qiov_full); pdu_complete(pdu, err); } Commit Message: CWE ID: CWE-399
static void coroutine_fn v9fs_write(void *opaque) { ssize_t err; int32_t fid; uint64_t off; uint32_t count; int32_t len = 0; int32_t total = 0; size_t offset = 7; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; QEMUIOVector qiov_full; QEMUIOVector qiov; err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count); if (err < 0) { pdu_complete(pdu, err); return; } offset += err; v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true); trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (fidp->fid_type == P9_FID_FILE) { if (fidp->fs.fd == -1) { err = -EINVAL; goto out; } } else if (fidp->fid_type == P9_FID_XATTR) { /* * setxattr operation */ err = v9fs_xattr_write(s, pdu, fidp, off, count, qiov_full.iov, qiov_full.niov); goto out; } else { err = -EINVAL; goto out; } qemu_iovec_init(&qiov, qiov_full.niov); do { qemu_iovec_reset(&qiov); qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total); if (0) { print_sg(qiov.iov, qiov.niov); } /* Loop in case of EINTR */ do { len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off); if (len >= 0) { off += len; total += len; } } while (len == -EINTR && !pdu->cancelled); if (len < 0) { /* IO error return the error */ err = len; goto out_qiov; } } while (total < count && len > 0); offset = 7; err = pdu_marshal(pdu, offset, "d", total); if (err < 0) { goto out_qiov; } err += offset; trace_v9fs_write_return(pdu->tag, pdu->id, total, err); out_qiov: qemu_iovec_destroy(&qiov); out: put_fid(pdu, fidp); out_nofid: qemu_iovec_destroy(&qiov_full); pdu_complete(pdu, err); }
164,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1586 CWE ID: CWE-119
static PixelChannels **AcquirePixelThreadSet(const Image *image) static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
170,205
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); }
173,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). CWE ID: CWE-119
int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; }
168,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int x509_crt_verify_child( mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, int path_cnt, int self_cnt, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; uint32_t parent_flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; mbedtls_x509_crt *grandparent; const mbedtls_md_info_t *md_info; /* Counting intermediate self signed certificates */ if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) self_cnt++; /* path_cnt is 0 for the first intermediate CA */ if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); } if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; md_info = mbedtls_md_info_from_type( child->sig_md ); if( md_info == NULL ) { /* * Cannot check 'unknown' hash */ *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } else { mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, mbedtls_md_get_size( md_info ), child->sig.p, child->sig.len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } } #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); #endif /* Look for a grandparent in trusted CAs */ for( grandparent = trust_ca; grandparent != NULL; grandparent = grandparent->next ) { if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } if( grandparent != NULL ) { ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { /* Look for a grandparent upwards the chain */ for( grandparent = parent->next; grandparent != NULL; grandparent = grandparent->next ) { /* +2 because the current step is not yet accounted for * and because max_pathlen is one higher than it should be. * Also self signed certificates do not count to the limit. */ if( grandparent->max_pathlen > 0 && grandparent->max_pathlen < 2 + path_cnt - self_cnt ) { continue; } if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } /* Is our parent part of the chain or at the top? */ if( grandparent != NULL ) { ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } } /* child is verified to be a child of the parent, call verify callback */ if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); *flags |= parent_flags; return( 0 ); } Commit Message: Only return VERIFY_FAILED from a single point Everything else is a fatal error. Also improve documentation about that for the vrfy callback. CWE ID: CWE-287
static int x509_crt_verify_child( mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, int path_cnt, int self_cnt, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; uint32_t parent_flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; mbedtls_x509_crt *grandparent; const mbedtls_md_info_t *md_info; /* Counting intermediate self signed certificates */ if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) self_cnt++; /* path_cnt is 0 for the first intermediate CA */ if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { /* return immediately as the goal is to avoid unbounded recursion */ return( MBEDTLS_ERR_X509_FATAL_ERROR ); } if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; md_info = mbedtls_md_info_from_type( child->sig_md ); if( md_info == NULL ) { /* * Cannot check 'unknown' hash */ *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } else { mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, mbedtls_md_get_size( md_info ), child->sig.p, child->sig.len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } } #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); #endif /* Look for a grandparent in trusted CAs */ for( grandparent = trust_ca; grandparent != NULL; grandparent = grandparent->next ) { if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } if( grandparent != NULL ) { ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { /* Look for a grandparent upwards the chain */ for( grandparent = parent->next; grandparent != NULL; grandparent = grandparent->next ) { /* +2 because the current step is not yet accounted for * and because max_pathlen is one higher than it should be. * Also self signed certificates do not count to the limit. */ if( grandparent->max_pathlen > 0 && grandparent->max_pathlen < 2 + path_cnt - self_cnt ) { continue; } if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } /* Is our parent part of the chain or at the top? */ if( grandparent != NULL ) { ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } } /* child is verified to be a child of the parent, call verify callback */ if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); *flags |= parent_flags; return( 0 ); }
170,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppListControllerDelegate::DoShowAppInfoFlow( Profile* profile, const std::string& extension_id) { DCHECK(CanDoShowAppInfoFlow()); ExtensionService* service = extensions::ExtensionSystem::Get(profile)->extension_service(); DCHECK(service); const extensions::Extension* extension = service->GetInstalledExtension( extension_id); DCHECK(extension); OnShowChildDialog(); UMA_HISTOGRAM_ENUMERATION("Apps.AppInfoDialog.Launches", AppInfoLaunchSource::FROM_APP_LIST, AppInfoLaunchSource::NUM_LAUNCH_SOURCES); ShowAppInfoInAppList( GetAppListWindow(), GetAppListBounds(), profile, extension, base::Bind(&AppListControllerDelegate::OnCloseChildDialog, base::Unretained(this))); } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
void AppListControllerDelegate::DoShowAppInfoFlow( Profile* profile, const std::string& extension_id) { DCHECK(CanDoShowAppInfoFlow()); const extensions::Extension* extension = GetExtension(profile, extension_id); DCHECK(extension); OnShowChildDialog(); UMA_HISTOGRAM_ENUMERATION("Apps.AppInfoDialog.Launches", AppInfoLaunchSource::FROM_APP_LIST, AppInfoLaunchSource::NUM_LAUNCH_SOURCES); ShowAppInfoInAppList( GetAppListWindow(), GetAppListBounds(), profile, extension, base::Bind(&AppListControllerDelegate::OnCloseChildDialog, base::Unretained(this))); }
171,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void impeg2d_dec_pic_data_thread(dec_state_t *ps_dec) { WORD32 i4_continue_decode; WORD32 i4_cur_row, temp; UWORD32 u4_bits_read; WORD32 i4_dequeue_job; IMPEG2D_ERROR_CODES_T e_error; i4_cur_row = ps_dec->u2_mb_y + 1; i4_continue_decode = 1; i4_dequeue_job = 1; do { if(i4_cur_row > ps_dec->u2_num_vert_mb) { i4_continue_decode = 0; break; } { if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job)) { job_t s_job; IV_API_CALL_STATUS_T e_ret; UWORD8 *pu1_buf; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_PROCESS == s_job.i4_cmd) { pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst; impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf, (ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8); i4_cur_row = s_job.i2_start_mb_y; ps_dec->i4_start_mb_y = s_job.i2_start_mb_y; ps_dec->i4_end_mb_y = s_job.i2_end_mb_y; ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y = ps_dec->i4_start_mb_y; ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb; } else { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); break; } } e_error = impeg2d_dec_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { impeg2d_next_start_code(ps_dec); } } /* Detecting next slice start code */ while(1) { u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN); temp = u4_bits_read & 0xFF; i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF)); if(i4_continue_decode) { /* If the slice is from the same row, then continue decoding without dequeue */ if((temp - 1) == i4_cur_row) { i4_dequeue_job = 0; break; } if(temp < ps_dec->i4_end_mb_y) { i4_cur_row = ps_dec->u2_mb_y; } else { i4_dequeue_job = 1; } break; } else break; } }while(i4_continue_decode); if(ps_dec->i4_num_cores > 1) { while(1) { job_t s_job; IV_API_CALL_STATUS_T e_ret; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_FMTCONV == s_job.i4_cmd) { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); } } } else { if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat))) impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, 0, ps_dec->u2_vertical_size); } } Commit Message: Fix for handling streams which resulted in negative num_mbs_left Bug: 26070014 Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f CWE ID: CWE-119
void impeg2d_dec_pic_data_thread(dec_state_t *ps_dec) { WORD32 i4_continue_decode; WORD32 i4_cur_row, temp; UWORD32 u4_bits_read; WORD32 i4_dequeue_job; IMPEG2D_ERROR_CODES_T e_error; i4_cur_row = ps_dec->u2_mb_y + 1; i4_continue_decode = 1; i4_dequeue_job = 1; do { if(i4_cur_row > ps_dec->u2_num_vert_mb) { i4_continue_decode = 0; break; } { if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job)) { job_t s_job; IV_API_CALL_STATUS_T e_ret; UWORD8 *pu1_buf; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_PROCESS == s_job.i4_cmd) { pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst; impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf, (ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8); i4_cur_row = s_job.i2_start_mb_y; ps_dec->i4_start_mb_y = s_job.i2_start_mb_y; ps_dec->i4_end_mb_y = s_job.i2_end_mb_y; ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y = ps_dec->i4_start_mb_y; ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb; } else { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); break; } } e_error = impeg2d_dec_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { impeg2d_next_start_code(ps_dec); } } /* Detecting next slice start code */ while(1) { u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN); temp = u4_bits_read & 0xFF; i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF)); if (1 == ps_dec->i4_num_cores && 0 == ps_dec->u2_num_mbs_left) { i4_continue_decode = 0; android_errorWriteLog(0x534e4554, "26070014"); } if(i4_continue_decode) { /* If the slice is from the same row, then continue decoding without dequeue */ if((temp - 1) == i4_cur_row) { i4_dequeue_job = 0; break; } if(temp < ps_dec->i4_end_mb_y) { i4_cur_row = ps_dec->u2_mb_y; } else { i4_dequeue_job = 1; } break; } else break; } }while(i4_continue_decode); if(ps_dec->i4_num_cores > 1) { while(1) { job_t s_job; IV_API_CALL_STATUS_T e_ret; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_FMTCONV == s_job.i4_cmd) { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); } } } else { if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat))) impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, 0, ps_dec->u2_vertical_size); } }
173,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gfx::Size ShellWindowFrameView::GetMaximumSize() { gfx::Size max_size = frame_->client_view()->GetMaximumSize(); if (!max_size.IsEmpty()) { gfx::Rect client_bounds = GetBoundsForClientView(); max_size.Enlarge(0, client_bounds.y()); } return max_size; } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 R=ben@chromium.org Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
gfx::Size ShellWindowFrameView::GetMaximumSize() { gfx::Size max_size = frame_->client_view()->GetMaximumSize(); if (is_frameless_) return max_size; if (!max_size.IsEmpty()) { gfx::Rect client_bounds = GetBoundsForClientView(); max_size.Enlarge(0, client_bounds.y()); } return max_size; }
170,712
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char16_t* cur_utf16 = src; const char16_t* const end_utf16 = src + src_len; char *cur = dst; while (cur_utf16 < end_utf16) { char32_t utf32; if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) { utf32 = (*cur_utf16++ - 0xD800) << 10; utf32 |= *cur_utf16++ - 0xDC00; utf32 += 0x10000; } else { utf32 = (char32_t) *cur_utf16++; } const size_t len = utf32_codepoint_utf8_length(utf32); utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len); cur += len; } *cur = '\0'; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst) void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char16_t* cur_utf16 = src; const char16_t* const end_utf16 = src + src_len; char *cur = dst; while (cur_utf16 < end_utf16) { char32_t utf32; if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) { utf32 = (*cur_utf16++ - 0xD800) << 10; utf32 |= *cur_utf16++ - 0xDC00; utf32 += 0x10000; } else { utf32 = (char32_t) *cur_utf16++; } const size_t len = utf32_codepoint_utf8_length(utf32); LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len); utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len); cur += len; dst_len -= len; } LOG_ALWAYS_FATAL_IF(dst_len < 1, "%zu < 1", dst_len); *cur = '\0'; }
173,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) { ui::Texture* container = image_transport_clients_[surface_id]; DCHECK(container); if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME || can_lock_compositor_ == NO_PENDING_COMMIT || resize_locks_.empty()) return false; gfx::Size container_size = ConvertSizeToDIP(this, container->size()); ResizeLockList::iterator it = resize_locks_.begin(); while (it != resize_locks_.end()) { if ((*it)->expected_size() == container_size) break; ++it; } return it == resize_locks_.end() || ++it != resize_locks_.end(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) { bool RenderWidgetHostViewAura::ShouldSkipFrame(const gfx::Size& size) { if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME || can_lock_compositor_ == NO_PENDING_COMMIT || resize_locks_.empty()) return false; gfx::Size container_size = ConvertSizeToDIP(this, size); ResizeLockList::iterator it = resize_locks_.begin(); while (it != resize_locks_.end()) { if ((*it)->expected_size() == container_size) break; ++it; } return it == resize_locks_.end() || ++it != resize_locks_.end(); }
171,386
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IPV6BuildTestPacket(uint32_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; uint8_t *pcontent; IPV6Hdr ip6h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip6h.s_ip6_nxt = 44; ip6h.s_ip6_hlim = 2; /* Source and dest address - very bogus addresses. */ ip6h.s_ip6_src[0] = 0x01010101; ip6h.s_ip6_src[1] = 0x01010101; ip6h.s_ip6_src[2] = 0x01010101; ip6h.s_ip6_src[3] = 0x01010101; ip6h.s_ip6_dst[0] = 0x02020202; ip6h.s_ip6_dst[1] = 0x02020202; ip6h.s_ip6_dst[2] = 0x02020202; ip6h.s_ip6_dst[3] = 0x02020202; /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip6h, sizeof(IPV6Hdr)); p->ip6h = (IPV6Hdr *)GET_PKT_DATA(p); IPV6_SET_RAW_VER(p->ip6h, 6); /* Fragmentation header. */ IPV6FragHdr *fh = (IPV6FragHdr *)(GET_PKT_DATA(p) + sizeof(IPV6Hdr)); fh->ip6fh_nxt = IPPROTO_ICMP; fh->ip6fh_ident = htonl(id); fh->ip6fh_offlg = htons((off << 3) | mf); DecodeIPV6FragHeader(p, (uint8_t *)fh, 8, 8 + content_len, 0); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr), pcontent, content_len); SET_PKT_LEN(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr) + content_len); SCFree(pcontent); p->ip6h->s_ip6_plen = htons(sizeof(IPV6FragHdr) + content_len); SET_IPV6_SRC_ADDR(p, &p->src); SET_IPV6_DST_ADDR(p, &p->dst); /* Self test. */ if (IPV6_GET_VER(p) != 6) goto error; if (IPV6_GET_NH(p) != 44) goto error; if (IPV6_GET_PLEN(p) != sizeof(IPV6FragHdr) + content_len) goto error; return p; error: fprintf(stderr, "Error building test packet.\n"); if (p != NULL) SCFree(p); return NULL; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
IPV6BuildTestPacket(uint32_t id, uint16_t off, int mf, const char content, IPV6BuildTestPacket(uint8_t proto, uint32_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; uint8_t *pcontent; IPV6Hdr ip6h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip6h.s_ip6_nxt = 44; ip6h.s_ip6_hlim = 2; /* Source and dest address - very bogus addresses. */ ip6h.s_ip6_src[0] = 0x01010101; ip6h.s_ip6_src[1] = 0x01010101; ip6h.s_ip6_src[2] = 0x01010101; ip6h.s_ip6_src[3] = 0x01010101; ip6h.s_ip6_dst[0] = 0x02020202; ip6h.s_ip6_dst[1] = 0x02020202; ip6h.s_ip6_dst[2] = 0x02020202; ip6h.s_ip6_dst[3] = 0x02020202; /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip6h, sizeof(IPV6Hdr)); p->ip6h = (IPV6Hdr *)GET_PKT_DATA(p); IPV6_SET_RAW_VER(p->ip6h, 6); /* Fragmentation header. */ IPV6FragHdr *fh = (IPV6FragHdr *)(GET_PKT_DATA(p) + sizeof(IPV6Hdr)); fh->ip6fh_nxt = proto; fh->ip6fh_ident = htonl(id); fh->ip6fh_offlg = htons((off << 3) | mf); DecodeIPV6FragHeader(p, (uint8_t *)fh, 8, 8 + content_len, 0); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr), pcontent, content_len); SET_PKT_LEN(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr) + content_len); SCFree(pcontent); p->ip6h->s_ip6_plen = htons(sizeof(IPV6FragHdr) + content_len); SET_IPV6_SRC_ADDR(p, &p->src); SET_IPV6_DST_ADDR(p, &p->dst); /* Self test. */ if (IPV6_GET_VER(p) != 6) goto error; if (IPV6_GET_NH(p) != 44) goto error; if (IPV6_GET_PLEN(p) != sizeof(IPV6FragHdr) + content_len) goto error; return p; error: fprintf(stderr, "Error building test packet.\n"); if (p != NULL) SCFree(p); return NULL; }
168,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool inode_capable(const struct inode *inode, int cap) { struct user_namespace *ns = current_user_ns(); return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid); } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <tytso@mit.edu> Cc: Serge Hallyn <serge.hallyn@ubuntu.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Dave Chinner <david@fromorbit.com> Cc: stable@vger.kernel.org Signed-off-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
bool inode_capable(const struct inode *inode, int cap) bool capable_wrt_inode_uidgid(const struct inode *inode, int cap) { struct user_namespace *ns = current_user_ns(); return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid) && kgid_has_mapping(ns, inode->i_gid); }
166,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _asn1_ltostr (long v, char *str) { long d, r; char temp[LTOSTR_MAX_SIZE]; int count, k, start; if (v < 0) { str[0] = '-'; start = 1; v = -v; } else start = 0; count = 0; do { d = v / 10; r = v - d * 10; temp[start + count] = '0' + (char) r; count++; v = d; } while (v); for (k = 0; k < count; k++) str[k + start] = temp[start + count - k - 1]; str[count + start] = 0; return str; } Commit Message: CWE ID: CWE-119
_asn1_ltostr (long v, char *str) _asn1_ltostr (long v, char str[LTOSTR_MAX_SIZE]) { long d, r; char temp[LTOSTR_MAX_SIZE]; int count, k, start; if (v < 0) { str[0] = '-'; start = 1; v = -v; } else start = 0; count = 0; do { d = v / 10; r = v - d * 10; temp[start + count] = '0' + (char) r; count++; v = d; } while (v && ((start+count) < LTOSTR_MAX_SIZE-1)); for (k = 0; k < count; k++) str[k + start] = temp[start + count - k - 1]; str[count + start] = 0; return str; }
164,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/ Commit Message: CWE ID: CWE-189
static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_NON_EXISTENT == zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/
164,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: media::AudioParameters GetDeviceParametersOnDeviceThread( media::AudioManager* audio_manager, const std::string& unique_id) { DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread()); return media::AudioDeviceDescription::IsDefaultDevice(unique_id) ? audio_manager->GetDefaultOutputStreamParameters() : audio_manager->GetOutputStreamParameters(unique_id); } 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:
media::AudioParameters GetDeviceParametersOnDeviceThread(
171,982
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (numrows < 0 || numcols < 0) { return 0; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; } Commit Message: Fixed an integer overflow problem. CWE ID: CWE-190
jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; size_t size; matrix = 0; if (numrows < 0 || numcols < 0) { goto error; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { goto error; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = 0; // matrix->datasize_ = numrows * numcols; if (!jas_safe_size_mul(numrows, numcols, &size)) { goto error; } matrix->datasize_ = size; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { goto error; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { goto error; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; error: if (matrix) { jas_matrix_destroy(matrix); } return 0; }
168,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pit_ioport_read(struct kvm_io_device *this, gpa_t addr, int len, void *data) { struct kvm_pit *pit = dev_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; int ret, count; struct kvm_kpit_channel_state *s; if (!pit_in_range(addr)) return -EOPNOTSUPP; addr &= KVM_PIT_CHANNEL_MASK; s = &pit_state->channels[addr]; mutex_lock(&pit_state->lock); if (s->status_latched) { s->status_latched = 0; ret = s->status; } else if (s->count_latched) { switch (s->count_latched) { default: case RW_STATE_LSB: ret = s->latched_count & 0xff; s->count_latched = 0; break; case RW_STATE_MSB: ret = s->latched_count >> 8; s->count_latched = 0; break; case RW_STATE_WORD0: ret = s->latched_count & 0xff; s->count_latched = RW_STATE_MSB; break; } } else { switch (s->read_state) { default: case RW_STATE_LSB: count = pit_get_count(kvm, addr); ret = count & 0xff; break; case RW_STATE_MSB: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; break; case RW_STATE_WORD0: count = pit_get_count(kvm, addr); ret = count & 0xff; s->read_state = RW_STATE_WORD1; break; case RW_STATE_WORD1: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; s->read_state = RW_STATE_WORD0; break; } } if (len > sizeof(ret)) len = sizeof(ret); memcpy(data, (char *)&ret, len); mutex_unlock(&pit_state->lock); return 0; } Commit Message: KVM: PIT: control word is write-only PIT control word (address 0x43) is write-only, reads are undefined. Cc: stable@kernel.org Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID: CWE-119
static int pit_ioport_read(struct kvm_io_device *this, gpa_t addr, int len, void *data) { struct kvm_pit *pit = dev_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; int ret, count; struct kvm_kpit_channel_state *s; if (!pit_in_range(addr)) return -EOPNOTSUPP; addr &= KVM_PIT_CHANNEL_MASK; if (addr == 3) return 0; s = &pit_state->channels[addr]; mutex_lock(&pit_state->lock); if (s->status_latched) { s->status_latched = 0; ret = s->status; } else if (s->count_latched) { switch (s->count_latched) { default: case RW_STATE_LSB: ret = s->latched_count & 0xff; s->count_latched = 0; break; case RW_STATE_MSB: ret = s->latched_count >> 8; s->count_latched = 0; break; case RW_STATE_WORD0: ret = s->latched_count & 0xff; s->count_latched = RW_STATE_MSB; break; } } else { switch (s->read_state) { default: case RW_STATE_LSB: count = pit_get_count(kvm, addr); ret = count & 0xff; break; case RW_STATE_MSB: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; break; case RW_STATE_WORD0: count = pit_get_count(kvm, addr); ret = count & 0xff; s->read_state = RW_STATE_WORD1; break; case RW_STATE_WORD1: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; s->read_state = RW_STATE_WORD0; break; } } if (len > sizeof(ret)) len = sizeof(ret); memcpy(data, (char *)&ret, len); mutex_unlock(&pit_state->lock); return 0; }
166,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::allocate_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = m_out_mem_ptr; for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer"); close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
OMX_ERRORTYPE omx_video::allocate_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = m_out_mem_ptr; for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = NULL; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer"); m_pOutput_pmem[i].buffer = NULL; close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); if (m_pOutput_pmem[i].buffer == NULL) { DEBUG_PRINT_ERROR("%s: Failed to allocate native-handle", __func__); return OMX_ErrorInsufficientResources; } (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; }
173,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; if (cnt < 0) { jas_deprecated("negative count for jas_stream_write"); } bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; }
168,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size) { ssize_t ret; guint watch; assert(qemu_in_coroutine()); /* Negotiation are always in main loop. */ watch = qio_channel_add_watch(ioc, G_IO_OUT, nbd_negotiate_continue, qemu_coroutine_self(), NULL); ret = nbd_write(ioc, buffer, size, NULL); g_source_remove(watch); return ret; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)
165,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces) { if (!element->isFrameOwnerElement()) return; HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element); Frame* frame = frameOwner->contentFrame(); if (!frame) return; KURL url = frame->document()->url(); if (url.isValid() && !url.isBlankURL()) return; url = m_serializer->urlForBlankFrame(frame); appendAttribute(result, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > R=abarth@chromium.org > > Review URL: https://codereview.chromium.org/68613003 TBR=tiger@opera.com Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces) void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, Element* element, Namespaces* namespaces) { if (!element->isFrameOwnerElement()) return; HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element); Frame* frame = frameOwner->contentFrame(); if (!frame) return; KURL url = frame->document()->url(); if (url.isValid() && !url.isBlankURL()) return; url = m_serializer->urlForBlankFrame(frame); appendAttribute(out, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces); }
171,566
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BGD_DECLARE(void) gdImageWebpEx (gdImagePtr im, FILE * outFile, int quality) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } gdImageWebpCtx(im, out, quality); out->gd_free(out); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to security@libgd.org. CVE-2016-6912 CWE ID: CWE-415
BGD_DECLARE(void) gdImageWebpEx (gdImagePtr im, FILE * outFile, int quality) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, quality); out->gd_free(out); }
168,818
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void die(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); if(fmt[strlen(fmt)-1] != '\n') printf("\n"); exit(EXIT_FAILURE); } 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
static void die(const char *fmt, ...) {
174,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (!mp) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); } Commit Message: mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: stable@vger.kernel.org Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> CWE ID: CWE-284
void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (!mp) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); if (mnt->mnt.mnt_flags & MNT_UMOUNT) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { hlist_add_head(&p->mnt_umount.s_list, &unmounted); umount_mnt(p); } } else umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); }
167,588
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint32_t color_string_to_rgba(const char *p, int len) { uint32_t ret = 0xFF000000; const ColorEntry *entry; char color_name[100]; if (*p == '#') { p++; len--; if (len == 3) { ret |= (hex_char_to_number(p[2]) << 4) | (hex_char_to_number(p[1]) << 12) | (hex_char_to_number(p[0]) << 20); } else if (len == 4) { ret = (hex_char_to_number(p[3]) << 4) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 20) | (hex_char_to_number(p[0]) << 28); } else if (len == 6) { ret |= hex_char_to_number(p[5]) | (hex_char_to_number(p[4]) << 4) | (hex_char_to_number(p[3]) << 8) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 16) | (hex_char_to_number(p[0]) << 20); } else if (len == 8) { ret = hex_char_to_number(p[7]) | (hex_char_to_number(p[6]) << 4) | (hex_char_to_number(p[5]) << 8) | (hex_char_to_number(p[4]) << 12) | (hex_char_to_number(p[3]) << 16) | (hex_char_to_number(p[2]) << 20) | (hex_char_to_number(p[1]) << 24) | (hex_char_to_number(p[0]) << 28); } } else { strncpy(color_name, p, len); color_name[len] = '\0'; entry = bsearch(color_name, color_table, FF_ARRAY_ELEMS(color_table), sizeof(ColorEntry), color_table_compare); if (!entry) return ret; ret = entry->rgb_color; } return ret; } Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues Most of these were found through code review in response to fixing 1466/clusterfuzz-testcase-minimized-5961584419536896 There is thus no testcase for most of this. The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static uint32_t color_string_to_rgba(const char *p, int len) { uint32_t ret = 0xFF000000; const ColorEntry *entry; char color_name[100]; len = FFMIN(FFMAX(len, 0), sizeof(color_name) - 1); if (*p == '#') { p++; len--; if (len == 3) { ret |= (hex_char_to_number(p[2]) << 4) | (hex_char_to_number(p[1]) << 12) | (hex_char_to_number(p[0]) << 20); } else if (len == 4) { ret = (hex_char_to_number(p[3]) << 4) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 20) | (hex_char_to_number(p[0]) << 28); } else if (len == 6) { ret |= hex_char_to_number(p[5]) | (hex_char_to_number(p[4]) << 4) | (hex_char_to_number(p[3]) << 8) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 16) | (hex_char_to_number(p[0]) << 20); } else if (len == 8) { ret = hex_char_to_number(p[7]) | (hex_char_to_number(p[6]) << 4) | (hex_char_to_number(p[5]) << 8) | (hex_char_to_number(p[4]) << 12) | (hex_char_to_number(p[3]) << 16) | (hex_char_to_number(p[2]) << 20) | (hex_char_to_number(p[1]) << 24) | (hex_char_to_number(p[0]) << 28); } } else { strncpy(color_name, p, len); color_name[len] = '\0'; entry = bsearch(color_name, color_table, FF_ARRAY_ELEMS(color_table), sizeof(ColorEntry), color_table_compare); if (!entry) return ret; ret = entry->rgb_color; } return ret; }
168,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_parse_color(xps_document *doc, char *base_uri, char *string, fz_colorspace **csp, float *samples) { char *p; int i, n; char buf[1024]; char *profile; *csp = fz_device_rgb(doc->ctx); samples[0] = 1; samples[1] = 0; samples[3] = 0; if (string[0] == '#') { if (strlen(string) == 9) { samples[0] = unhex(string[1]) * 16 + unhex(string[2]); samples[1] = unhex(string[3]) * 16 + unhex(string[4]); samples[2] = unhex(string[5]) * 16 + unhex(string[6]); samples[3] = unhex(string[7]) * 16 + unhex(string[8]); } else { samples[0] = 255; samples[1] = unhex(string[1]) * 16 + unhex(string[2]); samples[2] = unhex(string[3]) * 16 + unhex(string[4]); samples[3] = unhex(string[5]) * 16 + unhex(string[6]); } samples[0] /= 255; samples[1] /= 255; samples[2] /= 255; samples[3] /= 255; } else if (string[0] == 's' && string[1] == 'c' && string[2] == '#') { if (count_commas(string) == 2) sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3); if (count_commas(string) == 3) sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3); } else if (strstr(string, "ContextColor ") == string) { /* Crack the string for profile name and sample values */ fz_strlcpy(buf, string, sizeof buf); profile = strchr(buf, ' '); profile = strchr(buf, ' '); if (!profile) { fz_warn(doc->ctx, "cannot find icc profile uri in '%s'", string); return; } p = strchr(profile, ' '); p = strchr(profile, ' '); if (!p) { fz_warn(doc->ctx, "cannot find component values in '%s'", profile); return; } *p++ = 0; n = count_commas(p) + 1; i = 0; while (i < n) { p ++; } while (i < n) { samples[i++] = 0; } /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; default: *csp = fz_device_gray(doc->ctx); break; } } } for (i = 0; i < colorspace->n; i++) doc->color[i] = samples[i + 1]; doc->alpha = samples[0] * doc->opacity[doc->opacity_top]; } Commit Message: CWE ID: CWE-119
xps_parse_color(xps_document *doc, char *base_uri, char *string, fz_colorspace **csp, float *samples) { fz_context *ctx = doc->ctx; char *p; int i, n; char buf[1024]; char *profile; *csp = fz_device_rgb(ctx); samples[0] = 1; samples[1] = 0; samples[3] = 0; if (string[0] == '#') { if (strlen(string) == 9) { samples[0] = unhex(string[1]) * 16 + unhex(string[2]); samples[1] = unhex(string[3]) * 16 + unhex(string[4]); samples[2] = unhex(string[5]) * 16 + unhex(string[6]); samples[3] = unhex(string[7]) * 16 + unhex(string[8]); } else { samples[0] = 255; samples[1] = unhex(string[1]) * 16 + unhex(string[2]); samples[2] = unhex(string[3]) * 16 + unhex(string[4]); samples[3] = unhex(string[5]) * 16 + unhex(string[6]); } samples[0] /= 255; samples[1] /= 255; samples[2] /= 255; samples[3] /= 255; } else if (string[0] == 's' && string[1] == 'c' && string[2] == '#') { if (count_commas(string) == 2) sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3); if (count_commas(string) == 3) sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3); } else if (strstr(string, "ContextColor ") == string) { /* Crack the string for profile name and sample values */ fz_strlcpy(buf, string, sizeof buf); profile = strchr(buf, ' '); profile = strchr(buf, ' '); if (!profile) { fz_warn(ctx, "cannot find icc profile uri in '%s'", string); return; } p = strchr(profile, ' '); p = strchr(profile, ' '); if (!p) { fz_warn(ctx, "cannot find component values in '%s'", profile); return; } *p++ = 0; n = count_commas(p) + 1; if (n > FZ_MAX_COLORS) { fz_warn(ctx, "ignoring %d color components (max %d allowed)", n - FZ_MAX_COLORS, FZ_MAX_COLORS); n = FZ_MAX_COLORS; } i = 0; while (i < n) { p ++; } while (i < n) { samples[i++] = 0; } /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(ctx); break; case 4: *csp = fz_device_rgb(ctx); break; case 5: *csp = fz_device_cmyk(ctx); break; default: *csp = fz_device_gray(ctx); break; } } } for (i = 0; i < colorspace->n; i++) doc->color[i] = samples[i + 1]; doc->alpha = samples[0] * doc->opacity[doc->opacity_top]; }
165,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, getStub) { size_t len; char *buf; php_stream *fp; php_stream_filter *filter = NULL; phar_entry_info *stub; phar_entry_info *stub; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } if (SUCCESS == zend_hash_find(&(phar_obj->arc.archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) { fp = phar_obj->arc.archive->fp; } else { if (!(fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to open phar \"%s\"", phar_obj->arc.archive->fname); return; } if (stub->flags & PHAR_ENT_COMPRESSION_MASK) { char *filter_name; if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) { filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp) TSRMLS_CC); } else { filter = NULL; } if (!filter) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->arc.archive->fname, phar_decompress_filter(stub, 1)); return; } php_stream_filter_append(&fp->readfilters, filter); } } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); return; } php_stream_seek(fp, stub->offset_abs, SEEK_SET); len = stub->uncompressed_filesize; goto carry_on; } else { RETURN_STRINGL("", 0, 1); } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, getStub) { size_t len; char *buf; php_stream *fp; php_stream_filter *filter = NULL; phar_entry_info *stub; phar_entry_info *stub; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } if (SUCCESS == zend_hash_find(&(phar_obj->arc.archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) { fp = phar_obj->arc.archive->fp; } else { if (!(fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to open phar \"%s\"", phar_obj->arc.archive->fname); return; } if (stub->flags & PHAR_ENT_COMPRESSION_MASK) { char *filter_name; if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) { filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp) TSRMLS_CC); } else { filter = NULL; } if (!filter) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->arc.archive->fname, phar_decompress_filter(stub, 1)); return; } php_stream_filter_append(&fp->readfilters, filter); } } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); return; } php_stream_seek(fp, stub->offset_abs, SEEK_SET); len = stub->uncompressed_filesize; goto carry_on; } else { RETURN_STRINGL("", 0, 1); } }
165,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintingContextCairo::PrintingContextCairo(const std::string& app_locale) #if defined(OS_CHROMEOS) : PrintingContext(app_locale) { #else : PrintingContext(app_locale), print_dialog_(NULL) { #endif } PrintingContextCairo::~PrintingContextCairo() { ReleaseContext(); #if !defined(OS_CHROMEOS) if (print_dialog_) print_dialog_->ReleaseDialog(); #endif } #if !defined(OS_CHROMEOS) void PrintingContextCairo::SetCreatePrintDialogFunction( PrintDialogGtkInterface* (*create_dialog_func)( PrintingContextCairo* context)) { DCHECK(create_dialog_func); DCHECK(!create_dialog_func_); create_dialog_func_ = create_dialog_func; } void PrintingContextCairo::PrintDocument(const Metafile* metafile) { DCHECK(print_dialog_); DCHECK(metafile); print_dialog_->PrintDocument(metafile, document_name_); } #endif // !defined(OS_CHROMEOS) void PrintingContextCairo::AskUserForSettings( gfx::NativeView parent_view, int max_pages, bool has_selection, PrintSettingsCallback* callback) { #if defined(OS_CHROMEOS) callback->Run(OK); #else print_dialog_->ShowDialog(callback); #endif // defined(OS_CHROMEOS) } PrintingContext::Result PrintingContextCairo::UseDefaultSettings() { DCHECK(!in_print_job_); ResetSettings(); #if defined(OS_CHROMEOS) int dpi = 300; gfx::Size physical_size_device_units; gfx::Rect printable_area_device_units; int32_t width = 0; int32_t height = 0; UErrorCode error = U_ZERO_ERROR; ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error); if (error != U_ZERO_ERROR) { LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: " << error; width = static_cast<int>(8.5 * dpi); height = static_cast<int>(11 * dpi); } else { width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi); height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi); } physical_size_device_units.SetSize(width, height); printable_area_device_units.SetRect( static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi), static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi), width - (PrintSettingsInitializerGtk::kLeftMarginInInch + PrintSettingsInitializerGtk::kRightMarginInInch) * dpi, height - (PrintSettingsInitializerGtk::kTopMarginInInch + PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi); settings_.set_dpi(dpi); settings_.SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); #else if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } print_dialog_->UseDefaultSettings(); #endif // defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } PrintingContext::Result PrintingContextCairo::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; return OK; } PrintingContext::Result PrintingContextCairo::NewDocument( const string16& document_name) { DCHECK(!in_print_job_); in_print_job_ = true; #if !defined(OS_CHROMEOS) document_name_ = document_name; #endif // !defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::NewPage() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); ResetSettings(); return OK; } void PrintingContextCairo::Cancel() { abort_printing_ = true; in_print_job_ = false; } void PrintingContextCairo::ReleaseContext() { } gfx::NativeDrawingContext PrintingContextCairo::context() const { return NULL; } } // namespace printing Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PrintingContextCairo::PrintingContextCairo(const std::string& app_locale) #if defined(OS_CHROMEOS) : PrintingContext(app_locale) { #else : PrintingContext(app_locale), print_dialog_(NULL) { #endif } PrintingContextCairo::~PrintingContextCairo() { ReleaseContext(); #if !defined(OS_CHROMEOS) if (print_dialog_) print_dialog_->ReleaseDialog(); #endif } #if !defined(OS_CHROMEOS) void PrintingContextCairo::SetCreatePrintDialogFunction( PrintDialogGtkInterface* (*create_dialog_func)( PrintingContextCairo* context)) { DCHECK(create_dialog_func); DCHECK(!create_dialog_func_); create_dialog_func_ = create_dialog_func; } void PrintingContextCairo::PrintDocument(const Metafile* metafile) { DCHECK(print_dialog_); DCHECK(metafile); print_dialog_->PrintDocument(metafile, document_name_); } #endif // !defined(OS_CHROMEOS) void PrintingContextCairo::AskUserForSettings( gfx::NativeView parent_view, int max_pages, bool has_selection, PrintSettingsCallback* callback) { #if defined(OS_CHROMEOS) callback->Run(OK); #else print_dialog_->ShowDialog(callback); #endif // defined(OS_CHROMEOS) } PrintingContext::Result PrintingContextCairo::UseDefaultSettings() { DCHECK(!in_print_job_); ResetSettings(); #if defined(OS_CHROMEOS) int dpi = 300; gfx::Size physical_size_device_units; gfx::Rect printable_area_device_units; int32_t width = 0; int32_t height = 0; UErrorCode error = U_ZERO_ERROR; ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error); if (error != U_ZERO_ERROR) { LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: " << error; width = static_cast<int>(8.5 * dpi); height = static_cast<int>(11 * dpi); } else { width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi); height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi); } physical_size_device_units.SetSize(width, height); printable_area_device_units.SetRect( static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi), static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi), width - (PrintSettingsInitializerGtk::kLeftMarginInInch + PrintSettingsInitializerGtk::kRightMarginInInch) * dpi, height - (PrintSettingsInitializerGtk::kTopMarginInInch + PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi); settings_.set_dpi(dpi); settings_.SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); #else if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } print_dialog_->UseDefaultSettings(); #endif // defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } PrintingContext::Result PrintingContextCairo::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; return OK; } PrintingContext::Result PrintingContextCairo::NewDocument( const string16& document_name) { DCHECK(!in_print_job_); in_print_job_ = true; #if !defined(OS_CHROMEOS) document_name_ = document_name; #endif // !defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::NewPage() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); ResetSettings(); return OK; } void PrintingContextCairo::Cancel() { abort_printing_ = true; in_print_job_ = false; } void PrintingContextCairo::ReleaseContext() { } gfx::NativeDrawingContext PrintingContextCairo::context() const { return NULL; } } // namespace printing
170,266
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NetworkThrottleManagerImpl::SetTickClockForTesting( std::unique_ptr<base::TickClock> tick_clock) { tick_clock_ = std::move(tick_clock); DCHECK(!outstanding_recomputation_timer_->IsRunning()); outstanding_recomputation_timer_ = base::MakeUnique<base::Timer>( false /* retain_user_task */, false /* is_repeating */, tick_clock_.get()); } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <jbroman@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Bence Béky <bnc@chromium.org> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
void NetworkThrottleManagerImpl::SetTickClockForTesting( std::unique_ptr<base::TickClock> tick_clock) { tick_clock_ = std::move(tick_clock); DCHECK(!outstanding_recomputation_timer_->IsRunning()); outstanding_recomputation_timer_ = std::make_unique<base::Timer>( false /* retain_user_task */, false /* is_repeating */, tick_clock_.get()); }
173,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); } Commit Message: (for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check In lmp_print_data_link_subobjs(). 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
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; }
169,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static enum integrity_status evm_verify_hmac(struct dentry *dentry, const char *xattr_name, char *xattr_value, size_t xattr_value_len, struct integrity_iint_cache *iint) { struct evm_ima_xattr_data *xattr_data = NULL; struct evm_ima_xattr_data calc; enum integrity_status evm_status = INTEGRITY_PASS; int rc, xattr_len; if (iint && iint->evm_status == INTEGRITY_PASS) return iint->evm_status; /* if status is not PASS, try to check again - against -ENOMEM */ /* first need to know the sig type */ rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0, GFP_NOFS); if (rc <= 0) { evm_status = INTEGRITY_FAIL; if (rc == -ENODATA) { rc = evm_find_protected_xattrs(dentry); if (rc > 0) evm_status = INTEGRITY_NOLABEL; else if (rc == 0) evm_status = INTEGRITY_NOXATTRS; /* new file */ } else if (rc == -EOPNOTSUPP) { evm_status = INTEGRITY_UNKNOWN; } goto out; } xattr_len = rc; /* check value type */ switch (xattr_data->type) { case EVM_XATTR_HMAC: rc = evm_calc_hmac(dentry, xattr_name, xattr_value, xattr_value_len, calc.digest); if (rc) break; rc = memcmp(xattr_data->digest, calc.digest, sizeof(calc.digest)); if (rc) rc = -EINVAL; break; case EVM_IMA_XATTR_DIGSIG: rc = evm_calc_hash(dentry, xattr_name, xattr_value, xattr_value_len, calc.digest); if (rc) break; rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM, (const char *)xattr_data, xattr_len, calc.digest, sizeof(calc.digest)); if (!rc) { /* Replace RSA with HMAC if not mounted readonly and * not immutable */ if (!IS_RDONLY(d_backing_inode(dentry)) && !IS_IMMUTABLE(d_backing_inode(dentry))) evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len); } break; default: rc = -EINVAL; break; } if (rc) evm_status = (rc == -ENODATA) ? INTEGRITY_NOXATTRS : INTEGRITY_FAIL; out: if (iint) iint->evm_status = evm_status; kfree(xattr_data); return evm_status; } Commit Message: EVM: Use crypto_memneq() for digest comparisons This patch fixes vulnerability CVE-2016-2085. The problem exists because the vm_verify_hmac() function includes a use of memcmp(). Unfortunately, this allows timing side channel attacks; specifically a MAC forgery complexity drop from 2^128 to 2^12. This patch changes the memcmp() to the cryptographically safe crypto_memneq(). Reported-by: Xiaofei Rex Guo <xiaofei.rex.guo@intel.com> Signed-off-by: Ryan Ware <ware@linux.intel.com> Cc: stable@vger.kernel.org Signed-off-by: Mimi Zohar <zohar@linux.vnet.ibm.com> Signed-off-by: James Morris <james.l.morris@oracle.com> CWE ID: CWE-19
static enum integrity_status evm_verify_hmac(struct dentry *dentry, const char *xattr_name, char *xattr_value, size_t xattr_value_len, struct integrity_iint_cache *iint) { struct evm_ima_xattr_data *xattr_data = NULL; struct evm_ima_xattr_data calc; enum integrity_status evm_status = INTEGRITY_PASS; int rc, xattr_len; if (iint && iint->evm_status == INTEGRITY_PASS) return iint->evm_status; /* if status is not PASS, try to check again - against -ENOMEM */ /* first need to know the sig type */ rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0, GFP_NOFS); if (rc <= 0) { evm_status = INTEGRITY_FAIL; if (rc == -ENODATA) { rc = evm_find_protected_xattrs(dentry); if (rc > 0) evm_status = INTEGRITY_NOLABEL; else if (rc == 0) evm_status = INTEGRITY_NOXATTRS; /* new file */ } else if (rc == -EOPNOTSUPP) { evm_status = INTEGRITY_UNKNOWN; } goto out; } xattr_len = rc; /* check value type */ switch (xattr_data->type) { case EVM_XATTR_HMAC: rc = evm_calc_hmac(dentry, xattr_name, xattr_value, xattr_value_len, calc.digest); if (rc) break; rc = crypto_memneq(xattr_data->digest, calc.digest, sizeof(calc.digest)); if (rc) rc = -EINVAL; break; case EVM_IMA_XATTR_DIGSIG: rc = evm_calc_hash(dentry, xattr_name, xattr_value, xattr_value_len, calc.digest); if (rc) break; rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM, (const char *)xattr_data, xattr_len, calc.digest, sizeof(calc.digest)); if (!rc) { /* Replace RSA with HMAC if not mounted readonly and * not immutable */ if (!IS_RDONLY(d_backing_inode(dentry)) && !IS_IMMUTABLE(d_backing_inode(dentry))) evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len); } break; default: rc = -EINVAL; break; } if (rc) evm_status = (rc == -ENODATA) ? INTEGRITY_NOXATTRS : INTEGRITY_FAIL; out: if (iint) iint->evm_status = evm_status; kfree(xattr_data); return evm_status; }
167,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num)); asn1_write(data, blob->data, blob->length); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob) { if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num))) return false; if (!asn1_write(data, blob->data, blob->length)) return false; return asn1_pop_tag(data); }
164,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CSSDefaultStyleSheets::loadSimpleDefaultStyle() { ASSERT(!defaultStyle); ASSERT(!simpleDefaultStyleSheet); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = defaultStyle; defaultQuirksStyle = RuleSet::create().leakPtr(); simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet)); defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval()); defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval()); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void CSSDefaultStyleSheets::loadSimpleDefaultStyle()
171,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "app", std::unique_ptr<NativeHandler>( new extensions::AppBindings(dispatcher, context))); module_system->RegisterNativeHandler( "sync_file_system", std::unique_ptr<NativeHandler>( new extensions::SyncFileSystemCustomBindings(context))); module_system->RegisterNativeHandler( "file_browser_handler", std::unique_ptr<NativeHandler>( new extensions::FileBrowserHandlerCustomBindings(context))); module_system->RegisterNativeHandler( "file_manager_private", std::unique_ptr<NativeHandler>( new extensions::FileManagerPrivateCustomBindings(context))); module_system->RegisterNativeHandler( "notifications_private", std::unique_ptr<NativeHandler>( new extensions::NotificationsNativeHandler(context))); module_system->RegisterNativeHandler( "mediaGalleries", std::unique_ptr<NativeHandler>( new extensions::MediaGalleriesCustomBindings(context))); module_system->RegisterNativeHandler( "page_capture", std::unique_ptr<NativeHandler>( new extensions::PageCaptureCustomBindings(context))); module_system->RegisterNativeHandler( "platform_keys_natives", std::unique_ptr<NativeHandler>( new extensions::PlatformKeysNatives(context))); module_system->RegisterNativeHandler( "tabs", std::unique_ptr<NativeHandler>( new extensions::TabsCustomBindings(context))); module_system->RegisterNativeHandler( "webstore", std::unique_ptr<NativeHandler>( new extensions::WebstoreBindings(context))); #if defined(ENABLE_WEBRTC) module_system->RegisterNativeHandler( "cast_streaming_natives", std::unique_ptr<NativeHandler>( new extensions::CastStreamingNativeHandler(context))); #endif module_system->RegisterNativeHandler( "automationInternal", std::unique_ptr<NativeHandler>( new extensions::AutomationInternalCustomBindings(context))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "app", std::unique_ptr<NativeHandler>( new extensions::AppBindings(dispatcher, context))); module_system->RegisterNativeHandler( "sync_file_system", std::unique_ptr<NativeHandler>( new extensions::SyncFileSystemCustomBindings(context))); module_system->RegisterNativeHandler( "file_browser_handler", std::unique_ptr<NativeHandler>( new extensions::FileBrowserHandlerCustomBindings(context))); module_system->RegisterNativeHandler( "file_manager_private", std::unique_ptr<NativeHandler>( new extensions::FileManagerPrivateCustomBindings(context))); module_system->RegisterNativeHandler( "notifications_private", std::unique_ptr<NativeHandler>( new extensions::NotificationsNativeHandler(context))); module_system->RegisterNativeHandler( "mediaGalleries", std::unique_ptr<NativeHandler>( new extensions::MediaGalleriesCustomBindings(context))); module_system->RegisterNativeHandler( "page_capture", std::unique_ptr<NativeHandler>( new extensions::PageCaptureCustomBindings(context))); module_system->RegisterNativeHandler( "platform_keys_natives", std::unique_ptr<NativeHandler>( new extensions::PlatformKeysNatives(context))); module_system->RegisterNativeHandler( "tabs", std::unique_ptr<NativeHandler>( new extensions::TabsCustomBindings(context))); module_system->RegisterNativeHandler( "webstore", std::unique_ptr<NativeHandler>( new extensions::WebstoreBindings(context))); #if defined(ENABLE_WEBRTC) module_system->RegisterNativeHandler( "cast_streaming_natives", std::unique_ptr<NativeHandler>( new extensions::CastStreamingNativeHandler(context))); #endif module_system->RegisterNativeHandler( "automationInternal", std::unique_ptr<NativeHandler>( new extensions::AutomationInternalCustomBindings(context))); // The following are native handlers that are defined in //extensions, but // are only used for APIs defined in Chrome. // TODO(devlin): We should clean this up. If an API is defined in Chrome, // there's no reason to have its native handlers residing and being compiled // in //extensions. module_system->RegisterNativeHandler( "i18n", scoped_ptr<NativeHandler>(new extensions::I18NCustomBindings(context))); module_system->RegisterNativeHandler( "lazy_background_page", scoped_ptr<NativeHandler>( new extensions::LazyBackgroundPageNativeHandler(context))); }
172,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; if (sepIdx >= sizeof(szSec)) { fprintf(stderr, "Badly formatted option %s - Section name is too long\n", opt_string); return; } strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; if (sepIdx >= sizeof(szKey)) { fprintf(stderr, "Badly formatted option %s - key name is too long\n", opt_string); return; } strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; if (strlen(sep2 + 1) >= sizeof(szVal)) { fprintf(stderr, "Badly formatted option %s - value is too long\n", opt_string); return; } strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); }
169,791
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static jboolean enableNative(JNIEnv* env, jobject obj) { ALOGV("%s:",__FUNCTION__); jboolean result = JNI_FALSE; if (!sBluetoothInterface) return result; int ret = sBluetoothInterface->enable(); result = (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; return result; } Commit Message: Add guest mode functionality (3/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: If4a8855faf362d7f6de509d7ddc7197d1ac75cee CWE ID: CWE-20
static jboolean enableNative(JNIEnv* env, jobject obj) { static jboolean enableNative(JNIEnv* env, jobject obj, jboolean isGuest) { ALOGV("%s:",__FUNCTION__); jboolean result = JNI_FALSE; if (!sBluetoothInterface) return result; int ret = sBluetoothInterface->enable(isGuest == JNI_TRUE ? 1 : 0); result = (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; return result; }
174,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (written, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; } Commit Message: CWE ID: CWE-20
aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (AS_SEGMENT_MAX, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; }
164,639
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type) { M_list_str_t *parts; const char *part; char *out; size_t len; size_t i; size_t count; if (path == NULL) { return NULL; } len = M_list_str_len(path); if (len == 0) { return NULL; } sys_type = M_fs_path_get_system_type(sys_type); /* Remove any empty parts (except for the first part which denotes an abs path on Unix * or a UNC path on Windows). */ parts = M_list_str_duplicate(path); for (i=len-1; i>0; i--) { part = M_list_str_at(parts, i); if (part == NULL || *part == '\0') { M_list_str_remove_at(parts, i); } } len = M_list_str_len(parts); /* Join puts the sep between items. If there are no items then the sep * won't be written. */ part = M_list_str_at(parts, 0); if (len == 1 && (part == NULL || *part == '\0')) { M_list_str_destroy(parts); if (sys_type == M_FS_SYSTEM_WINDOWS) { return M_strdup("\\\\"); } return M_strdup("/"); } /* Handle windows abs path because they need two separators. */ if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) { part = M_list_str_at(parts, 0); /* If we have 1 item we need to add two empties so we get the second separator. */ count = (len == 1) ? 2 : 1; /* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */ if (part != NULL && *part == '\0') { for (i=0; i<count; i++) { M_list_str_insert_at(parts, "", 0); } } else if (M_fs_path_isabs(part, sys_type) && len == 1) { /* We need to add an empty so we get a separator after the drive. */ M_list_str_insert_at(parts, "", 1); } } out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type)); M_list_str_destroy(parts); return out; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type) { M_list_str_t *parts; const char *part; char *out; size_t len; size_t i; size_t count; if (path == NULL) { return NULL; } len = M_list_str_len(path); if (len == 0) { return NULL; } sys_type = M_fs_path_get_system_type(sys_type); /* Remove any empty parts (except for the first part which denotes an abs path on Unix * or a UNC path on Windows). */ parts = M_list_str_duplicate(path); for (i=len-1; i>0; i--) { part = M_list_str_at(parts, i); if (part == NULL || *part == '\0') { M_list_str_remove_at(parts, i); } } len = M_list_str_len(parts); /* Join puts the sep between items. If there are no items then the sep * won't be written. */ part = M_list_str_at(parts, 0); if (len == 1 && (part == NULL || *part == '\0')) { M_list_str_destroy(parts); if (sys_type == M_FS_SYSTEM_WINDOWS) { return M_strdup("\\\\"); } return M_strdup("/"); } /* Handle windows abs path because they need two separators. */ if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) { part = M_list_str_at(parts, 0); /* If we have 1 item we need to add two empties so we get the second separator. */ count = (len == 1) ? 2 : 1; /* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */ if (part != NULL && *part == '\0') { for (i=0; i<count; i++) { M_list_str_insert_at(parts, "", 0); } } else if (M_fs_path_isabs(part, sys_type) && len == 1) { /* We need to add an empty so we get a separator after the drive. */ M_list_str_insert_at(parts, "", 1); } } out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type)); M_list_str_destroy(parts); return out; }
169,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string GetDMToken() { std::string dm_token = *GetTestingDMToken(); #if !defined(OS_CHROMEOS) if (dm_token.empty() && policy::ChromeBrowserCloudManagementController::IsEnabled()) { dm_token = policy::BrowserDMTokenStorage::Get()->RetrieveDMToken(); } #endif return dm_token; } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org> Reviewed-by: Tien Mai <tienmai@chromium.org> Reviewed-by: Daniel Rubery <drubery@chromium.org> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
std::string GetDMToken() { BrowserDMToken GetTestingDMToken() { const char* dm_token = *GetTestingDMTokenStorage(); return dm_token && dm_token[0] ? BrowserDMToken::CreateValidToken(dm_token) : BrowserDMToken::CreateEmptyToken(); } policy::BrowserDMTokenStorage::BrowserDMToken GetDMToken() { auto dm_token = GetTestingDMToken(); #if !defined(OS_CHROMEOS) if (dm_token.is_empty() && policy::ChromeBrowserCloudManagementController::IsEnabled()) { dm_token = policy::BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken(); } #endif return dm_token; }
172,353
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_results(struct iperf_test *test) { int r = 0; cJSON *j; cJSON *j_cpu_util_total; cJSON *j_cpu_util_user; cJSON *j_cpu_util_system; cJSON *j_sender_has_retransmits; int result_has_retransmits; cJSON *j_streams; int n, i; cJSON *j_stream; cJSON *j_id; cJSON *j_bytes; cJSON *j_retransmits; cJSON *j_jitter; cJSON *j_errors; cJSON *j_packets; cJSON *j_server_output; int sid, cerror, pcount; double jitter; iperf_size_t bytes_transferred; int retransmits; struct iperf_stream *sp; j = JSON_read(test->ctrl_sck); if (j == NULL) { i_errno = IERECVRESULTS; r = -1; } else { j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total"); j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user"); j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system"); j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits"); if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) { i_errno = IERECVRESULTS; r = -1; } else { if (test->debug) { printf("get_results\n%s\n", cJSON_Print(j)); } test->remote_cpu_util[0] = j_cpu_util_total->valuefloat; test->remote_cpu_util[1] = j_cpu_util_user->valuefloat; test->remote_cpu_util[2] = j_cpu_util_system->valuefloat; result_has_retransmits = j_sender_has_retransmits->valueint; if (! test->sender) test->sender_has_retransmits = result_has_retransmits; j_streams = cJSON_GetObjectItem(j, "streams"); if (j_streams == NULL) { i_errno = IERECVRESULTS; r = -1; } else { n = cJSON_GetArraySize(j_streams); for (i=0; i<n; ++i) { j_stream = cJSON_GetArrayItem(j_streams, i); if (j_stream == NULL) { i_errno = IERECVRESULTS; r = -1; } else { j_id = cJSON_GetObjectItem(j_stream, "id"); j_bytes = cJSON_GetObjectItem(j_stream, "bytes"); j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits"); j_jitter = cJSON_GetObjectItem(j_stream, "jitter"); j_errors = cJSON_GetObjectItem(j_stream, "errors"); j_packets = cJSON_GetObjectItem(j_stream, "packets"); if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) { i_errno = IERECVRESULTS; r = -1; } else { sid = j_id->valueint; bytes_transferred = j_bytes->valueint; retransmits = j_retransmits->valueint; jitter = j_jitter->valuefloat; cerror = j_errors->valueint; pcount = j_packets->valueint; SLIST_FOREACH(sp, &test->streams, streams) if (sp->id == sid) break; if (sp == NULL) { i_errno = IESTREAMID; r = -1; } else { if (test->sender) { sp->jitter = jitter; sp->cnt_error = cerror; sp->packet_count = pcount; sp->result->bytes_received = bytes_transferred; } else { sp->result->bytes_sent = bytes_transferred; sp->result->stream_retrans = retransmits; } } } } } /* * If we're the client and we're supposed to get remote results, * look them up and process accordingly. */ if (test->role == 'c' && iperf_get_test_get_server_output(test)) { /* Look for JSON. If we find it, grab the object so it doesn't get deleted. */ j_server_output = cJSON_DetachItemFromObject(j, "server_output_json"); if (j_server_output != NULL) { test->json_server_output = j_server_output; } else { /* No JSON, look for textual output. Make a copy of the text for later. */ j_server_output = cJSON_GetObjectItem(j, "server_output_text"); if (j_server_output != NULL) { test->server_output_text = strdup(j_server_output->valuestring); } } } } } cJSON_Delete(j); } return r; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
get_results(struct iperf_test *test) { int r = 0; cJSON *j; cJSON *j_cpu_util_total; cJSON *j_cpu_util_user; cJSON *j_cpu_util_system; cJSON *j_sender_has_retransmits; int result_has_retransmits; cJSON *j_streams; int n, i; cJSON *j_stream; cJSON *j_id; cJSON *j_bytes; cJSON *j_retransmits; cJSON *j_jitter; cJSON *j_errors; cJSON *j_packets; cJSON *j_server_output; int sid, cerror, pcount; double jitter; iperf_size_t bytes_transferred; int retransmits; struct iperf_stream *sp; j = JSON_read(test->ctrl_sck); if (j == NULL) { i_errno = IERECVRESULTS; r = -1; } else { j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total"); j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user"); j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system"); j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits"); if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) { i_errno = IERECVRESULTS; r = -1; } else { if (test->debug) { printf("get_results\n%s\n", cJSON_Print(j)); } test->remote_cpu_util[0] = j_cpu_util_total->valuedouble; test->remote_cpu_util[1] = j_cpu_util_user->valuedouble; test->remote_cpu_util[2] = j_cpu_util_system->valuedouble; result_has_retransmits = j_sender_has_retransmits->valueint; if (! test->sender) test->sender_has_retransmits = result_has_retransmits; j_streams = cJSON_GetObjectItem(j, "streams"); if (j_streams == NULL) { i_errno = IERECVRESULTS; r = -1; } else { n = cJSON_GetArraySize(j_streams); for (i=0; i<n; ++i) { j_stream = cJSON_GetArrayItem(j_streams, i); if (j_stream == NULL) { i_errno = IERECVRESULTS; r = -1; } else { j_id = cJSON_GetObjectItem(j_stream, "id"); j_bytes = cJSON_GetObjectItem(j_stream, "bytes"); j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits"); j_jitter = cJSON_GetObjectItem(j_stream, "jitter"); j_errors = cJSON_GetObjectItem(j_stream, "errors"); j_packets = cJSON_GetObjectItem(j_stream, "packets"); if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) { i_errno = IERECVRESULTS; r = -1; } else { sid = j_id->valueint; bytes_transferred = j_bytes->valueint; retransmits = j_retransmits->valueint; jitter = j_jitter->valuedouble; cerror = j_errors->valueint; pcount = j_packets->valueint; SLIST_FOREACH(sp, &test->streams, streams) if (sp->id == sid) break; if (sp == NULL) { i_errno = IESTREAMID; r = -1; } else { if (test->sender) { sp->jitter = jitter; sp->cnt_error = cerror; sp->packet_count = pcount; sp->result->bytes_received = bytes_transferred; } else { sp->result->bytes_sent = bytes_transferred; sp->result->stream_retrans = retransmits; } } } } } /* * If we're the client and we're supposed to get remote results, * look them up and process accordingly. */ if (test->role == 'c' && iperf_get_test_get_server_output(test)) { /* Look for JSON. If we find it, grab the object so it doesn't get deleted. */ j_server_output = cJSON_DetachItemFromObject(j, "server_output_json"); if (j_server_output != NULL) { test->json_server_output = j_server_output; } else { /* No JSON, look for textual output. Make a copy of the text for later. */ j_server_output = cJSON_GetObjectItem(j, "server_output_text"); if (j_server_output != NULL) { test->server_output_text = strdup(j_server_output->valuestring); } } } } } cJSON_Delete(j); } return r; }
167,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } Commit Message: CVE-2017-13689/IKEv1: Fix addr+subnet length check. An IPv6 address plus subnet mask is 32 bytes, not 20 bytes. 16 bytes of IPv6 address, 16 bytes of subnet mask. 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
ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; }
167,804
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AccessType GetExtensionAccess(const Extension* extension, const GURL& url, int tab_id) { bool allowed_script = IsAllowedScript(extension, url, tab_id); bool allowed_capture = extension->permissions_data()->CanCaptureVisiblePage(tab_id, nullptr); if (allowed_script && allowed_capture) return ALLOWED_SCRIPT_AND_CAPTURE; if (allowed_script) return ALLOWED_SCRIPT_ONLY; if (allowed_capture) return ALLOWED_CAPTURE_ONLY; return DISALLOWED; } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Karan Bhatia <karandeepb@chromium.org> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20
AccessType GetExtensionAccess(const Extension* extension, const GURL& url, int tab_id) { bool allowed_script = IsAllowedScript(extension, url, tab_id); bool allowed_capture = extension->permissions_data()->CanCaptureVisiblePage( url, extension, tab_id, nullptr); if (allowed_script && allowed_capture) return ALLOWED_SCRIPT_AND_CAPTURE; if (allowed_script) return ALLOWED_SCRIPT_ONLY; if (allowed_capture) return ALLOWED_CAPTURE_ONLY; return DISALLOWED; }
173,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lex(struct scanner *s, union lvalue *val) { skip_more_whitespace_and_comments: /* Skip spaces. */ while (is_space(peek(s))) if (next(s) == '\n') return TOK_END_OF_LINE; /* Skip comments. */ if (chr(s, '#')) { skip_to_eol(s); goto skip_more_whitespace_and_comments; } /* See if we're done. */ if (eof(s)) return TOK_END_OF_FILE; /* New token. */ s->token_line = s->line; s->token_column = s->column; s->buf_pos = 0; /* LHS Keysym. */ if (chr(s, '<')) { while (peek(s) != '>' && !eol(s)) buf_append(s, next(s)); if (!chr(s, '>')) { scanner_err(s, "unterminated keysym literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "keysym literal is too long"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_LHS_KEYSYM; } /* Colon. */ if (chr(s, ':')) return TOK_COLON; if (chr(s, '!')) return TOK_BANG; if (chr(s, '~')) return TOK_TILDE; /* String literal. */ if (chr(s, '\"')) { while (!eof(s) && !eol(s) && peek(s) != '\"') { if (chr(s, '\\')) { uint8_t o; if (chr(s, '\\')) { buf_append(s, '\\'); } else if (chr(s, '"')) { buf_append(s, '"'); } else if (chr(s, 'x') || chr(s, 'X')) { if (hex(s, &o)) buf_append(s, (char) o); else scanner_warn(s, "illegal hexadecimal escape sequence in string literal"); } else if (oct(s, &o)) { buf_append(s, (char) o); } else { scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s)); /* Ignore. */ } } else { buf_append(s, next(s)); } } if (!chr(s, '\"')) { scanner_err(s, "unterminated string literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "string literal is too long"); return TOK_ERROR; } if (!is_valid_utf8(s->buf, s->buf_pos - 1)) { scanner_err(s, "string literal is not a valid UTF-8 string"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_STRING; } /* Identifier or include. */ if (is_alpha(peek(s)) || peek(s) == '_') { s->buf_pos = 0; while (is_alnum(peek(s)) || peek(s) == '_') buf_append(s, next(s)); if (!buf_append(s, '\0')) { scanner_err(s, "identifier is too long"); return TOK_ERROR; } if (streq(s->buf, "include")) return TOK_INCLUDE; val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_IDENT; } /* Discard rest of line. */ skip_to_eol(s); scanner_err(s, "unrecognized token"); return TOK_ERROR; } Commit Message: compose: fix infinite loop in parser on some inputs The parser would enter an infinite loop if an unterminated keysym literal occurs at EOF. Found with the afl fuzzer. Signed-off-by: Ran Benita <ran234@gmail.com> CWE ID: CWE-835
lex(struct scanner *s, union lvalue *val) { skip_more_whitespace_and_comments: /* Skip spaces. */ while (is_space(peek(s))) if (next(s) == '\n') return TOK_END_OF_LINE; /* Skip comments. */ if (chr(s, '#')) { skip_to_eol(s); goto skip_more_whitespace_and_comments; } /* See if we're done. */ if (eof(s)) return TOK_END_OF_FILE; /* New token. */ s->token_line = s->line; s->token_column = s->column; s->buf_pos = 0; /* LHS Keysym. */ if (chr(s, '<')) { while (peek(s) != '>' && !eol(s) && !eof(s)) buf_append(s, next(s)); if (!chr(s, '>')) { scanner_err(s, "unterminated keysym literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "keysym literal is too long"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_LHS_KEYSYM; } /* Colon. */ if (chr(s, ':')) return TOK_COLON; if (chr(s, '!')) return TOK_BANG; if (chr(s, '~')) return TOK_TILDE; /* String literal. */ if (chr(s, '\"')) { while (!eof(s) && !eol(s) && peek(s) != '\"') { if (chr(s, '\\')) { uint8_t o; if (chr(s, '\\')) { buf_append(s, '\\'); } else if (chr(s, '"')) { buf_append(s, '"'); } else if (chr(s, 'x') || chr(s, 'X')) { if (hex(s, &o)) buf_append(s, (char) o); else scanner_warn(s, "illegal hexadecimal escape sequence in string literal"); } else if (oct(s, &o)) { buf_append(s, (char) o); } else { scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s)); /* Ignore. */ } } else { buf_append(s, next(s)); } } if (!chr(s, '\"')) { scanner_err(s, "unterminated string literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "string literal is too long"); return TOK_ERROR; } if (!is_valid_utf8(s->buf, s->buf_pos - 1)) { scanner_err(s, "string literal is not a valid UTF-8 string"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_STRING; } /* Identifier or include. */ if (is_alpha(peek(s)) || peek(s) == '_') { s->buf_pos = 0; while (is_alnum(peek(s)) || peek(s) == '_') buf_append(s, next(s)); if (!buf_append(s, '\0')) { scanner_err(s, "identifier is too long"); return TOK_ERROR; } if (streq(s->buf, "include")) return TOK_INCLUDE; val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_IDENT; } /* Discard rest of line. */ skip_to_eol(s); scanner_err(s, "unrecognized token"); return TOK_ERROR; }
169,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DataReductionProxyIOData::DataReductionProxyIOData( Client client, PrefService* prefs, network::NetworkConnectionTracker* network_connection_tracker, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, bool enabled, const std::string& user_agent, const std::string& channel) : client_(client), network_connection_tracker_(network_connection_tracker), io_task_runner_(io_task_runner), ui_task_runner_(ui_task_runner), enabled_(enabled), channel_(channel), effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { DCHECK(io_task_runner_); DCHECK(ui_task_runner_); configurator_.reset(new DataReductionProxyConfigurator()); configurator_->SetConfigUpdatedCallback(base::BindRepeating( &DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this))); DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr; std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config = std::make_unique<DataReductionProxyMutableConfigValues>(); raw_mutable_config = mutable_config.get(); config_.reset(new DataReductionProxyConfig( io_task_runner, ui_task_runner, network_connection_tracker_, std::move(mutable_config), configurator_.get())); request_options_.reset( new DataReductionProxyRequestOptions(client_, config_.get())); request_options_->Init(); request_options_->SetUpdateHeaderCallback(base::BindRepeating( &DataReductionProxyIOData::UpdateProxyRequestHeaders, base::Unretained(this))); config_client_.reset(new DataReductionProxyConfigServiceClient( GetBackoffPolicy(), request_options_.get(), raw_mutable_config, config_.get(), this, network_connection_tracker_, base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig, base::Unretained(this)))); network_properties_manager_.reset(new NetworkPropertiesManager( base::DefaultClock::GetInstance(), prefs, ui_task_runner_)); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
DataReductionProxyIOData::DataReductionProxyIOData( Client client, PrefService* prefs, network::NetworkConnectionTracker* network_connection_tracker, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, bool enabled, const std::string& user_agent, const std::string& channel) : client_(client), network_connection_tracker_(network_connection_tracker), io_task_runner_(io_task_runner), ui_task_runner_(ui_task_runner), enabled_(enabled), channel_(channel), effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { DCHECK(io_task_runner_); DCHECK(ui_task_runner_); configurator_.reset(new DataReductionProxyConfigurator()); configurator_->SetConfigUpdatedCallback(base::BindRepeating( &DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this))); DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr; std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config = std::make_unique<DataReductionProxyMutableConfigValues>(); raw_mutable_config = mutable_config.get(); config_.reset(new DataReductionProxyConfig( io_task_runner, ui_task_runner, network_connection_tracker_, std::move(mutable_config), configurator_.get())); request_options_.reset( new DataReductionProxyRequestOptions(client_, config_.get())); request_options_->Init(); request_options_->SetUpdateHeaderCallback(base::BindRepeating( &DataReductionProxyIOData::UpdateProxyRequestHeaders, base::Unretained(this))); if (!params::IsIncludedInHoldbackFieldTrial()) { config_client_.reset(new DataReductionProxyConfigServiceClient( GetBackoffPolicy(), request_options_.get(), raw_mutable_config, config_.get(), this, network_connection_tracker_, base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig, base::Unretained(this)))); } network_properties_manager_.reset(new NetworkPropertiesManager( base::DefaultClock::GetInstance(), prefs, ui_task_runner_)); }
172,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SHORT_SEC_SIZE(h) == len); (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + CDF_SHORT_SEC_POS(h, id), len); return len; } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (sst->sst_len < (size_t)id) { DPRINTF(("bad sector id %d > %d\n", id, sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; }
169,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { InputMethodDescriptors* descriptors = new InputMethodDescriptors; descriptors->push_back( input_method::GetFallbackInputMethodDescriptor()); return descriptors; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { input_method::InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { input_method::InputMethodDescriptors* descriptors = new input_method::InputMethodDescriptors; descriptors->push_back( input_method::GetFallbackInputMethodDescriptor()); return descriptors; }
170,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped"); gfx::PluginWindowHandle handle = GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id); if (handle != gfx::kNullPluginWindow) { RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params)); return; } base::ScopedClosureRunner scoped_completion_runner( base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id_, params.route_id, true /* alive */, false /* presented */)); int render_process_id = 0; int render_widget_id = 0; if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface( params.surface_id, &render_process_id, &render_widget_id)) { return; } RenderWidgetHelper* helper = RenderWidgetHelper::FromProcessHostID(render_process_id); if (!helper) return; scoped_completion_runner.Release(); helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped( render_widget_id, params.surface_id, params.surface_handle, params.route_id, params.size, host_id_)); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped"); gfx::PluginWindowHandle handle = GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id); if (handle != gfx::kNullPluginWindow) { RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params)); return; } base::ScopedClosureRunner scoped_completion_runner( base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id_, params.route_id, true /* alive */, params.surface_handle)); int render_process_id = 0; int render_widget_id = 0; if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface( params.surface_id, &render_process_id, &render_widget_id)) { return; } RenderWidgetHelper* helper = RenderWidgetHelper::FromProcessHostID(render_process_id); if (!helper) return; scoped_completion_runner.Release(); helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped( render_widget_id, params.surface_id, params.surface_handle, params.route_id, params.size, host_id_)); }
171,355
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle(iconv_handle, src, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } Commit Message: CWE ID: CWE-200
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; }
164,672