instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. 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_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; }
167,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udp_v6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; struct udphdr *uh; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi6 *fl6 = &inet->cork.fl.u.ip6; int err = 0; int is_udplite = IS_UDPLITE(sk); __wsum csum = 0; /* Grab the skbuff where UDP header space exists. */ if ((skb = skb_peek(&sk->sk_write_queue)) == NULL) goto out; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = fl6->fl6_sport; uh->dest = fl6->fl6_dport; uh->len = htons(up->len); uh->check = 0; if (is_udplite) csum = udplite_csum_outgoing(sk, skb); else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, up->len); goto send; } else csum = udp_csum_outgoing(sk, skb); /* add protocol-dependent pseudo-header */ uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr, up->len, fl6->flowi6_proto, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip6_push_pending_frames(sk); if (err) { if (err == -ENOBUFS && !inet6_sk(sk)->recverr) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); out: up->len = 0; up->pending = 0; return err; } Commit Message: ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data We accidentally call down to ip6_push_pending_frames when uncorking pending AF_INET data on a ipv6 socket. This results in the following splat (from Dave Jones): skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL> ------------[ cut here ]------------ kernel BUG at net/core/skbuff.c:126! invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth +netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37 task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000 RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65 RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282 RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006 RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520 RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800 R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800 FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600 Stack: ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4 ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6 ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0 Call Trace: [<ffffffff8159a9aa>] skb_push+0x3a/0x40 [<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0 [<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140 [<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0 [<ffffffff81694660>] ? udplite_getfrag+0x20/0x20 [<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0 [<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0 [<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40 [<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20 [<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0 [<ffffffff816f5d54>] tracesys+0xdd/0xe2 Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 RIP [<ffffffff816e759c>] skb_panic+0x63/0x65 RSP <ffff8801e6431de8> This patch adds a check if the pending data is of address family AF_INET and directly calls udp_push_ending_frames from udp_v6_push_pending_frames if that is the case. This bug was found by Dave Jones with trinity. (Also move the initialization of fl6 below the AF_INET check, even if not strictly necessary.) Cc: Dave Jones <[email protected]> Cc: YOSHIFUJI Hideaki <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int udp_v6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; struct udphdr *uh; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi6 *fl6; int err = 0; int is_udplite = IS_UDPLITE(sk); __wsum csum = 0; if (up->pending == AF_INET) return udp_push_pending_frames(sk); fl6 = &inet->cork.fl.u.ip6; /* Grab the skbuff where UDP header space exists. */ if ((skb = skb_peek(&sk->sk_write_queue)) == NULL) goto out; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = fl6->fl6_sport; uh->dest = fl6->fl6_dport; uh->len = htons(up->len); uh->check = 0; if (is_udplite) csum = udplite_csum_outgoing(sk, skb); else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, up->len); goto send; } else csum = udp_csum_outgoing(sk, skb); /* add protocol-dependent pseudo-header */ uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr, up->len, fl6->flowi6_proto, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip6_push_pending_frames(sk); if (err) { if (err == -ENOBUFS && !inet6_sk(sk)->recverr) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); out: up->len = 0; up->pending = 0; return err; }
166,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv) { int i; TSRMLS_FETCH(); if (parser && handler && !EG(exception)) { zval ***args; zval *retval; int result; zend_fcall_info fci; args = safe_emalloc(sizeof(zval **), argc, 0); for (i = 0; i < argc; i++) { args[i] = &argv[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = handler; fci.symbol_table = NULL; fci.object_ptr = parser->object; fci.retval_ptr_ptr = &retval; fci.param_count = argc; fci.params = args; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { zval **method; zval **obj; if (Z_TYPE_P(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler)); } else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler"); } for (i = 0; i < argc; i++) { zval_ptr_dtor(args[i]); } efree(args); if (result == FAILURE) { return NULL; } else { return EG(exception) ? NULL : retval; } } else { for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return NULL; } } Commit Message: CWE ID: CWE-119
static zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv) { int i; TSRMLS_FETCH(); if (parser && handler && !EG(exception)) { zval ***args; zval *retval; int result; zend_fcall_info fci; args = safe_emalloc(sizeof(zval **), argc, 0); for (i = 0; i < argc; i++) { args[i] = &argv[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = handler; fci.symbol_table = NULL; fci.object_ptr = parser->object; fci.retval_ptr_ptr = &retval; fci.param_count = argc; fci.params = args; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { zval **method; zval **obj; if (Z_TYPE_P(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler)); } else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler"); } for (i = 0; i < argc; i++) { zval_ptr_dtor(args[i]); } efree(args); if (result == FAILURE) { return NULL; } else { return EG(exception) ? NULL : retval; } } else { for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return NULL; } }
165,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, void *hba_private) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); SCSIRequest *req; SCSIDiskReq *r; req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private); r = DO_UPCAST(SCSIDiskReq, req, req); r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE); return req; } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, void *hba_private) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); SCSIRequest *req; req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private); return req; }
166,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_cr_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 _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. 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_cr_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 _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; }
167,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* 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) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { ValidateColormapValue(image,*p & mask,&index,exception); *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { ValidateColormapValue(image,(size_t) (x*map_length+ (*p & mask)),&index,exception); *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Reset memory for RLE decoder (patch provided by scarybeasts) CWE ID: CWE-200
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* 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) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { ValidateColormapValue(image,*p & mask,&index,exception); *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { ValidateColormapValue(image,(size_t) (x*map_length+ (*p & mask)),&index,exception); *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ASessionDescription::getFormatType( size_t index, unsigned long *PT, AString *desc, AString *params) const { AString format; getFormat(index, &format); const char *lastSpacePos = strrchr(format.c_str(), ' '); CHECK(lastSpacePos != NULL); char *end; unsigned long x = strtoul(lastSpacePos + 1, &end, 10); CHECK_GT(end, lastSpacePos + 1); CHECK_EQ(*end, '\0'); *PT = x; char key[20]; sprintf(key, "a=rtpmap:%lu", x); CHECK(findAttribute(index, key, desc)); sprintf(key, "a=fmtp:%lu", x); if (!findAttribute(index, key, params)) { params->clear(); } } Commit Message: Fix corruption via buffer overflow in mediaserver change unbound sprintf() to snprintf() so network-provided values can't overflow the buffers. Applicable to all K/L/M/N branches. Bug: 25747670 Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6 CWE ID: CWE-284
void ASessionDescription::getFormatType( size_t index, unsigned long *PT, AString *desc, AString *params) const { AString format; getFormat(index, &format); const char *lastSpacePos = strrchr(format.c_str(), ' '); CHECK(lastSpacePos != NULL); char *end; unsigned long x = strtoul(lastSpacePos + 1, &end, 10); CHECK_GT(end, lastSpacePos + 1); CHECK_EQ(*end, '\0'); *PT = x; char key[32]; snprintf(key, sizeof(key), "a=rtpmap:%lu", x); CHECK(findAttribute(index, key, desc)); snprintf(key, sizeof(key), "a=fmtp:%lu", x); if (!findAttribute(index, key, params)) { params->clear(); } }
173,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: native_handle* Parcel::readNativeHandle() const { int numFds, numInts; status_t err; err = readInt32(&numFds); if (err != NO_ERROR) return 0; err = readInt32(&numInts); if (err != NO_ERROR) return 0; native_handle* h = native_handle_create(numFds, numInts); for (int i=0 ; err==NO_ERROR && i<numFds ; i++) { h->data[i] = dup(readFileDescriptor()); if (h->data[i] < 0) err = BAD_VALUE; } err = read(h->data + numFds, sizeof(int)*numInts); if (err != NO_ERROR) { native_handle_close(h); native_handle_delete(h); h = 0; } return h; } Commit Message: Verify that the native handle was created The inputs to native_handle_create can cause an overflowed allocation, so check the return value of native_handle_create before accessing the memory it returns. Bug:19334482 Change-Id: I1f489382776c2a1390793a79dc27ea17baa9b2a2 (cherry picked from commit eaac99a7172da52a76ba48c26413778a74951b1a) CWE ID: CWE-189
native_handle* Parcel::readNativeHandle() const { int numFds, numInts; status_t err; err = readInt32(&numFds); if (err != NO_ERROR) return 0; err = readInt32(&numInts); if (err != NO_ERROR) return 0; native_handle* h = native_handle_create(numFds, numInts); if (!h) { return 0; } for (int i=0 ; err==NO_ERROR && i<numFds ; i++) { h->data[i] = dup(readFileDescriptor()); if (h->data[i] < 0) err = BAD_VALUE; } err = read(h->data + numFds, sizeof(int)*numInts); if (err != NO_ERROR) { native_handle_close(h); native_handle_delete(h); h = 0; } return h; }
173,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } convert_to_long_ex(item); stylearr[index++] = Z_LVAL_PP(item); } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } if (Z_TYPE_PP(item) != IS_LONG) { zval lval; lval = **item; zval_copy_ctor(&lval); convert_to_long(&lval); stylearr[index++] = Z_LVAL(lval); } else { stylearr[index++] = Z_LVAL_PP(item); } } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; }
166,425
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const user_manager::UserList UserSelectionScreen::PrepareUserListForSending( const user_manager::UserList& users, const AccountId& owner, bool is_signin_to_add) { user_manager::UserList users_to_send; bool has_owner = owner.is_valid(); size_t max_non_owner_users = has_owner ? kMaxUsers - 1 : kMaxUsers; size_t non_owner_count = 0; for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { bool is_owner = ((*it)->GetAccountId() == owner); bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); if ((is_public_account && !is_signin_to_add) || is_owner || (!is_public_account && non_owner_count < max_non_owner_users)) { if (!is_owner) ++non_owner_count; if (is_owner && users_to_send.size() > kMaxUsers) { users_to_send.insert(users_to_send.begin() + (kMaxUsers - 1), *it); while (users_to_send.size() > kMaxUsers) users_to_send.erase(users_to_send.begin() + kMaxUsers); } else if (users_to_send.size() < kMaxUsers) { users_to_send.push_back(*it); } } } return users_to_send; } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
const user_manager::UserList UserSelectionScreen::PrepareUserListForSending( const user_manager::UserList& users, const AccountId& owner, bool is_signin_to_add) { user_manager::UserList users_to_send; bool has_owner = owner.is_valid(); size_t max_non_owner_users = has_owner ? kMaxUsers - 1 : kMaxUsers; size_t non_owner_count = 0; for (user_manager::User* user : users) { bool is_owner = user->GetAccountId() == owner; bool is_public_account = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; if ((is_public_account && !is_signin_to_add) || is_owner || (!is_public_account && non_owner_count < max_non_owner_users)) { if (!is_owner) ++non_owner_count; if (is_owner && users_to_send.size() > kMaxUsers) { users_to_send.insert(users_to_send.begin() + (kMaxUsers - 1), user); while (users_to_send.size() > kMaxUsers) users_to_send.erase(users_to_send.begin() + kMaxUsers); } else if (users_to_send.size() < kMaxUsers) { users_to_send.push_back(user); } } } return users_to_send; }
172,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dhcpv4_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint8_t type, optlen; i = 0; while (i < length) { tlv = cp + i; type = (uint8_t)tlv[0]; optlen = (uint8_t)tlv[1]; value = tlv + 2; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 2 )); switch (type) { case DH4OPT_DNS_SERVERS: case DH4OPT_NTP_SERVERS: { if (optlen < 4 || optlen % 4 != 0) { return -1; } for (t = 0; t < optlen; t += 4) ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t))); } break; case DH4OPT_DOMAIN_SEARCH: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 2 + optlen; } return 0; } Commit Message: CVE-2017-13044/HNCP: add DHCPv4-Data bounds checks dhcpv4_print() in print-hncp.c had the same bug as dhcpv6_print(), apply a fix along the same lines. 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
dhcpv4_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint8_t type, optlen; i = 0; while (i < length) { if (i + 2 > length) return -1; tlv = cp + i; type = (uint8_t)tlv[0]; optlen = (uint8_t)tlv[1]; value = tlv + 2; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 2 )); if (i + 2 + optlen > length) return -1; switch (type) { case DH4OPT_DNS_SERVERS: case DH4OPT_NTP_SERVERS: { if (optlen < 4 || optlen % 4 != 0) { return -1; } for (t = 0; t < optlen; t += 4) ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t))); } break; case DH4OPT_DOMAIN_SEARCH: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 2 + optlen; } return 0; }
167,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int unshare_userns(unsigned long unshare_flags, struct cred **new_cred) { struct cred *cred; if (!(unshare_flags & CLONE_NEWUSER)) return 0; cred = prepare_creds(); if (!cred) return -ENOMEM; *new_cred = cred; return create_user_ns(cred); } Commit Message: userns: unshare_userns(&cred) should not populate cred on failure unshare_userns(new_cred) does *new_cred = prepare_creds() before create_user_ns() which can fail. However, the caller expects that it doesn't need to take care of new_cred if unshare_userns() fails. We could change the single caller, sys_unshare(), but I think it would be more clean to avoid the side effects on failure, so with this patch unshare_userns() does put_cred() itself and initializes *new_cred only if create_user_ns() succeeeds. Cc: [email protected] Signed-off-by: Oleg Nesterov <[email protected]> Reviewed-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
int unshare_userns(unsigned long unshare_flags, struct cred **new_cred) { struct cred *cred; int err = -ENOMEM; if (!(unshare_flags & CLONE_NEWUSER)) return 0; cred = prepare_creds(); if (cred) { err = create_user_ns(cred); if (err) put_cred(cred); else *new_cred = cred; } return err; }
166,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int piv_general_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[4096]; u8 *rbuf; size_t rbuflen; unsigned int cla_out, tag_out; const u8 *body; size_t bodylen; int find_len = 0; piv_private_data_t * priv = PIV_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } r = sc_lock(card); if (r != SC_SUCCESS) LOG_FUNC_RETURN(card->ctx, r); sc_format_apdu(card, &apdu, recvbuf ? SC_APDU_CASE_4_SHORT: SC_APDU_CASE_3_SHORT, ins, p1, p2); apdu.flags |= SC_APDU_FLAGS_CHAINING; /* if looking for length of object, dont try and read the rest of buffer here */ if (rbuflen == 8 && card->reader->active_protocol == SC_PROTO_T1) { apdu.flags |= SC_APDU_FLAGS_NO_GET_RESP; find_len = 1; } apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 256) ? 256 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_log(card->ctx, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_log(card->ctx, "DEE r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_log(card->ctx, "Transmit failed"); goto err; } if (!(find_len && apdu.sw1 == 0x61)) r = sc_check_sw(card, apdu.sw1, apdu.sw2); /* TODO: - DEE look later at tag vs size read too */ if (r < 0) { sc_log(card->ctx, "Card returned error "); goto err; } /* * See how much we read and make sure it is asn1 * if not, return 0 indicating no data found */ rbuflen = 0; /* in case rseplen < 3 i.e. not parseable */ /* we may only be using get data to test the security status of the card, so zero length is OK */ if ( recvbuflen && recvbuf && apdu.resplen > 3 && priv->pin_cmd_noparse != 1) { *recvbuflen = 0; /* we should have all the tag data, so we have to tell sc_asn1_find_tag * the buffer is bigger, so it will not produce "ASN1.tag too long!" */ body = rbuf; if (sc_asn1_read_tag(&body, 0xffff, &cla_out, &tag_out, &bodylen) != SC_SUCCESS || body == NULL) { /* only early beta cards had this problem */ sc_log(card->ctx, "***** received buffer tag MISSING "); body = rbuf; /* some readers/cards might return 6c 00 */ if (apdu.sw1 == 0x61 || apdu.sw2 == 0x6c ) bodylen = 12000; else bodylen = apdu.resplen; } rbuflen = body - rbuf + bodylen; /* if using internal buffer, alloc new one */ if (rbuf == rbufinitbuf) { *recvbuf = malloc(rbuflen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, rbuflen); /* copy tag too */ } } if (recvbuflen) { *recvbuflen = rbuflen; r = *recvbuflen; } err: sc_unlock(card); LOG_FUNC_RETURN(card->ctx, r); } 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
static int piv_general_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[4096]; u8 *rbuf; size_t rbuflen; unsigned int cla_out, tag_out; const u8 *body; size_t bodylen; int find_len = 0; piv_private_data_t * priv = PIV_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } r = sc_lock(card); if (r != SC_SUCCESS) LOG_FUNC_RETURN(card->ctx, r); sc_format_apdu(card, &apdu, recvbuf ? SC_APDU_CASE_4_SHORT: SC_APDU_CASE_3_SHORT, ins, p1, p2); apdu.flags |= SC_APDU_FLAGS_CHAINING; /* if looking for length of object, dont try and read the rest of buffer here */ if (rbuflen == 8 && card->reader->active_protocol == SC_PROTO_T1) { apdu.flags |= SC_APDU_FLAGS_NO_GET_RESP; find_len = 1; } apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 256) ? 256 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_log(card->ctx, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_log(card->ctx, "DEE r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_log(card->ctx, "Transmit failed"); goto err; } if (!(find_len && apdu.sw1 == 0x61)) r = sc_check_sw(card, apdu.sw1, apdu.sw2); /* TODO: - DEE look later at tag vs size read too */ if (r < 0) { sc_log(card->ctx, "Card returned error "); goto err; } /* * See how much we read and make sure it is asn1 * if not, return 0 indicating no data found */ rbuflen = 0; /* in case rseplen < 3 i.e. not parseable */ /* we may only be using get data to test the security status of the card, so zero length is OK */ if ( recvbuflen && recvbuf && apdu.resplen > 3 && priv->pin_cmd_noparse != 1) { *recvbuflen = 0; /* we should have all the tag data, so we have to tell sc_asn1_find_tag * the buffer is bigger, so it will not produce "ASN1.tag too long!" */ body = rbuf; if (sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen) != SC_SUCCESS || body == NULL) { /* only early beta cards had this problem */ sc_log(card->ctx, "***** received buffer tag MISSING "); body = rbuf; /* some readers/cards might return 6c 00 */ if (apdu.sw1 == 0x61 || apdu.sw2 == 0x6c ) bodylen = 12000; else bodylen = apdu.resplen; } rbuflen = body - rbuf + bodylen; /* if using internal buffer, alloc new one */ if (rbuf == rbufinitbuf) { *recvbuf = malloc(rbuflen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, rbuflen); /* copy tag too */ } } if (recvbuflen) { *recvbuflen = rbuflen; r = *recvbuflen; } err: sc_unlock(card); LOG_FUNC_RETURN(card->ctx, r); }
169,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation( ResourceTimingInfo* info) { if (IsDetached()) return false; if (!GetFrame()->Owner()) return false; if (!GetFrame()->should_send_resource_timing_info_to_parent()) return false; if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward) return false; return true; } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation( ResourceTimingInfo* info) { if (IsDetached()) return false; if (!GetFrame()->Owner()) return false; if (!GetFrame()->should_send_resource_timing_info_to_parent()) return false; // location may have been changed after initial navigation, if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward) { // ...and do not report subsequent navigations in the iframe too. GetFrame()->SetShouldSendResourceTimingInfoToParent(false); return false; } return true; }
172,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DataReductionProxySettings::DataReductionProxySettings() : unreachable_(false), deferred_initialization_(false), prefs_(nullptr), config_(nullptr), clock_(base::DefaultClock::GetInstance()) {} Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
DataReductionProxySettings::DataReductionProxySettings() : unreachable_(false), deferred_initialization_(false), prefs_(nullptr), config_(nullptr), clock_(base::DefaultClock::GetInstance()) {}
172,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev) { struct net_device *rcv = NULL; struct veth_priv *priv, *rcv_priv; struct veth_net_stats *stats, *rcv_stats; int length; priv = netdev_priv(dev); rcv = priv->peer; rcv_priv = netdev_priv(rcv); stats = this_cpu_ptr(priv->stats); rcv_stats = this_cpu_ptr(rcv_priv->stats); if (!(rcv->flags & IFF_UP)) goto tx_drop; if (dev->features & NETIF_F_NO_CSUM) skb->ip_summed = rcv_priv->ip_summed; length = skb->len + ETH_HLEN; if (dev_forward_skb(rcv, skb) != NET_RX_SUCCESS) goto rx_drop; stats->tx_bytes += length; stats->tx_packets++; rcv_stats->rx_bytes += length; rcv_stats->rx_packets++; return NETDEV_TX_OK; tx_drop: kfree_skb(skb); stats->tx_dropped++; return NETDEV_TX_OK; rx_drop: kfree_skb(skb); rcv_stats->rx_dropped++; return NETDEV_TX_OK; } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev) { struct net_device *rcv = NULL; struct veth_priv *priv, *rcv_priv; struct veth_net_stats *stats, *rcv_stats; int length; priv = netdev_priv(dev); rcv = priv->peer; rcv_priv = netdev_priv(rcv); stats = this_cpu_ptr(priv->stats); rcv_stats = this_cpu_ptr(rcv_priv->stats); if (!(rcv->flags & IFF_UP)) goto tx_drop; if (dev->features & NETIF_F_NO_CSUM) skb->ip_summed = rcv_priv->ip_summed; length = skb->len + ETH_HLEN; if (dev_forward_skb(rcv, skb) != NET_RX_SUCCESS) goto rx_drop; stats->tx_bytes += length; stats->tx_packets++; rcv_stats->rx_bytes += length; rcv_stats->rx_packets++; return NETDEV_TX_OK; tx_drop: kfree_skb(skb); stats->tx_dropped++; return NETDEV_TX_OK; rx_drop: rcv_stats->rx_dropped++; return NETDEV_TX_OK; }
166,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FragmentPaintPropertyTreeBuilder::UpdateInnerBorderRadiusClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsInnerBorderRadiusClip(object_)) { const LayoutBox& box = ToLayoutBox(object_); ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; if (box.IsLayoutReplaced()) { state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor( LayoutRect(context_.current.paint_offset, box.Size()), LayoutRectOutsets(-(box.PaddingTop() + box.BorderTop()), -(box.PaddingRight() + box.BorderRight()), -(box.PaddingBottom() + box.BorderBottom()), -(box.PaddingLeft() + box.BorderLeft()))); } else { state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor( LayoutRect(context_.current.paint_offset, box.Size())); } OnUpdateClip(properties_->UpdateInnerBorderRadiusClip( context_.current.clip, std::move(state))); } else { OnClearClip(properties_->ClearInnerBorderRadiusClip()); } } if (auto* border_radius_clip = properties_->InnerBorderRadiusClip()) context_.current.clip = border_radius_clip; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void FragmentPaintPropertyTreeBuilder::UpdateInnerBorderRadiusClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsInnerBorderRadiusClip(object_)) { const LayoutBox& box = ToLayoutBox(object_); ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; if (box.IsLayoutReplaced()) { state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor( LayoutRect(context_.current.paint_offset, box.Size()), LayoutRectOutsets(-(box.PaddingTop() + box.BorderTop()), -(box.PaddingRight() + box.BorderRight()), -(box.PaddingBottom() + box.BorderBottom()), -(box.PaddingLeft() + box.BorderLeft()))); } else { state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor( LayoutRect(context_.current.paint_offset, box.Size())); } OnUpdateClip(properties_->UpdateInnerBorderRadiusClip( *context_.current.clip, std::move(state))); } else { OnClearClip(properties_->ClearInnerBorderRadiusClip()); } } if (auto* border_radius_clip = properties_->InnerBorderRadiusClip()) context_.current.clip = border_radius_clip; }
171,798
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void perf_tp_event(u64 addr, u64 count, void *record, int entry_size, struct pt_regs *regs, struct hlist_head *head, int rctx) { struct perf_sample_data data; struct perf_event *event; struct hlist_node *node; struct perf_raw_record raw = { .size = entry_size, .data = record, }; perf_sample_data_init(&data, addr); data.raw = &raw; hlist_for_each_entry_rcu(event, node, head, hlist_entry) { if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, 1, &data, regs); } perf_swevent_put_recursion_context(rctx); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
void perf_tp_event(u64 addr, u64 count, void *record, int entry_size, struct pt_regs *regs, struct hlist_head *head, int rctx) { struct perf_sample_data data; struct perf_event *event; struct hlist_node *node; struct perf_raw_record raw = { .size = entry_size, .data = record, }; perf_sample_data_init(&data, addr); data.raw = &raw; hlist_for_each_entry_rcu(event, node, head, hlist_entry) { if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } perf_swevent_put_recursion_context(rctx); }
165,840
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n, len; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the rose frame start */ memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); len = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1; len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1; if (!rose_parse_facilities(skb->data + len + 4, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); /* * We can't accept the Call Request. */ if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; } Commit Message: rose: Add length checks to CALL_REQUEST parsing Define some constant offsets for CALL_REQUEST based on the description at <http://www.techfest.com/networking/wan/x25plp.htm> and the definition of ROSE as using 10-digit (5-byte) addresses. Use them consistently. Validate all implicit and explicit facilities lengths. Validate the address length byte rather than either trusting or assuming its value. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the rose frame start */ memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); if (!rose_parse_facilities(skb->data + ROSE_CALL_REQ_FACILITIES_OFF, skb->len - ROSE_CALL_REQ_FACILITIES_OFF, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); /* * We can't accept the Call Request. */ if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; }
165,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void IOHandler::Read( const std::string& handle, Maybe<int> offset, Maybe<int> max_size, std::unique_ptr<ReadCallback> callback) { static const size_t kDefaultChunkSize = 10 * 1024 * 1024; static const char kBlobPrefix[] = "blob:"; scoped_refptr<DevToolsIOContext::ROStream> stream = io_context_->GetByHandle(handle); if (!stream && process_host_ && StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) { BrowserContext* browser_context = process_host_->GetBrowserContext(); ChromeBlobStorageContext* blob_context = ChromeBlobStorageContext::GetFor(browser_context); StoragePartition* storage_partition = process_host_->GetStoragePartition(); std::string uuid = handle.substr(strlen(kBlobPrefix)); stream = io_context_->OpenBlob(blob_context, storage_partition, handle, uuid); } if (!stream) { callback->sendFailure(Response::InvalidParams("Invalid stream handle")); return; } stream->Read( offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize), base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(), base::Passed(std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void IOHandler::Read( const std::string& handle, Maybe<int> offset, Maybe<int> max_size, std::unique_ptr<ReadCallback> callback) { static const size_t kDefaultChunkSize = 10 * 1024 * 1024; static const char kBlobPrefix[] = "blob:"; scoped_refptr<DevToolsIOContext::ROStream> stream = io_context_->GetByHandle(handle); if (!stream && browser_context_ && StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) { ChromeBlobStorageContext* blob_context = ChromeBlobStorageContext::GetFor(browser_context_); std::string uuid = handle.substr(strlen(kBlobPrefix)); stream = io_context_->OpenBlob(blob_context, storage_partition_, handle, uuid); } if (!stream) { callback->sendFailure(Response::InvalidParams("Invalid stream handle")); return; } stream->Read( offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize), base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(), base::Passed(std::move(callback)))); }
172,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if(cc%(bps*stride)!=0) { TIFFErrorExt(tif->tif_clientdata, "fpAcc", "%s", "cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); return 1; }
166,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int equalizer_get_parameter(effect_context_t *context, effect_param_t *p, uint32_t *size) { equalizer_context_t *eq_ctxt = (equalizer_context_t *)context; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); int32_t *param_tmp = (int32_t *)p->data; int32_t param = *param_tmp++; int32_t param2; char *name; void *value = p->data + voffset; int i; ALOGV("%s", __func__); p->status = 0; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (p->vsize < sizeof(int16_t)) p->status = -EINVAL; p->vsize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (p->vsize < 2 * sizeof(int16_t)) p->status = -EINVAL; p->vsize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (p->vsize < 2 * sizeof(int32_t)) p->status = -EINVAL; p->vsize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (p->vsize < sizeof(int32_t)) p->status = -EINVAL; p->vsize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (p->vsize < (2 + NUM_EQ_BANDS) * sizeof(uint16_t)) p->status = -EINVAL; p->vsize = (2 + NUM_EQ_BANDS) * sizeof(uint16_t); break; default: p->status = -EINVAL; } *size = sizeof(effect_param_t) + voffset + p->vsize; if (p->status != 0) return 0; switch (param) { case EQ_PARAM_NUM_BANDS: ALOGV("%s: EQ_PARAM_NUM_BANDS", __func__); *(uint16_t *)value = (uint16_t)NUM_EQ_BANDS; break; case EQ_PARAM_LEVEL_RANGE: ALOGV("%s: EQ_PARAM_LEVEL_RANGE", __func__); *(int16_t *)value = -1500; *((int16_t *)value + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: ALOGV("%s: EQ_PARAM_BAND_LEVEL", __func__); param2 = *param_tmp; if (param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; break; } *(int16_t *)value = (int16_t)equalizer_get_band_level(eq_ctxt, param2); break; case EQ_PARAM_CENTER_FREQ: ALOGV("%s: EQ_PARAM_CENTER_FREQ", __func__); param2 = *param_tmp; if (param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; break; } *(int32_t *)value = equalizer_get_center_frequency(eq_ctxt, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: ALOGV("%s: EQ_PARAM_BAND_FREQ_RANGE", __func__); param2 = *param_tmp; if (param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; break; } equalizer_get_band_freq_range(eq_ctxt, param2, (uint32_t *)value, ((uint32_t *)value + 1)); break; case EQ_PARAM_GET_BAND: ALOGV("%s: EQ_PARAM_GET_BAND", __func__); param2 = *param_tmp; *(uint16_t *)value = (uint16_t)equalizer_get_band(eq_ctxt, param2); break; case EQ_PARAM_CUR_PRESET: ALOGV("%s: EQ_PARAM_CUR_PRESET", __func__); *(uint16_t *)value = (uint16_t)equalizer_get_preset(eq_ctxt); break; case EQ_PARAM_GET_NUM_OF_PRESETS: ALOGV("%s: EQ_PARAM_GET_NUM_OF_PRESETS", __func__); *(uint16_t *)value = (uint16_t)equalizer_get_num_presets(eq_ctxt); break; case EQ_PARAM_GET_PRESET_NAME: ALOGV("%s: EQ_PARAM_GET_PRESET_NAME", __func__); param2 = *param_tmp; ALOGV("param2: %d", param2); if (param2 >= equalizer_get_num_presets(eq_ctxt)) { p->status = -EINVAL; break; } name = (char *)value; strlcpy(name, equalizer_get_preset_name(eq_ctxt, param2), p->vsize - 1); name[p->vsize - 1] = 0; p->vsize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { ALOGV("%s: EQ_PARAM_PROPERTIES", __func__); int16_t *prop = (int16_t *)value; prop[0] = (int16_t)equalizer_get_preset(eq_ctxt); prop[1] = (int16_t)NUM_EQ_BANDS; for (i = 0; i < NUM_EQ_BANDS; i++) { prop[2 + i] = (int16_t)equalizer_get_band_level(eq_ctxt, i); } } break; default: p->status = -EINVAL; break; } return 0; } Commit Message: Fix security vulnerability: Equalizer command might allow negative indexes Bug: 32247948 Bug: 32438598 Bug: 32436341 Test: use POC on bug or cts security test Change-Id: I56a92582687599b5b313dea1abcb8bcb19c7fc0e (cherry picked from commit 3f37d4ef89f4f0eef9e201c5a91b7b2c77ed1071) (cherry picked from commit ceb7b2d7a4c4cb8d03f166c61f5c7551c6c760aa) CWE ID: CWE-200
int equalizer_get_parameter(effect_context_t *context, effect_param_t *p, uint32_t *size) { equalizer_context_t *eq_ctxt = (equalizer_context_t *)context; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); int32_t *param_tmp = (int32_t *)p->data; int32_t param = *param_tmp++; int32_t param2; char *name; void *value = p->data + voffset; int i; ALOGV("%s", __func__); p->status = 0; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (p->vsize < sizeof(int16_t)) p->status = -EINVAL; p->vsize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (p->vsize < 2 * sizeof(int16_t)) p->status = -EINVAL; p->vsize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (p->vsize < 2 * sizeof(int32_t)) p->status = -EINVAL; p->vsize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (p->vsize < sizeof(int32_t)) p->status = -EINVAL; p->vsize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (p->vsize < (2 + NUM_EQ_BANDS) * sizeof(uint16_t)) p->status = -EINVAL; p->vsize = (2 + NUM_EQ_BANDS) * sizeof(uint16_t); break; default: p->status = -EINVAL; } *size = sizeof(effect_param_t) + voffset + p->vsize; if (p->status != 0) return 0; switch (param) { case EQ_PARAM_NUM_BANDS: ALOGV("%s: EQ_PARAM_NUM_BANDS", __func__); *(uint16_t *)value = (uint16_t)NUM_EQ_BANDS; break; case EQ_PARAM_LEVEL_RANGE: ALOGV("%s: EQ_PARAM_LEVEL_RANGE", __func__); *(int16_t *)value = -1500; *((int16_t *)value + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: ALOGV("%s: EQ_PARAM_BAND_LEVEL", __func__); param2 = *param_tmp; if (param2 < 0 || param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32438598"); ALOGW("\tERROR EQ_PARAM_BAND_LEVEL band %d", param2); } break; } *(int16_t *)value = (int16_t)equalizer_get_band_level(eq_ctxt, param2); break; case EQ_PARAM_CENTER_FREQ: ALOGV("%s: EQ_PARAM_CENTER_FREQ", __func__); param2 = *param_tmp; if (param2 < 0 || param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32436341"); ALOGW("\tERROR EQ_PARAM_CENTER_FREQ band %d", param2); } break; } *(int32_t *)value = equalizer_get_center_frequency(eq_ctxt, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: ALOGV("%s: EQ_PARAM_BAND_FREQ_RANGE", __func__); param2 = *param_tmp; if (param2 < 0 || param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32247948"); ALOGW("\tERROR EQ_PARAM_BAND_FREQ_RANGE band %d", param2); } break; } equalizer_get_band_freq_range(eq_ctxt, param2, (uint32_t *)value, ((uint32_t *)value + 1)); break; case EQ_PARAM_GET_BAND: ALOGV("%s: EQ_PARAM_GET_BAND", __func__); param2 = *param_tmp; *(uint16_t *)value = (uint16_t)equalizer_get_band(eq_ctxt, param2); break; case EQ_PARAM_CUR_PRESET: ALOGV("%s: EQ_PARAM_CUR_PRESET", __func__); *(uint16_t *)value = (uint16_t)equalizer_get_preset(eq_ctxt); break; case EQ_PARAM_GET_NUM_OF_PRESETS: ALOGV("%s: EQ_PARAM_GET_NUM_OF_PRESETS", __func__); *(uint16_t *)value = (uint16_t)equalizer_get_num_presets(eq_ctxt); break; case EQ_PARAM_GET_PRESET_NAME: ALOGV("%s: EQ_PARAM_GET_PRESET_NAME", __func__); param2 = *param_tmp; ALOGV("param2: %d", param2); if (param2 >= equalizer_get_num_presets(eq_ctxt)) { p->status = -EINVAL; break; } name = (char *)value; strlcpy(name, equalizer_get_preset_name(eq_ctxt, param2), p->vsize - 1); name[p->vsize - 1] = 0; p->vsize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { ALOGV("%s: EQ_PARAM_PROPERTIES", __func__); int16_t *prop = (int16_t *)value; prop[0] = (int16_t)equalizer_get_preset(eq_ctxt); prop[1] = (int16_t)NUM_EQ_BANDS; for (i = 0; i < NUM_EQ_BANDS; i++) { prop[2 + i] = (int16_t)equalizer_get_band_level(eq_ctxt, i); } } break; default: p->status = -EINVAL; break; } return 0; }
174,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GraphicsContext::clip(const Path& path) { #ifdef __WXMAC__ if (paintingDisabled()) return; wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); CGContextRef context = (CGContextRef)gc->GetNativeContext(); if (!context) return; CGPathRef nativePath = (CGPathRef)path.platformPath()->GetNativePath(); if (path.isEmpty()) CGContextClipToRect(context, CGRectZero); else if (nativePath) { CGContextBeginPath(context); CGContextAddPath(context, nativePath); CGContextClip(context); } #else notImplemented(); #endif } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::clip(const Path& path) { if (paintingDisabled()) return; // if the path is empty, we clip against a zero rect to reduce the clipping region to // nothing - which is the intended behavior of clip() if the path is empty. if (path.isEmpty()) m_data->context->SetClippingRegion(0, 0, 0, 0); else clipPath(path, RULE_NONZERO); }
170,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264
check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
167,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_letterSpacing(font->letterSpacing()) { } Commit Message: Fix uninitialized variables in HarfBuzzShaperBase https://bugs.webkit.org/show_bug.cgi?id=79546 Reviewed by Dirk Pranke. These were introduced in r108733. * platform/graphics/harfbuzz/HarfBuzzShaperBase.cpp: (WebCore::HarfBuzzShaperBase::HarfBuzzShaperBase): git-svn-id: svn://svn.chromium.org/blink/trunk@108871 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362
HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_normalizedBufferLength(0) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_padding(0) , m_padPerWordBreak(0) , m_padError(0) , m_letterSpacing(font->letterSpacing()) { }
170,964
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *my_asctime(time_t t) { struct tm *tm; char *str; int len; tm = localtime(&t); str = g_strdup(asctime(tm)); len = strlen(str); if (len > 0) str[len-1] = '\0'; return str; } Commit Message: Merge branch 'security' into 'master' Security Closes #10 See merge request !17 CWE ID: CWE-416
char *my_asctime(time_t t) { struct tm *tm; char *str; int len; tm = localtime(&t); if (tm == NULL) return g_strdup("???"); str = g_strdup(asctime(tm)); len = strlen(str); if (len > 0) str[len-1] = '\0'; return str; }
168,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_syscall_exit(void *ignore, struct pt_regs *regs, long ret) { struct syscall_metadata *sys_data; struct syscall_trace_exit *rec; struct hlist_head *head; int syscall_nr; int rctx; int size; syscall_nr = trace_get_syscall_nr(current, regs); if (syscall_nr < 0) return; if (!test_bit(syscall_nr, enabled_perf_exit_syscalls)) return; sys_data = syscall_nr_to_meta(syscall_nr); if (!sys_data) return; head = this_cpu_ptr(sys_data->exit_event->perf_events); if (hlist_empty(head)) return; /* We can probably do that at build time */ size = ALIGN(sizeof(*rec) + sizeof(u32), sizeof(u64)); size -= sizeof(u32); rec = (struct syscall_trace_exit *)perf_trace_buf_prepare(size, sys_data->exit_event->event.type, regs, &rctx); if (!rec) return; rec->nr = syscall_nr; rec->ret = syscall_get_return_value(current, regs); perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL); } Commit Message: tracing/syscalls: Ignore numbers outside NR_syscalls' range ARM has some private syscalls (for example, set_tls(2)) which lie outside the range of NR_syscalls. If any of these are called while syscall tracing is being performed, out-of-bounds array access will occur in the ftrace and perf sys_{enter,exit} handlers. # trace-cmd record -e raw_syscalls:* true && trace-cmd report ... true-653 [000] 384.675777: sys_enter: NR 192 (0, 1000, 3, 4000022, ffffffff, 0) true-653 [000] 384.675812: sys_exit: NR 192 = 1995915264 true-653 [000] 384.675971: sys_enter: NR 983045 (76f74480, 76f74000, 76f74b28, 76f74480, 76f76f74, 1) true-653 [000] 384.675988: sys_exit: NR 983045 = 0 ... # trace-cmd record -e syscalls:* true [ 17.289329] Unable to handle kernel paging request at virtual address aaaaaace [ 17.289590] pgd = 9e71c000 [ 17.289696] [aaaaaace] *pgd=00000000 [ 17.289985] Internal error: Oops: 5 [#1] PREEMPT SMP ARM [ 17.290169] Modules linked in: [ 17.290391] CPU: 0 PID: 704 Comm: true Not tainted 3.18.0-rc2+ #21 [ 17.290585] task: 9f4dab00 ti: 9e710000 task.ti: 9e710000 [ 17.290747] PC is at ftrace_syscall_enter+0x48/0x1f8 [ 17.290866] LR is at syscall_trace_enter+0x124/0x184 Fix this by ignoring out-of-NR_syscalls-bounds syscall numbers. Commit cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls" added the check for less than zero, but it should have also checked for greater than NR_syscalls. Link: http://lkml.kernel.org/p/[email protected] Fixes: cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls" Cc: [email protected] # 2.6.33+ Signed-off-by: Rabin Vincent <[email protected]> Signed-off-by: Steven Rostedt <[email protected]> CWE ID: CWE-264
static void perf_syscall_exit(void *ignore, struct pt_regs *regs, long ret) { struct syscall_metadata *sys_data; struct syscall_trace_exit *rec; struct hlist_head *head; int syscall_nr; int rctx; int size; syscall_nr = trace_get_syscall_nr(current, regs); if (syscall_nr < 0 || syscall_nr >= NR_syscalls) return; if (!test_bit(syscall_nr, enabled_perf_exit_syscalls)) return; sys_data = syscall_nr_to_meta(syscall_nr); if (!sys_data) return; head = this_cpu_ptr(sys_data->exit_event->perf_events); if (hlist_empty(head)) return; /* We can probably do that at build time */ size = ALIGN(sizeof(*rec) + sizeof(u32), sizeof(u64)); size -= sizeof(u32); rec = (struct syscall_trace_exit *)perf_trace_buf_prepare(size, sys_data->exit_event->event.type, regs, &rctx); if (!rec) return; rec->nr = syscall_nr; rec->ret = syscall_get_return_value(current, regs); perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL); }
166,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = l2t_send(tdev, skb, l2e); if (error < 0) kfree_skb(skb); return error; } Commit Message: iw_cxgb3: Fix incorrectly returning error on success The cxgb3_*_send() functions return NET_XMIT_ values, which are positive integers values. So don't treat positive return values as an error. Signed-off-by: Steve Wise <[email protected]> Signed-off-by: Hariprasad Shenai <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID:
static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = l2t_send(tdev, skb, l2e); if (error < 0) kfree_skb(skb); return error < 0 ? error : 0; }
167,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope& worker, const String& url, ExceptionState& exceptionState) { KURL completedURL = worker.completeURL(url); ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } if (!completedURL.isValid()) { exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid."); return 0; } RefPtr<EntrySyncCallbackHelper> resolveURLHelper = EntrySyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper->successCallback(), resolveURLHelper->errorCallback(), &worker); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->resolveURL(&worker, completedURL, callbacks.release()); return resolveURLHelper->getResult(exceptionState); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope& worker, const String& url, ExceptionState& exceptionState) { KURL completedURL = worker.completeURL(url); ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } if (!completedURL.isValid()) { exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid."); return 0; } EntrySyncCallbackHelper* resolveURLHelper = EntrySyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper->successCallback(), resolveURLHelper->errorCallback(), &worker); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->resolveURL(&worker, completedURL, callbacks.release()); return resolveURLHelper->getResult(exceptionState); }
171,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet_request_sock *ireq; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif if (sk_acceptq_is_full(sk)) goto exit_overflow; if (!dst && (dst = inet_csk_route_req(sk, req)) == NULL) goto exit; newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto exit_nonewsk; newsk->sk_gso_type = SKB_GSO_TCPV4; sk_setup_caps(newsk, dst); newtp = tcp_sk(newsk); newinet = inet_sk(newsk); ireq = inet_rsk(req); newinet->inet_daddr = ireq->rmt_addr; newinet->inet_rcv_saddr = ireq->loc_addr; newinet->inet_saddr = ireq->loc_addr; newinet->opt = ireq->opt; ireq->opt = NULL; newinet->mc_index = inet_iif(skb); newinet->mc_ttl = ip_hdr(skb)->ttl; inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newinet->opt) inet_csk(newsk)->icsk_ext_hdr_len = newinet->opt->optlen; newinet->inet_id = newtp->write_seq ^ jiffies; tcp_mtup_init(newsk); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); if (tcp_sk(sk)->rx_opt.user_mss && tcp_sk(sk)->rx_opt.user_mss < newtp->advmss) newtp->advmss = tcp_sk(sk)->rx_opt.user_mss; tcp_initialize_rcv_mss(newsk); #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v4_md5_do_lookup(sk, newinet->inet_daddr); if (key != NULL) { /* * We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC); if (newkey != NULL) tcp_v4_md5_do_add(newsk, newinet->inet_daddr, newkey, key->keylen); sk_nocaps_add(newsk, NETIF_F_GSO_MASK); } #endif if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto exit; } __inet_hash_nolisten(newsk, NULL); return newsk; exit_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); exit_nonewsk: dst_release(dst); exit: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet_request_sock *ireq; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct ip_options_rcu *inet_opt; if (sk_acceptq_is_full(sk)) goto exit_overflow; if (!dst && (dst = inet_csk_route_req(sk, req)) == NULL) goto exit; newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto exit_nonewsk; newsk->sk_gso_type = SKB_GSO_TCPV4; sk_setup_caps(newsk, dst); newtp = tcp_sk(newsk); newinet = inet_sk(newsk); ireq = inet_rsk(req); newinet->inet_daddr = ireq->rmt_addr; newinet->inet_rcv_saddr = ireq->loc_addr; newinet->inet_saddr = ireq->loc_addr; inet_opt = ireq->opt; rcu_assign_pointer(newinet->inet_opt, inet_opt); ireq->opt = NULL; newinet->mc_index = inet_iif(skb); newinet->mc_ttl = ip_hdr(skb)->ttl; inet_csk(newsk)->icsk_ext_hdr_len = 0; if (inet_opt) inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen; newinet->inet_id = newtp->write_seq ^ jiffies; tcp_mtup_init(newsk); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); if (tcp_sk(sk)->rx_opt.user_mss && tcp_sk(sk)->rx_opt.user_mss < newtp->advmss) newtp->advmss = tcp_sk(sk)->rx_opt.user_mss; tcp_initialize_rcv_mss(newsk); #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v4_md5_do_lookup(sk, newinet->inet_daddr); if (key != NULL) { /* * We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC); if (newkey != NULL) tcp_v4_md5_do_add(newsk, newinet->inet_daddr, newkey, key->keylen); sk_nocaps_add(newsk, NETIF_F_GSO_MASK); } #endif if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto exit; } __inet_hash_nolisten(newsk, NULL); return newsk; exit_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); exit_nonewsk: dst_release(dst); exit: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }
165,572
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *url_decode_r(char *to, char *url, size_t size) { char *s = url, // source *d = to, // destination *e = &to[size - 1]; // destination end while(*s && d < e) { if(unlikely(*s == '%')) { if(likely(s[1] && s[2])) { *d++ = from_hex(s[1]) << 4 | from_hex(s[2]); s += 2; } } else if(unlikely(*s == '+')) *d++ = ' '; else *d++ = *s; s++; } *d = '\0'; return to; } Commit Message: fixed vulnerabilities identified by red4sec.com (#4521) CWE ID: CWE-200
char *url_decode_r(char *to, char *url, size_t size) { char *s = url, // source *d = to, // destination *e = &to[size - 1]; // destination end while(*s && d < e) { if(unlikely(*s == '%')) { if(likely(s[1] && s[2])) { char t = from_hex(s[1]) << 4 | from_hex(s[2]); // avoid HTTP header injection *d++ = (char)((isprint(t))? t : ' '); s += 2; } } else if(unlikely(*s == '+')) *d++ = ' '; else *d++ = *s; s++; } *d = '\0'; return to; }
169,812
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int proc_keys_show(struct seq_file *m, void *v) { struct rb_node *_p = v; struct key *key = rb_entry(_p, struct key, serial_node); struct timespec now; unsigned long timo; key_ref_t key_ref, skey_ref; char xbuf[16]; int rc; struct keyring_search_context ctx = { .index_key.type = key->type, .index_key.description = key->description, .cred = m->file->f_cred, .match_data.cmp = lookup_user_key_possessed, .match_data.raw_data = key, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; key_ref = make_key_ref(key, 0); /* determine if the key is possessed by this process (a test we can * skip if the key does not indicate the possessor can view it */ if (key->perm & KEY_POS_VIEW) { skey_ref = search_my_process_keyrings(&ctx); if (!IS_ERR(skey_ref)) { key_ref_put(skey_ref); key_ref = make_key_ref(key, 1); } } /* check whether the current task is allowed to view the key */ rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); if (rc < 0) return 0; now = current_kernel_time(); rcu_read_lock(); /* come up with a suitable timeout value */ if (key->expiry == 0) { memcpy(xbuf, "perm", 5); } else if (now.tv_sec >= key->expiry) { memcpy(xbuf, "expd", 5); } else { timo = key->expiry - now.tv_sec; if (timo < 60) sprintf(xbuf, "%lus", timo); else if (timo < 60*60) sprintf(xbuf, "%lum", timo / 60); else if (timo < 60*60*24) sprintf(xbuf, "%luh", timo / (60*60)); else if (timo < 60*60*24*7) sprintf(xbuf, "%lud", timo / (60*60*24)); else sprintf(xbuf, "%luw", timo / (60*60*24*7)); } #define showflag(KEY, LETTER, FLAG) \ (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", key->serial, showflag(key, 'I', KEY_FLAG_INSTANTIATED), showflag(key, 'R', KEY_FLAG_REVOKED), showflag(key, 'D', KEY_FLAG_DEAD), showflag(key, 'Q', KEY_FLAG_IN_QUOTA), showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), showflag(key, 'N', KEY_FLAG_NEGATIVE), showflag(key, 'i', KEY_FLAG_INVALIDATED), refcount_read(&key->usage), xbuf, key->perm, from_kuid_munged(seq_user_ns(m), key->uid), from_kgid_munged(seq_user_ns(m), key->gid), key->type->name); #undef showflag if (key->type->describe) key->type->describe(key, m); seq_putc(m, '\n'); rcu_read_unlock(); return 0; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
static int proc_keys_show(struct seq_file *m, void *v) { struct rb_node *_p = v; struct key *key = rb_entry(_p, struct key, serial_node); struct timespec now; unsigned long timo; key_ref_t key_ref, skey_ref; char xbuf[16]; short state; int rc; struct keyring_search_context ctx = { .index_key.type = key->type, .index_key.description = key->description, .cred = m->file->f_cred, .match_data.cmp = lookup_user_key_possessed, .match_data.raw_data = key, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; key_ref = make_key_ref(key, 0); /* determine if the key is possessed by this process (a test we can * skip if the key does not indicate the possessor can view it */ if (key->perm & KEY_POS_VIEW) { skey_ref = search_my_process_keyrings(&ctx); if (!IS_ERR(skey_ref)) { key_ref_put(skey_ref); key_ref = make_key_ref(key, 1); } } /* check whether the current task is allowed to view the key */ rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); if (rc < 0) return 0; now = current_kernel_time(); rcu_read_lock(); /* come up with a suitable timeout value */ if (key->expiry == 0) { memcpy(xbuf, "perm", 5); } else if (now.tv_sec >= key->expiry) { memcpy(xbuf, "expd", 5); } else { timo = key->expiry - now.tv_sec; if (timo < 60) sprintf(xbuf, "%lus", timo); else if (timo < 60*60) sprintf(xbuf, "%lum", timo / 60); else if (timo < 60*60*24) sprintf(xbuf, "%luh", timo / (60*60)); else if (timo < 60*60*24*7) sprintf(xbuf, "%lud", timo / (60*60*24)); else sprintf(xbuf, "%luw", timo / (60*60*24*7)); } state = key_read_state(key); #define showflag(KEY, LETTER, FLAG) \ (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", key->serial, state != KEY_IS_UNINSTANTIATED ? 'I' : '-', showflag(key, 'R', KEY_FLAG_REVOKED), showflag(key, 'D', KEY_FLAG_DEAD), showflag(key, 'Q', KEY_FLAG_IN_QUOTA), showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), state < 0 ? 'N' : '-', showflag(key, 'i', KEY_FLAG_INVALIDATED), refcount_read(&key->usage), xbuf, key->perm, from_kuid_munged(seq_user_ns(m), key->uid), from_kgid_munged(seq_user_ns(m), key->gid), key->type->name); #undef showflag if (key->type->describe) key->type->describe(key, m); seq_putc(m, '\n'); rcu_read_unlock(); return 0; }
167,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct page *pages[NFS4ACL_MAXPAGES] = {NULL, }; struct nfs_getaclargs args = { .fh = NFS_FH(inode), .acl_pages = pages, .acl_len = buflen, }; struct nfs_getaclres res = { .acl_len = buflen, }; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL], .rpc_argp = &args, .rpc_resp = &res, }; unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE); int ret = -ENOMEM, i; /* As long as we're doing a round trip to the server anyway, * let's be prepared for a page of acl data. */ if (npages == 0) npages = 1; if (npages > ARRAY_SIZE(pages)) return -ERANGE; for (i = 0; i < npages; i++) { pages[i] = alloc_page(GFP_KERNEL); if (!pages[i]) goto out_free; } /* for decoding across pages */ res.acl_scratch = alloc_page(GFP_KERNEL); if (!res.acl_scratch) goto out_free; args.acl_len = npages * PAGE_SIZE; args.acl_pgbase = 0; dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n", __func__, buf, buflen, npages, args.acl_len); ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0); if (ret) goto out_free; /* Handle the case where the passed-in buffer is too short */ if (res.acl_flags & NFS4_ACL_TRUNC) { /* Did the user only issue a request for the acl length? */ if (buf == NULL) goto out_ok; ret = -ERANGE; goto out_free; } nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len); if (buf) _copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len); out_ok: ret = res.acl_len; out_free: for (i = 0; i < npages; i++) if (pages[i]) __free_page(pages[i]); if (res.acl_scratch) __free_page(res.acl_scratch); return ret; } Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in __nfs4_get_acl_uncached" accidently dropped the checking for too small result buffer length. If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount supporting ACLs, the ACL has not been cached and the buffer suplied is too short, we still copy the complete ACL, resulting in kernel and user space memory corruption. Signed-off-by: Sven Wegener <[email protected]> Cc: [email protected] Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-119
static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct page *pages[NFS4ACL_MAXPAGES] = {NULL, }; struct nfs_getaclargs args = { .fh = NFS_FH(inode), .acl_pages = pages, .acl_len = buflen, }; struct nfs_getaclres res = { .acl_len = buflen, }; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL], .rpc_argp = &args, .rpc_resp = &res, }; unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE); int ret = -ENOMEM, i; /* As long as we're doing a round trip to the server anyway, * let's be prepared for a page of acl data. */ if (npages == 0) npages = 1; if (npages > ARRAY_SIZE(pages)) return -ERANGE; for (i = 0; i < npages; i++) { pages[i] = alloc_page(GFP_KERNEL); if (!pages[i]) goto out_free; } /* for decoding across pages */ res.acl_scratch = alloc_page(GFP_KERNEL); if (!res.acl_scratch) goto out_free; args.acl_len = npages * PAGE_SIZE; args.acl_pgbase = 0; dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n", __func__, buf, buflen, npages, args.acl_len); ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0); if (ret) goto out_free; /* Handle the case where the passed-in buffer is too short */ if (res.acl_flags & NFS4_ACL_TRUNC) { /* Did the user only issue a request for the acl length? */ if (buf == NULL) goto out_ok; ret = -ERANGE; goto out_free; } nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len); if (buf) { if (res.acl_len > buflen) { ret = -ERANGE; goto out_free; } _copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len); } out_ok: ret = res.acl_len; out_free: for (i = 0; i < npages; i++) if (pages[i]) __free_page(pages[i]); if (res.acl_scratch) __free_page(res.acl_scratch); return ret; }
165,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } s += padlen + 3; (*psig) = s; /* return SUCCESS */ return NULL; } Commit Message: wo#7449 . verify padding contents for IKEv2 RSA sig check Special thanks to Sze Yiu Chau of Purdue University ([email protected]) who reported the issue. CWE ID: CWE-347
err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } /* signature starts after ASN wrapped padding [00,01,FF..FF,00] */ (*psig) = s + padlen + 3; /* verify padding contents */ { const u_char *p; size_t cnt_ffs = 0; for (p = s+2; p < s+padlen+2; p++) if (*p == 0xFF) cnt_ffs ++; if (cnt_ffs != padlen) return "4" "invalid Padding String"; } /* return SUCCESS */ return NULL; }
169,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static noinline void key_gc_unused_keys(struct list_head *keys) { while (!list_empty(keys)) { struct key *key = list_entry(keys->next, struct key, graveyard_link); list_del(&key->graveyard_link); kdebug("- %u", key->serial); key_check(key); /* Throw away the key data */ if (key->type->destroy) key->type->destroy(key); security_key_free(key); /* deal with the user's key tracking and quota */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) atomic_dec(&key->user->nikeys); key_user_put(key->user); kfree(key->description); #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC_X; #endif kmem_cache_free(key_jar, key); } } Commit Message: Merge branch 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs Pull key handling fixes from David Howells: "Here are two patches, the first of which at least should go upstream immediately: (1) Prevent a user-triggerable crash in the keyrings destructor when a negatively instantiated keyring is garbage collected. I have also seen this triggered for user type keys. (2) Prevent the user from using requesting that a keyring be created and instantiated through an upcall. Doing so is probably safe since the keyring type ignores the arguments to its instantiation function - but we probably shouldn't let keyrings be created in this manner" * 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs: KEYS: Don't permit request_key() to construct a new keyring KEYS: Fix crash when attempt to garbage collect an uninstantiated keyring CWE ID: CWE-20
static noinline void key_gc_unused_keys(struct list_head *keys) { while (!list_empty(keys)) { struct key *key = list_entry(keys->next, struct key, graveyard_link); list_del(&key->graveyard_link); kdebug("- %u", key->serial); key_check(key); /* Throw away the key data if the key is instantiated */ if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) && !test_bit(KEY_FLAG_NEGATIVE, &key->flags) && key->type->destroy) key->type->destroy(key); security_key_free(key); /* deal with the user's key tracking and quota */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) atomic_dec(&key->user->nikeys); key_user_put(key->user); kfree(key->description); #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC_X; #endif kmem_cache_free(key_jar, key); } }
166,576
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __exit void sctp_exit(void) { /* BUG. This should probably do something useful like clean * up all the remaining associations and all that memory. */ /* Unregister with inet6/inet layers. */ sctp_v6_del_protocol(); sctp_v4_del_protocol(); unregister_pernet_subsys(&sctp_net_ops); /* Free protosw registrations */ sctp_v6_protosw_exit(); sctp_v4_protosw_exit(); /* Unregister with socket layer. */ sctp_v6_pf_exit(); sctp_v4_pf_exit(); sctp_sysctl_unregister(); free_pages((unsigned long)sctp_assoc_hashtable, get_order(sctp_assoc_hashsize * sizeof(struct sctp_hashbucket))); kfree(sctp_ep_hashtable); free_pages((unsigned long)sctp_port_hashtable, get_order(sctp_port_hashsize * sizeof(struct sctp_bind_hashbucket))); percpu_counter_destroy(&sctp_sockets_allocated); rcu_barrier(); /* Wait for completion of call_rcu()'s */ kmem_cache_destroy(sctp_chunk_cachep); kmem_cache_destroy(sctp_bucket_cachep); } Commit Message: sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static __exit void sctp_exit(void) { /* BUG. This should probably do something useful like clean * up all the remaining associations and all that memory. */ /* Unregister with inet6/inet layers. */ sctp_v6_del_protocol(); sctp_v4_del_protocol(); unregister_pernet_subsys(&sctp_ctrlsock_ops); /* Free protosw registrations */ sctp_v6_protosw_exit(); sctp_v4_protosw_exit(); unregister_pernet_subsys(&sctp_defaults_ops); /* Unregister with socket layer. */ sctp_v6_pf_exit(); sctp_v4_pf_exit(); sctp_sysctl_unregister(); free_pages((unsigned long)sctp_assoc_hashtable, get_order(sctp_assoc_hashsize * sizeof(struct sctp_hashbucket))); kfree(sctp_ep_hashtable); free_pages((unsigned long)sctp_port_hashtable, get_order(sctp_port_hashsize * sizeof(struct sctp_bind_hashbucket))); percpu_counter_destroy(&sctp_sockets_allocated); rcu_barrier(); /* Wait for completion of call_rcu()'s */ kmem_cache_destroy(sctp_chunk_cachep); kmem_cache_destroy(sctp_bucket_cachep); }
166,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); if (ctxt->instate == XML_PARSER_EOF) return(-1); /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); if (ctxt->instate == XML_PARSER_EOF) return(-1); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); if (ctxt->instate == XML_PARSER_EOF) return(-1); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } return(0); }
171,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_COMPAT_FUNCS *cf; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; const unsigned char *p = NULL, *q; unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */ unsigned char imphack = 0, oclass; char seq_eoc, seq_nolen, cst, isopt; long tmplen; int i; int otag; int ret = 0; ASN1_VALUE **pchptr, *ptmpval; if (!pval) return 0; if (aux && aux->asn1_cb) asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { /* * tagging or OPTIONAL is currently illegal on an item template * because the flags can't get passed down. In practice this * isn't a problem: we include the relevant flags from the item * template in the template itself. */ if ((tag != -1) || opt) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); goto err; } return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); break; case ASN1_ITYPE_MSTRING: p = *in; /* Just read in tag and class */ ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Must be UNIVERSAL class */ if (oclass != V_ASN1_UNIVERSAL) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL); goto err; } /* Check tag matches bit map */ if (!(ASN1_tag2bit(otag) & it->utype)) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG); goto err; } return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx); case ASN1_ITYPE_EXTERN: /* Use new style d2i */ ef = it->funcs; return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_COMPAT: /* we must resort to old style evil hackery */ cf = it->funcs; /* If OPTIONAL see if it is there */ if (opt) { int exptag; p = *in; if (tag == -1) exptag = it->utype; else exptag = tag; /* * Don't care about anything other than presence of expected tag */ ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL, &p, len, exptag, aclass, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (ret == -1) return -1; } /* * This is the old style evil hack IMPLICIT handling: since the * underlying code is expecting a tag and class other than the one * present we change the buffer temporarily then change it back * afterwards. This doesn't and never did work for tags > 30. Yes * this is *horrible* but it is only needed for old style d2i which * will hopefully not be around for much longer. FIXME: should copy * the buffer then modify it so the input buffer can be const: we * should *always* copy because the old style d2i might modify the * buffer. */ if (tag != -1) { wp = *(unsigned char **)in; imphack = *wp; if (p == NULL) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED) | it->utype); } ptmpval = cf->asn1_d2i(pval, in, len); if (tag != -1) *wp = imphack; if (ptmpval) return 1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; if (*pval) { /* Free up and zero CHOICE value if initialised */ i = asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { tt = it->templates + i; pchptr = asn1_get_field_ptr(pval, tt); ASN1_template_free(pchptr, tt); asn1_set_choice_selector(pval, -1, it); } } else if (!ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* CHOICE type, try each possibility in turn */ p = *in; for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { pchptr = asn1_get_field_ptr(pval, tt); /* * We mark field as OPTIONAL so its absence can be recognised. */ ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; /* If positive return, read OK, break loop */ if (ret > 0) break; /* Otherwise must be an ASN1 parsing error */ errtt = tt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Did we fall off the end without reading anything? */ if (i == it->tcount) { /* If OPTIONAL, this is OK */ if (opt) { /* Free and zero it */ ASN1_item_ex_free(pval, it); return -1; } ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE); goto err; } asn1_set_choice_selector(pval, i, it); if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; *in = p; return 1; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: p = *in; tmplen = len; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; aclass = V_ASN1_UNIVERSAL; } /* Get SEQUENCE length and update len, p */ ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; if (aux && (aux->flags & ASN1_AFLG_BROKEN)) { len = tmplen - (p - *in); seq_nolen = 1; } /* If indefinite we don't do a length check */ else seq_nolen = seq_eoc; if (!cst) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); goto err; } if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Free up and zero any ADB found */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { if (tt->flags & ASN1_TFLG_ADB_MASK) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } } /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; pseqval = asn1_get_field_ptr(pval, seqtt); /* Have we ran out of data? */ if (!len) break; q = p; if (asn1_check_eoc(&p, len)) { if (!seq_eoc) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC); goto err; } len -= p - q; seq_eoc = 0; q = p; break; } /* * This determines the OPTIONAL flag value. The field cannot be * omitted if it is the last of a SEQUENCE and there is still * data to be read. This isn't strictly necessary but it * increases efficiency in some cases. */ if (i == (it->tcount - 1)) isopt = 0; else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL); /* * attempt to read in field, allowing each to be OPTIONAL */ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; } else if (ret == -1) { /* * OPTIONAL component absent. Free and zero the field. */ ASN1_template_free(pseqval, seqtt); continue; } /* Update length */ len -= p - q; } /* Check for EOC if expecting one */ if (seq_eoc && !asn1_check_eoc(&p, len)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC); goto err; } /* Check all data read */ if (!seq_nolen && len) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH); goto err; } /* * If we get here we've got no more data in the SEQUENCE, however we * may not have read all fields so check all remaining are OPTIONAL * and clear any that are. */ for (; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; if (seqtt->flags & ASN1_TFLG_OPTIONAL) { ASN1_VALUE **pseqval; pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } else { errtt = seqtt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING); goto err; } } /* Save encoding */ if (!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; *in = p; return 1; default: return 0; } auxerr: ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR); auxerr: ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR); err: ASN1_item_ex_free(pval, it); if (errtt) ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname); } Commit Message: CWE ID: CWE-200
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_COMPAT_FUNCS *cf; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; const unsigned char *p = NULL, *q; unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */ unsigned char imphack = 0, oclass; char seq_eoc, seq_nolen, cst, isopt; long tmplen; int i; int otag; int ret = 0; ASN1_VALUE **pchptr, *ptmpval; int combine = aclass & ASN1_TFLG_COMBINE; aclass &= ~ASN1_TFLG_COMBINE; if (!pval) return 0; if (aux && aux->asn1_cb) asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { /* * tagging or OPTIONAL is currently illegal on an item template * because the flags can't get passed down. In practice this * isn't a problem: we include the relevant flags from the item * template in the template itself. */ if ((tag != -1) || opt) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); goto err; } return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); break; case ASN1_ITYPE_MSTRING: p = *in; /* Just read in tag and class */ ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Must be UNIVERSAL class */ if (oclass != V_ASN1_UNIVERSAL) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL); goto err; } /* Check tag matches bit map */ if (!(ASN1_tag2bit(otag) & it->utype)) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG); goto err; } return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx); case ASN1_ITYPE_EXTERN: /* Use new style d2i */ ef = it->funcs; return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_COMPAT: /* we must resort to old style evil hackery */ cf = it->funcs; /* If OPTIONAL see if it is there */ if (opt) { int exptag; p = *in; if (tag == -1) exptag = it->utype; else exptag = tag; /* * Don't care about anything other than presence of expected tag */ ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL, &p, len, exptag, aclass, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (ret == -1) return -1; } /* * This is the old style evil hack IMPLICIT handling: since the * underlying code is expecting a tag and class other than the one * present we change the buffer temporarily then change it back * afterwards. This doesn't and never did work for tags > 30. Yes * this is *horrible* but it is only needed for old style d2i which * will hopefully not be around for much longer. FIXME: should copy * the buffer then modify it so the input buffer can be const: we * should *always* copy because the old style d2i might modify the * buffer. */ if (tag != -1) { wp = *(unsigned char **)in; imphack = *wp; if (p == NULL) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED) | it->utype); } ptmpval = cf->asn1_d2i(pval, in, len); if (tag != -1) *wp = imphack; if (ptmpval) return 1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; if (*pval) { /* Free up and zero CHOICE value if initialised */ i = asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { tt = it->templates + i; pchptr = asn1_get_field_ptr(pval, tt); ASN1_template_free(pchptr, tt); asn1_set_choice_selector(pval, -1, it); } } else if (!ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* CHOICE type, try each possibility in turn */ p = *in; for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { pchptr = asn1_get_field_ptr(pval, tt); /* * We mark field as OPTIONAL so its absence can be recognised. */ ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; /* If positive return, read OK, break loop */ if (ret > 0) break; /* Otherwise must be an ASN1 parsing error */ errtt = tt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Did we fall off the end without reading anything? */ if (i == it->tcount) { /* If OPTIONAL, this is OK */ if (opt) { /* Free and zero it */ ASN1_item_ex_free(pval, it); return -1; } ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE); goto err; } asn1_set_choice_selector(pval, i, it); if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; *in = p; return 1; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: p = *in; tmplen = len; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; aclass = V_ASN1_UNIVERSAL; } /* Get SEQUENCE length and update len, p */ ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; if (aux && (aux->flags & ASN1_AFLG_BROKEN)) { len = tmplen - (p - *in); seq_nolen = 1; } /* If indefinite we don't do a length check */ else seq_nolen = seq_eoc; if (!cst) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); goto err; } if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Free up and zero any ADB found */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { if (tt->flags & ASN1_TFLG_ADB_MASK) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } } /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; pseqval = asn1_get_field_ptr(pval, seqtt); /* Have we ran out of data? */ if (!len) break; q = p; if (asn1_check_eoc(&p, len)) { if (!seq_eoc) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC); goto err; } len -= p - q; seq_eoc = 0; q = p; break; } /* * This determines the OPTIONAL flag value. The field cannot be * omitted if it is the last of a SEQUENCE and there is still * data to be read. This isn't strictly necessary but it * increases efficiency in some cases. */ if (i == (it->tcount - 1)) isopt = 0; else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL); /* * attempt to read in field, allowing each to be OPTIONAL */ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; } else if (ret == -1) { /* * OPTIONAL component absent. Free and zero the field. */ ASN1_template_free(pseqval, seqtt); continue; } /* Update length */ len -= p - q; } /* Check for EOC if expecting one */ if (seq_eoc && !asn1_check_eoc(&p, len)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC); goto err; } /* Check all data read */ if (!seq_nolen && len) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH); goto err; } /* * If we get here we've got no more data in the SEQUENCE, however we * may not have read all fields so check all remaining are OPTIONAL * and clear any that are. */ for (; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; if (seqtt->flags & ASN1_TFLG_OPTIONAL) { ASN1_VALUE **pseqval; pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } else { errtt = seqtt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING); goto err; } } /* Save encoding */ if (!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; *in = p; return 1; default: return 0; } auxerr: ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR); auxerr: ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR); err: if (combine == 0) ASN1_item_ex_free(pval, it); if (errtt) ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname); }
164,718
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ip6_append_data_mtu(int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (skb == NULL) { /* first fragment, reserve header_len */ *mtu = *mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = dst_mtu(rt->dst.path); } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } Commit Message: ipv6: ip6_append_data_mtu did not care about pmtudisc and frag_size If the socket had an IPV6_MTU value set, ip6_append_data_mtu lost track of this when appending the second frame on a corked socket. This results in the following splat: [37598.993962] ------------[ cut here ]------------ [37598.994008] kernel BUG at net/core/skbuff.c:2064! [37598.994008] invalid opcode: 0000 [#1] SMP [37598.994008] Modules linked in: tcp_lp uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core videodev media vfat fat usb_storage fuse ebtable_nat xt_CHECKSUM bridge stp llc ipt_MASQUERADE nf_conntrack_netbios_ns nf_conntrack_broadcast ip6table_mangle ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 iptable_nat +nf_nat_ipv4 nf_nat iptable_mangle nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ebtable_filter ebtables ip6table_filter ip6_tables be2iscsi iscsi_boot_sysfs bnx2i cnic uio cxgb4i cxgb4 cxgb3i cxgb3 mdio libcxgbi ib_iser rdma_cm ib_addr iw_cm ib_cm ib_sa ib_mad ib_core iscsi_tcp libiscsi_tcp libiscsi +scsi_transport_iscsi rfcomm bnep iTCO_wdt iTCO_vendor_support snd_hda_codec_conexant arc4 iwldvm mac80211 snd_hda_intel acpi_cpufreq mperf coretemp snd_hda_codec microcode cdc_wdm cdc_acm [37598.994008] snd_hwdep cdc_ether snd_seq snd_seq_device usbnet mii joydev btusb snd_pcm bluetooth i2c_i801 e1000e lpc_ich mfd_core ptp iwlwifi pps_core snd_page_alloc mei cfg80211 snd_timer thinkpad_acpi snd tpm_tis soundcore rfkill tpm tpm_bios vhost_net tun macvtap macvlan kvm_intel kvm uinput binfmt_misc +dm_crypt i915 i2c_algo_bit drm_kms_helper drm i2c_core wmi video [37598.994008] CPU 0 [37598.994008] Pid: 27320, comm: t2 Not tainted 3.9.6-200.fc18.x86_64 #1 LENOVO 27744PG/27744PG [37598.994008] RIP: 0010:[<ffffffff815443a5>] [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330 [37598.994008] RSP: 0018:ffff88003670da18 EFLAGS: 00010202 [37598.994008] RAX: ffff88018105c018 RBX: 0000000000000004 RCX: 00000000000006c0 [37598.994008] RDX: ffff88018105a6c0 RSI: ffff88018105a000 RDI: ffff8801e1b0aa00 [37598.994008] RBP: ffff88003670da78 R08: 0000000000000000 R09: ffff88018105c040 [37598.994008] R10: ffff8801e1b0aa00 R11: 0000000000000000 R12: 000000000000fff8 [37598.994008] R13: 00000000000004fc R14: 00000000ffff0504 R15: 0000000000000000 [37598.994008] FS: 00007f28eea59740(0000) GS:ffff88023bc00000(0000) knlGS:0000000000000000 [37598.994008] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b [37598.994008] CR2: 0000003d935789e0 CR3: 00000000365cb000 CR4: 00000000000407f0 [37598.994008] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [37598.994008] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 [37598.994008] Process t2 (pid: 27320, threadinfo ffff88003670c000, task ffff88022c162ee0) [37598.994008] Stack: [37598.994008] ffff88022e098a00 ffff88020f973fc0 0000000000000008 00000000000004c8 [37598.994008] ffff88020f973fc0 00000000000004c4 ffff88003670da78 ffff8801e1b0a200 [37598.994008] 0000000000000018 00000000000004c8 ffff88020f973fc0 00000000000004c4 [37598.994008] Call Trace: [37598.994008] [<ffffffff815fc21f>] ip6_append_data+0xccf/0xfe0 [37598.994008] [<ffffffff8158d9f0>] ? ip_copy_metadata+0x1a0/0x1a0 [37598.994008] [<ffffffff81661f66>] ? _raw_spin_lock_bh+0x16/0x40 [37598.994008] [<ffffffff8161548d>] udpv6_sendmsg+0x1ed/0xc10 [37598.994008] [<ffffffff812a2845>] ? sock_has_perm+0x75/0x90 [37598.994008] [<ffffffff815c3693>] inet_sendmsg+0x63/0xb0 [37598.994008] [<ffffffff812a2973>] ? selinux_socket_sendmsg+0x23/0x30 [37598.994008] [<ffffffff8153a450>] sock_sendmsg+0xb0/0xe0 [37598.994008] [<ffffffff810135d1>] ? __switch_to+0x181/0x4a0 [37598.994008] [<ffffffff8153d97d>] sys_sendto+0x12d/0x180 [37598.994008] [<ffffffff810dfb64>] ? __audit_syscall_entry+0x94/0xf0 [37598.994008] [<ffffffff81020ed1>] ? syscall_trace_enter+0x231/0x240 [37598.994008] [<ffffffff8166a7e7>] tracesys+0xdd/0xe2 [37598.994008] Code: fe 07 00 00 48 c7 c7 04 28 a6 81 89 45 a0 4c 89 4d b8 44 89 5d a8 e8 1b ac b1 ff 44 8b 5d a8 4c 8b 4d b8 8b 45 a0 e9 cf fe ff ff <0f> 0b 66 0f 1f 84 00 00 00 00 00 66 66 66 66 90 55 48 89 e5 48 [37598.994008] RIP [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330 [37598.994008] RSP <ffff88003670da18> [37599.007323] ---[ end trace d69f6a17f8ac8eee ]--- While there, also check if path mtu discovery is activated for this socket. The logic was adapted from ip6_append_data when first writing on the corked socket. This bug was introduced with commit 0c1833797a5a6ec23ea9261d979aa18078720b74 ("ipv6: fix incorrect ipsec fragment"). v2: a) Replace IPV6_PMTU_DISC_DO with IPV6_PMTUDISC_PROBE. b) Don't pass ipv6_pinfo to ip6_append_data_mtu (suggestion by Gao feng, thanks!). c) Change mtu to unsigned int, else we get a warning about non-matching types because of the min()-macro type-check. Acked-by: Gao feng <[email protected]> Cc: YOSHIFUJI Hideaki <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static void ip6_append_data_mtu(int *mtu, static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, bool pmtuprobe) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (skb == NULL) { /* first fragment, reserve header_len */ *mtu = *mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = min(*mtu, pmtuprobe ? rt->dst.dev->mtu : dst_mtu(rt->dst.path)); } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } }
166,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GfxImageColorMap::GfxImageColorMap(int bitsA, Object *decode, GfxColorSpace *colorSpaceA) { GfxIndexedColorSpace *indexedCS; GfxSeparationColorSpace *sepCS; int maxPixel, indexHigh; Guchar *lookup2; Function *sepFunc; Object obj; double x[gfxColorMaxComps]; double y[gfxColorMaxComps]; int i, j, k, byte; double mapped; ok = gTrue; bits = bitsA; maxPixel = (1 << bits) - 1; colorSpace = colorSpaceA; if (maxPixel > 255) maxPixel = 255; for (k = 0; k < gfxColorMaxComps; ++k) { lookup[k] = NULL; } if (decode->isNull()) { nComps = colorSpace->getNComps(); colorSpace->getDefaultRanges(decodeLow, decodeRange, maxPixel); } else if (decode->isArray()) { nComps = decode->arrayGetLength() / 2; if (nComps != colorSpace->getNComps()) { goto err1; } for (i = 0; i < nComps; ++i) { decode->arrayGet(2*i, &obj); if (!obj.isNum()) { goto err2; } decodeLow[i] = obj.getNum(); obj.free(); decode->arrayGet(2*i+1, &obj); if (!obj.isNum()) { goto err2; } decodeRange[i] = obj.getNum() - decodeLow[i]; obj.free(); } } else { goto err1; } colorSpace2 = NULL; nComps2 = 0; if (colorSpace->getMode() == csIndexed) { indexedCS = (GfxIndexedColorSpace *)colorSpace; colorSpace2 = indexedCS->getBase(); indexHigh = indexedCS->getIndexHigh(); nComps2 = colorSpace2->getNComps(); lookup2 = indexedCS->getLookup(); colorSpace2->getDefaultRanges(x, y, indexHigh); byte_lookup = (Guchar *)gmalloc ((maxPixel + 1) * nComps2); for (k = 0; k < nComps2; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { j = (int)(decodeLow[0] + (i * decodeRange[0]) / maxPixel + 0.5); if (j < 0) { j = 0; } else if (j > indexHigh) { j = indexHigh; } mapped = x[k] + (lookup2[j*nComps2 + k] / 255.0) * y[k]; lookup[k][i] = dblToCol(mapped); byte_lookup[i * nComps2 + k] = (Guchar) (mapped * 255); } } } else if (colorSpace->getMode() == csSeparation) { sepCS = (GfxSeparationColorSpace *)colorSpace; colorSpace2 = sepCS->getAlt(); nComps2 = colorSpace2->getNComps(); sepFunc = sepCS->getFunc(); byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps2); for (k = 0; k < nComps2; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { x[0] = decodeLow[0] + (i * decodeRange[0]) / maxPixel; sepFunc->transform(x, y); lookup[k][i] = dblToCol(y[k]); byte_lookup[i*nComps2 + k] = (Guchar) (y[k] * 255); } } } else { byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps); for (k = 0; k < nComps; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { mapped = decodeLow[k] + (i * decodeRange[k]) / maxPixel; lookup[k][i] = dblToCol(mapped); byte = (int) (mapped * 255.0 + 0.5); if (byte < 0) byte = 0; else if (byte > 255) byte = 255; byte_lookup[i * nComps + k] = byte; } } } return; err2: obj.free(); err1: ok = gFalse; byte_lookup = NULL; } Commit Message: CWE ID: CWE-189
GfxImageColorMap::GfxImageColorMap(int bitsA, Object *decode, GfxColorSpace *colorSpaceA) { GfxIndexedColorSpace *indexedCS; GfxSeparationColorSpace *sepCS; int maxPixel, indexHigh; Guchar *lookup2; Function *sepFunc; Object obj; double x[gfxColorMaxComps]; double y[gfxColorMaxComps]; int i, j, k, byte; double mapped; ok = gTrue; bits = bitsA; maxPixel = (1 << bits) - 1; colorSpace = colorSpaceA; if (maxPixel > 255) maxPixel = 255; for (k = 0; k < gfxColorMaxComps; ++k) { lookup[k] = NULL; } if (decode->isNull()) { nComps = colorSpace->getNComps(); colorSpace->getDefaultRanges(decodeLow, decodeRange, maxPixel); } else if (decode->isArray()) { nComps = decode->arrayGetLength() / 2; if (nComps != colorSpace->getNComps()) { goto err1; } for (i = 0; i < nComps; ++i) { decode->arrayGet(2*i, &obj); if (!obj.isNum()) { goto err2; } decodeLow[i] = obj.getNum(); obj.free(); decode->arrayGet(2*i+1, &obj); if (!obj.isNum()) { goto err2; } decodeRange[i] = obj.getNum() - decodeLow[i]; obj.free(); } } else { goto err1; } colorSpace2 = NULL; nComps2 = 0; if (colorSpace->getMode() == csIndexed) { indexedCS = (GfxIndexedColorSpace *)colorSpace; colorSpace2 = indexedCS->getBase(); indexHigh = indexedCS->getIndexHigh(); nComps2 = colorSpace2->getNComps(); lookup2 = indexedCS->getLookup(); colorSpace2->getDefaultRanges(x, y, indexHigh); byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps2); for (k = 0; k < nComps2; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { j = (int)(decodeLow[0] + (i * decodeRange[0]) / maxPixel + 0.5); if (j < 0) { j = 0; } else if (j > indexHigh) { j = indexHigh; } mapped = x[k] + (lookup2[j*nComps2 + k] / 255.0) * y[k]; lookup[k][i] = dblToCol(mapped); byte_lookup[i * nComps2 + k] = (Guchar) (mapped * 255); } } } else if (colorSpace->getMode() == csSeparation) { sepCS = (GfxSeparationColorSpace *)colorSpace; colorSpace2 = sepCS->getAlt(); nComps2 = colorSpace2->getNComps(); sepFunc = sepCS->getFunc(); byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps2); for (k = 0; k < nComps2; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { x[0] = decodeLow[0] + (i * decodeRange[0]) / maxPixel; sepFunc->transform(x, y); lookup[k][i] = dblToCol(y[k]); byte_lookup[i*nComps2 + k] = (Guchar) (y[k] * 255); } } } else { byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps); for (k = 0; k < nComps; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { mapped = decodeLow[k] + (i * decodeRange[k]) / maxPixel; lookup[k][i] = dblToCol(mapped); byte = (int) (mapped * 255.0 + 0.5); if (byte < 0) byte = 0; else if (byte > 255) byte = 255; byte_lookup[i * nComps + k] = byte; } } } return; err2: obj.free(); err1: ok = gFalse; byte_lookup = NULL; }
164,608
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } Commit Message: KVM: Fix iommu map/unmap to handle memory slot moves The iommu integration into memory slots expects memory slots to be added or removed and doesn't handle the move case. We can unmap slots from the iommu after we mark them invalid and map them before installing the final memslot array. Also re-order the kmemdup vs map so we don't leave iommu mappings if we get ENOMEM. Reviewed-by: Gleb Natapov <[email protected]> Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399
int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* slot was deleted or moved, clear iommu mapping */ kvm_iommu_unmap_pages(kvm, &old); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* map new memory slot into the iommu */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_slots; } /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_slots: kfree(slots); out_free: kvm_free_physmem_slot(&new, &old); out: return r; }
169,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); } Commit Message: * libtiff/tif_pixarlog.c: fix potential buffer write overrun in PixarLogDecode() on corrupted/unexpected images (reported by Mathias Svensson) CWE ID: CWE-787
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } /* Check that we will not fill more than what was allocated */ if (sp->stream.avail_out > sp->tbuf_size) { TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); }
169,449
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameHostImpl::ResetFeaturePolicy() { RenderFrameHostImpl* parent_frame_host = GetParent(); const FeaturePolicy* parent_policy = parent_frame_host ? parent_frame_host->get_feature_policy() : nullptr; ParsedFeaturePolicyHeader container_policy = frame_tree_node()->effective_container_policy(); feature_policy_ = FeaturePolicy::CreateFromParentPolicy( parent_policy, container_policy, last_committed_origin_); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
void RenderFrameHostImpl::ResetFeaturePolicy() { RenderFrameHostImpl* parent_frame_host = GetParent(); const FeaturePolicy* parent_policy = parent_frame_host ? parent_frame_host->feature_policy() : nullptr; ParsedFeaturePolicyHeader container_policy = frame_tree_node()->effective_container_policy(); feature_policy_ = FeaturePolicy::CreateFromParentPolicy( parent_policy, container_policy, last_committed_origin_); }
171,964
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) { if (!nestable_tasks_allowed_ || !SweepDelayedWorkQueueAndReturnTrueIfStillHasWork()) { recent_time_ = *next_delayed_work_time = TimeTicks(); return false; } TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time; if (next_run_time > recent_time_) { recent_time_ = TimeTicks::Now(); // Get a better view of Now(); if (next_run_time > recent_time_) { *next_delayed_work_time = next_run_time; return false; } } PendingTask pending_task = std::move(const_cast<PendingTask&>(delayed_work_queue_.top())); delayed_work_queue_.pop(); if (SweepDelayedWorkQueueAndReturnTrueIfStillHasWork()) *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time; return DeferOrRunPendingTask(std::move(pending_task)); } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) { if (!NestableTasksAllowed() || !SweepDelayedWorkQueueAndReturnTrueIfStillHasWork()) { recent_time_ = *next_delayed_work_time = TimeTicks(); return false; } TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time; if (next_run_time > recent_time_) { recent_time_ = TimeTicks::Now(); // Get a better view of Now(); if (next_run_time > recent_time_) { *next_delayed_work_time = next_run_time; return false; } } PendingTask pending_task = std::move(const_cast<PendingTask&>(delayed_work_queue_.top())); delayed_work_queue_.pop(); if (SweepDelayedWorkQueueAndReturnTrueIfStillHasWork()) *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time; return DeferOrRunPendingTask(std::move(pending_task)); }
171,863
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded, sizeof(buffer)); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } }
169,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ __ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ if (np->opt != NULL) newnp->opt = ipv6_dup_options(newsk, np->opt); inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt != NULL) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ __ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }
167,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void V8RecursionScope::didLeaveScriptContext() { Microtask::performCheckpoint(); V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
void V8RecursionScope::didLeaveScriptContext() { Microtask::performCheckpoint(m_isolate); V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks(); }
171,943
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \ * 1/2 version > record header * 3/4 length / * 5 msg_type \ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply reject such connections to avoid * protocol version downgrade attacks. */ if (p[3] == 0 && p[4] < 6) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp("GET ", (char *)p,4) == 0) || (strncmp("POST ",(char *)p,5) == 0) || (strncmp("HEAD ",(char *)p,5) == 0) || (strncmp("PUT ", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp("CONNECT",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } /* ensure that TLS_MAX_VERSION is up-to-date */ OPENSSL_assert(s->version <= TLS_MAX_VERSION); #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header * (other cases skip this state) */ type=2; p=s->packet; v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. It's format is: * Byte Content * 0-1 msg_length * 2 msg_type * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } if (n < 9) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } j=ssl23_read_bytes(s,n+2); /* We previously read 11 bytes, so if j > 0, we must have * j == n+2 == s->packet_length. We have at least 11 valid * packet bytes. */ if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); if (s->msg_callback) s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ p=s->packet; p+=5; n2s(p,csl); n2s(p,sil); n2s(p,cl); d=(unsigned char *)s->init_buf->data; if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format * Client Hello, can we? Error condition should be * '>' otherweise */ { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; i<csl; i+=3) { if (p[i] != 0) continue; *(d++)=p[i+1]; *(d++)=p[i+2]; j+=2; } s2n(j,dd); /* COMPRESSION */ *(d++)=1; *(d++)=0; #if 0 /* copy any remaining data with may be extensions */ p = p+csl+sil+cl; while (p < s->packet+s->packet_length) { *(d++)=*(p++); } #endif i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ if (!ssl_init_wbio_buffer(s,1)) goto err; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } if (s->version == TLS1_2_VERSION) s->method = TLSv1_2_server_method(); else if (s->version == TLS1_1_VERSION) s->method = TLSv1_1_server_method(); else if (s->version == TLS1_VERSION) s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } if (s->version == TLS1_2_VERSION) s->method = TLSv1_2_server_method(); else if (s->version == TLS1_1_VERSION) s->method = TLSv1_1_server_method(); else if (s->version == TLS1_VERSION) s->method = TLSv1_server_method(); else s->method = SSLv3_server_method(); #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; } Commit Message: CWE ID: CWE-310
int ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \ * 1/2 version > record header * 3/4 length / * 5 msg_type \ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply reject such connections to avoid * protocol version downgrade attacks. */ if (p[3] == 0 && p[4] < 6) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp("GET ", (char *)p,4) == 0) || (strncmp("POST ",(char *)p,5) == 0) || (strncmp("HEAD ",(char *)p,5) == 0) || (strncmp("PUT ", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp("CONNECT",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } /* ensure that TLS_MAX_VERSION is up-to-date */ OPENSSL_assert(s->version <= TLS_MAX_VERSION); #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header * (other cases skip this state) */ type=2; p=s->packet; v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. It's format is: * Byte Content * 0-1 msg_length * 2 msg_type * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } if (n < 9) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } j=ssl23_read_bytes(s,n+2); /* We previously read 11 bytes, so if j > 0, we must have * j == n+2 == s->packet_length. We have at least 11 valid * packet bytes. */ if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); if (s->msg_callback) s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ p=s->packet; p+=5; n2s(p,csl); n2s(p,sil); n2s(p,cl); d=(unsigned char *)s->init_buf->data; if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format * Client Hello, can we? Error condition should be * '>' otherweise */ { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; i<csl; i+=3) { if (p[i] != 0) continue; *(d++)=p[i+1]; *(d++)=p[i+2]; j+=2; } s2n(j,dd); /* COMPRESSION */ *(d++)=1; *(d++)=0; #if 0 /* copy any remaining data with may be extensions */ p = p+csl+sil+cl; while (p < s->packet+s->packet_length) { *(d++)=*(p++); } #endif i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ s->method = ssl23_get_server_method(s->version); if (s->method == NULL) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; } if (!ssl_init_wbio_buffer(s,1)) goto err; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } if (s->version == TLS1_2_VERSION) s->method = TLSv1_2_server_method(); else if (s->version == TLS1_1_VERSION) s->method = TLSv1_1_server_method(); else if (s->version == TLS1_VERSION) s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; }
165,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } } 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
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (encoding_mode_ != ::libvpx_test::kRealTime) { encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } } }
174,513
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gsm_xsmp_client_connect (GsmXSMPClient *client, SmsConn conn, unsigned long *mask_ret, SmsCallbacks *callbacks_ret) { client->priv->conn = conn; if (client->priv->protocol_timeout) { g_source_remove (client->priv->protocol_timeout); client->priv->protocol_timeout = 0; } g_debug ("GsmXSMPClient: Initializing client %s", client->priv->description); *mask_ret = 0; *mask_ret |= SmsRegisterClientProcMask; callbacks_ret->register_client.callback = register_client_callback; callbacks_ret->register_client.manager_data = client; *mask_ret |= SmsInteractRequestProcMask; callbacks_ret->interact_request.callback = interact_request_callback; callbacks_ret->interact_request.manager_data = client; *mask_ret |= SmsInteractDoneProcMask; callbacks_ret->interact_done.callback = interact_done_callback; callbacks_ret->interact_done.manager_data = client; *mask_ret |= SmsSaveYourselfRequestProcMask; callbacks_ret->save_yourself_request.callback = save_yourself_request_callback; callbacks_ret->save_yourself_request.manager_data = client; *mask_ret |= SmsSaveYourselfP2RequestProcMask; callbacks_ret->save_yourself_phase2_request.callback = save_yourself_phase2_request_callback; callbacks_ret->save_yourself_phase2_request.manager_data = client; *mask_ret |= SmsSaveYourselfDoneProcMask; callbacks_ret->save_yourself_done.callback = save_yourself_done_callback; callbacks_ret->save_yourself_done.manager_data = client; *mask_ret |= SmsCloseConnectionProcMask; callbacks_ret->close_connection.callback = close_connection_callback; callbacks_ret->close_connection.manager_data = client; *mask_ret |= SmsSetPropertiesProcMask; callbacks_ret->set_properties.callback = set_properties_callback; callbacks_ret->set_properties.manager_data = client; *mask_ret |= SmsDeletePropertiesProcMask; callbacks_ret->delete_properties.callback = delete_properties_callback; callbacks_ret->delete_properties.manager_data = client; *mask_ret |= SmsGetPropertiesProcMask; callbacks_ret->get_properties.callback = get_properties_callback; callbacks_ret->get_properties.manager_data = client; } Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists We used to create the GsmXSMPClient before the XSMP connection is really accepted. This can lead to some issues, though. An example is: https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting: "What is happening is that a new client (probably metacity in your case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION phase, which causes a new GsmXSMPClient to be added to the client store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client has had a chance to establish a xsmp connection, which means that client->priv->conn will not be initialized at the point that xsmp_stop is called on the new unregistered client." The fix is to create the GsmXSMPClient object when there's a real XSMP connection. This implies moving the timeout that makes sure we don't have an empty client to the XSMP server. https://bugzilla.gnome.org/show_bug.cgi?id=598211 CWE ID: CWE-835
gsm_xsmp_client_connect (GsmXSMPClient *client, SmsConn conn, unsigned long *mask_ret, SmsCallbacks *callbacks_ret) { client->priv->conn = conn; g_debug ("GsmXSMPClient: Initializing client %s", client->priv->description); *mask_ret = 0; *mask_ret |= SmsRegisterClientProcMask; callbacks_ret->register_client.callback = register_client_callback; callbacks_ret->register_client.manager_data = client; *mask_ret |= SmsInteractRequestProcMask; callbacks_ret->interact_request.callback = interact_request_callback; callbacks_ret->interact_request.manager_data = client; *mask_ret |= SmsInteractDoneProcMask; callbacks_ret->interact_done.callback = interact_done_callback; callbacks_ret->interact_done.manager_data = client; *mask_ret |= SmsSaveYourselfRequestProcMask; callbacks_ret->save_yourself_request.callback = save_yourself_request_callback; callbacks_ret->save_yourself_request.manager_data = client; *mask_ret |= SmsSaveYourselfP2RequestProcMask; callbacks_ret->save_yourself_phase2_request.callback = save_yourself_phase2_request_callback; callbacks_ret->save_yourself_phase2_request.manager_data = client; *mask_ret |= SmsSaveYourselfDoneProcMask; callbacks_ret->save_yourself_done.callback = save_yourself_done_callback; callbacks_ret->save_yourself_done.manager_data = client; *mask_ret |= SmsCloseConnectionProcMask; callbacks_ret->close_connection.callback = close_connection_callback; callbacks_ret->close_connection.manager_data = client; *mask_ret |= SmsSetPropertiesProcMask; callbacks_ret->set_properties.callback = set_properties_callback; callbacks_ret->set_properties.manager_data = client; *mask_ret |= SmsDeletePropertiesProcMask; callbacks_ret->delete_properties.callback = delete_properties_callback; callbacks_ret->delete_properties.manager_data = client; *mask_ret |= SmsGetPropertiesProcMask; callbacks_ret->get_properties.callback = get_properties_callback; callbacks_ret->get_properties.manager_data = client; }
168,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; } Commit Message: Check effect command reply size in AudioFlinger Bug: 29251553 Change-Id: I1bcc1281f1f0542bb645f6358ce31631f2a8ffbf CWE ID: CWE-20
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; }
173,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int check_mtab(const char *progname, const char *devname, const char *dir) { if (check_newline(progname, devname) == -1 || check_newline(progname, dir) == -1) return EX_USAGE; return 0; } Commit Message: CWE ID: CWE-20
static int check_mtab(const char *progname, const char *devname, const char *dir) { if (check_newline(progname, devname) || check_newline(progname, dir)) return EX_USAGE; return 0; }
164,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GLES2DecoderImpl::TexStorageImpl(GLenum target, GLsizei levels, GLenum internal_format, GLsizei width, GLsizei height, GLsizei depth, ContextState::Dimension dimension, const char* function_name) { if (levels == 0) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "levels == 0"); return; } bool is_compressed_format = IsCompressedTextureFormat(internal_format); if (is_compressed_format && target == GL_TEXTURE_3D) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "target invalid for format"); return; } bool is_invalid_texstorage_size = width < 1 || height < 1 || depth < 1; if (!texture_manager()->ValidForTarget(target, 0, width, height, depth) || is_invalid_texstorage_size || TextureManager::ComputeMipMapCount(target, width, height, depth) < levels) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, function_name, "dimensions out of range"); return; } TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( &state_, target); if (!texture_ref) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "unknown texture for target"); return; } Texture* texture = texture_ref->texture(); if (texture->IsAttachedToFramebuffer()) { framebuffer_state_.clear_state_dirty = true; } if (texture->IsImmutable()) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "texture is immutable"); return; } GLenum format = TextureManager::ExtractFormatFromStorageFormat( internal_format); GLenum type = TextureManager::ExtractTypeFromStorageFormat(internal_format); { GLsizei level_width = width; GLsizei level_height = height; GLsizei level_depth = depth; base::CheckedNumeric<uint32_t> estimated_size(0); PixelStoreParams params; params.alignment = 1; for (int ii = 0; ii < levels; ++ii) { uint32_t size; if (is_compressed_format) { GLsizei level_size; if (!GetCompressedTexSizeInBytes( function_name, level_width, level_height, level_depth, internal_format, &level_size, state_.GetErrorState())) { return; } size = static_cast<uint32_t>(level_size); } else { if (!GLES2Util::ComputeImageDataSizesES3(level_width, level_height, level_depth, format, type, params, &size, nullptr, nullptr, nullptr, nullptr)) { LOCAL_SET_GL_ERROR( GL_OUT_OF_MEMORY, function_name, "dimensions too large"); return; } } estimated_size += size; level_width = std::max(1, level_width >> 1); level_height = std::max(1, level_height >> 1); if (target == GL_TEXTURE_3D) level_depth = std::max(1, level_depth >> 1); } if (!estimated_size.IsValid()) { LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, function_name, "out of memory"); return; } } GLenum compatibility_internal_format = texture_manager()->AdjustTexStorageFormat(feature_info_.get(), internal_format); const CompressedFormatInfo* format_info = GetCompressedFormatInfo(internal_format); if (format_info != nullptr && !format_info->support_check(*feature_info_)) { compatibility_internal_format = format_info->decompressed_internal_format; } if (workarounds().reset_base_mipmap_level_before_texstorage && texture->base_level() > 0) api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); if (dimension == ContextState::k2D) { api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, width, height); } else { api()->glTexStorage3DFn(target, levels, compatibility_internal_format, width, height, depth); } if (workarounds().reset_base_mipmap_level_before_texstorage && texture->base_level() > 0) api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, texture->base_level()); { GLsizei level_width = width; GLsizei level_height = height; GLsizei level_depth = depth; GLenum adjusted_internal_format = feature_info_->IsWebGL1OrES2Context() ? format : internal_format; for (int ii = 0; ii < levels; ++ii) { if (target == GL_TEXTURE_CUBE_MAP) { for (int jj = 0; jj < 6; ++jj) { GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X + jj; texture_manager()->SetLevelInfo( texture_ref, face, ii, adjusted_internal_format, level_width, level_height, 1, 0, format, type, gfx::Rect()); } } else { texture_manager()->SetLevelInfo( texture_ref, target, ii, adjusted_internal_format, level_width, level_height, level_depth, 0, format, type, gfx::Rect()); } level_width = std::max(1, level_width >> 1); level_height = std::max(1, level_height >> 1); if (target == GL_TEXTURE_3D) level_depth = std::max(1, level_depth >> 1); } texture->ApplyFormatWorkarounds(feature_info_.get()); texture->SetImmutable(true); } } Commit Message: Implement immutable texture base/max level clamping It seems some drivers fail to handle that gracefully, so let's always clamp to be on the safe side. BUG=877874 TEST=test case in the bug, gpu_unittests [email protected] 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: I6d93cb9389ea70525df4604112223604577582a2 Reviewed-on: https://chromium-review.googlesource.com/1194994 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#587264} CWE ID: CWE-119
void GLES2DecoderImpl::TexStorageImpl(GLenum target, GLsizei levels, GLenum internal_format, GLsizei width, GLsizei height, GLsizei depth, ContextState::Dimension dimension, const char* function_name) { if (levels == 0) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "levels == 0"); return; } bool is_compressed_format = IsCompressedTextureFormat(internal_format); if (is_compressed_format && target == GL_TEXTURE_3D) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "target invalid for format"); return; } bool is_invalid_texstorage_size = width < 1 || height < 1 || depth < 1; if (!texture_manager()->ValidForTarget(target, 0, width, height, depth) || is_invalid_texstorage_size || TextureManager::ComputeMipMapCount(target, width, height, depth) < levels) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, function_name, "dimensions out of range"); return; } TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( &state_, target); if (!texture_ref) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "unknown texture for target"); return; } Texture* texture = texture_ref->texture(); if (texture->IsAttachedToFramebuffer()) { framebuffer_state_.clear_state_dirty = true; } if (texture->IsImmutable()) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "texture is immutable"); return; } GLenum format = TextureManager::ExtractFormatFromStorageFormat( internal_format); GLenum type = TextureManager::ExtractTypeFromStorageFormat(internal_format); { GLsizei level_width = width; GLsizei level_height = height; GLsizei level_depth = depth; base::CheckedNumeric<uint32_t> estimated_size(0); PixelStoreParams params; params.alignment = 1; for (int ii = 0; ii < levels; ++ii) { uint32_t size; if (is_compressed_format) { GLsizei level_size; if (!GetCompressedTexSizeInBytes( function_name, level_width, level_height, level_depth, internal_format, &level_size, state_.GetErrorState())) { return; } size = static_cast<uint32_t>(level_size); } else { if (!GLES2Util::ComputeImageDataSizesES3(level_width, level_height, level_depth, format, type, params, &size, nullptr, nullptr, nullptr, nullptr)) { LOCAL_SET_GL_ERROR( GL_OUT_OF_MEMORY, function_name, "dimensions too large"); return; } } estimated_size += size; level_width = std::max(1, level_width >> 1); level_height = std::max(1, level_height >> 1); if (target == GL_TEXTURE_3D) level_depth = std::max(1, level_depth >> 1); } if (!estimated_size.IsValid()) { LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, function_name, "out of memory"); return; } } GLenum compatibility_internal_format = texture_manager()->AdjustTexStorageFormat(feature_info_.get(), internal_format); const CompressedFormatInfo* format_info = GetCompressedFormatInfo(internal_format); if (format_info != nullptr && !format_info->support_check(*feature_info_)) { compatibility_internal_format = format_info->decompressed_internal_format; } { GLsizei level_width = width; GLsizei level_height = height; GLsizei level_depth = depth; GLenum adjusted_internal_format = feature_info_->IsWebGL1OrES2Context() ? format : internal_format; for (int ii = 0; ii < levels; ++ii) { if (target == GL_TEXTURE_CUBE_MAP) { for (int jj = 0; jj < 6; ++jj) { GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X + jj; texture_manager()->SetLevelInfo( texture_ref, face, ii, adjusted_internal_format, level_width, level_height, 1, 0, format, type, gfx::Rect()); } } else { texture_manager()->SetLevelInfo( texture_ref, target, ii, adjusted_internal_format, level_width, level_height, level_depth, 0, format, type, gfx::Rect()); } level_width = std::max(1, level_width >> 1); level_height = std::max(1, level_height >> 1); if (target == GL_TEXTURE_3D) level_depth = std::max(1, level_depth >> 1); } texture->ApplyFormatWorkarounds(feature_info_.get()); texture->SetImmutable(true); } if (workarounds().reset_base_mipmap_level_before_texstorage && texture->base_level() > 0) api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); // TODO(zmo): We might need to emulate TexStorage using TexImage or // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. if (dimension == ContextState::k2D) { api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, width, height); } else { api()->glTexStorage3DFn(target, levels, compatibility_internal_format, width, height, depth); } if (workarounds().reset_base_mipmap_level_before_texstorage && texture->base_level() > 0) { // Note base_level is already clamped due to texture->SetImmutable(true). // This is necessary for certain NVidia Linux drivers; otherwise they // may trigger segmentation fault. See https://crbug.com/877874. api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, texture->base_level()); } }
172,659
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_get_display_script) { get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_display_script) PHP_FUNCTION(locale_get_display_script) { get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,187
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); } Commit Message: CWE ID: CWE-125
walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL || str->pos == -1) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); }
164,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, size_t msg_len) { struct sock *sk = asoc->base.sk; int err = 0; long current_timeo = *timeo_p; DEFINE_WAIT(wait); pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc, *timeo_p, msg_len); /* Increment the association's refcnt. */ sctp_association_hold(asoc); /* Wait on the association specific sndbuf space. */ for (;;) { prepare_to_wait_exclusive(&asoc->wait, &wait, TASK_INTERRUPTIBLE); if (!*timeo_p) goto do_nonblock; if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING || asoc->base.dead) goto do_error; if (signal_pending(current)) goto do_interrupted; if (msg_len <= sctp_wspace(asoc)) break; /* Let another process have a go. Since we are going * to sleep anyway. */ release_sock(sk); current_timeo = schedule_timeout(current_timeo); BUG_ON(sk != asoc->base.sk); lock_sock(sk); *timeo_p = current_timeo; } out: finish_wait(&asoc->wait, &wait); /* Release the association's refcnt. */ sctp_association_put(asoc); return err; do_error: err = -EPIPE; goto out; do_interrupted: err = sock_intr_errno(*timeo_p); goto out; do_nonblock: err = -EAGAIN; goto out; } Commit Message: sctp: avoid BUG_ON on sctp_wait_for_sndbuf Alexander Popov reported that an application may trigger a BUG_ON in sctp_wait_for_sndbuf if the socket tx buffer is full, a thread is waiting on it to queue more data and meanwhile another thread peels off the association being used by the first thread. This patch replaces the BUG_ON call with a proper error handling. It will return -EPIPE to the original sendmsg call, similarly to what would have been done if the association wasn't found in the first place. Acked-by: Alexander Popov <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Reviewed-by: Xin Long <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, size_t msg_len) { struct sock *sk = asoc->base.sk; int err = 0; long current_timeo = *timeo_p; DEFINE_WAIT(wait); pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc, *timeo_p, msg_len); /* Increment the association's refcnt. */ sctp_association_hold(asoc); /* Wait on the association specific sndbuf space. */ for (;;) { prepare_to_wait_exclusive(&asoc->wait, &wait, TASK_INTERRUPTIBLE); if (!*timeo_p) goto do_nonblock; if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING || asoc->base.dead) goto do_error; if (signal_pending(current)) goto do_interrupted; if (msg_len <= sctp_wspace(asoc)) break; /* Let another process have a go. Since we are going * to sleep anyway. */ release_sock(sk); current_timeo = schedule_timeout(current_timeo); if (sk != asoc->base.sk) goto do_error; lock_sock(sk); *timeo_p = current_timeo; } out: finish_wait(&asoc->wait, &wait); /* Release the association's refcnt. */ sctp_association_put(asoc); return err; do_error: err = -EPIPE; goto out; do_interrupted: err = sock_intr_errno(*timeo_p); goto out; do_nonblock: err = -EAGAIN; goto out; }
168,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gfx::SwapResult GLSurfaceEGLSurfaceControl::CommitOverlayPlanes( PresentationCallback callback) { NOTREACHED(); return gfx::SwapResult::SWAP_FAILED; } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID:
gfx::SwapResult GLSurfaceEGLSurfaceControl::CommitOverlayPlanes( gfx::SwapResult GLSurfaceEGLSurfaceControl::PostSubBuffer( int x, int y, int width, int height, PresentationCallback callback) { NOTREACHED(); return gfx::SwapResult::SWAP_FAILED; }
172,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { xmlElementContentPtr ret = NULL, cur = NULL, n; const xmlChar *elem = NULL; GROW; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; SHRINK; if (RAW == ')') { if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); if (RAW == '*') { ret->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } return(ret); } if ((RAW == '(') || (RAW == '|')) { ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); } while (RAW == '|') { NEXT; if (elem == NULL) { ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (ret == NULL) return(NULL); ret->c1 = cur; if (cur != NULL) cur->parent = ret; cur = ret; } else { n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (n == NULL) return(NULL); n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (n->c1 != NULL) n->c1->parent = n; cur->c2 = n; if (n != NULL) n->parent = cur; cur = n; } SKIP_BLANKS; elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementMixedContentDecl : Name expected\n"); xmlFreeDocElementContent(ctxt->myDoc, cur); return(NULL); } SKIP_BLANKS; GROW; } if ((RAW == ')') && (NXT(1) == '*')) { if (elem != NULL) { cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur->c2 != NULL) cur->c2->parent = cur; } if (ret != NULL) ret->ocur = XML_ELEMENT_CONTENT_MULT; if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } SKIP(2); } else { xmlFreeDocElementContent(ctxt->myDoc, ret); xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL); return(NULL); } } else { xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL); } return(ret); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { xmlElementContentPtr ret = NULL, cur = NULL, n; const xmlChar *elem = NULL; GROW; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; SHRINK; if (RAW == ')') { if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); if (RAW == '*') { ret->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } return(ret); } if ((RAW == '(') || (RAW == '|')) { ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); } while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) { NEXT; if (elem == NULL) { ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (ret == NULL) return(NULL); ret->c1 = cur; if (cur != NULL) cur->parent = ret; cur = ret; } else { n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (n == NULL) return(NULL); n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (n->c1 != NULL) n->c1->parent = n; cur->c2 = n; if (n != NULL) n->parent = cur; cur = n; } SKIP_BLANKS; elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementMixedContentDecl : Name expected\n"); xmlFreeDocElementContent(ctxt->myDoc, cur); return(NULL); } SKIP_BLANKS; GROW; } if ((RAW == ')') && (NXT(1) == '*')) { if (elem != NULL) { cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur->c2 != NULL) cur->c2->parent = cur; } if (ret != NULL) ret->ocur = XML_ELEMENT_CONTENT_MULT; if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } SKIP(2); } else { xmlFreeDocElementContent(ctxt->myDoc, ret); xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL); return(NULL); } } else { xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL); } return(ret); }
171,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, int start, int count) { removed_count_++; } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None [email protected] Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, int start, int count) OVERRIDE { removed_count_++; }
170,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; } Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: [email protected] Cc: Jens Axboe <[email protected]> Cc: James Bottomley <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); error = scsi_verify_blk_ioctl(bdev, cmd); if (error < 0) return error; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; }
169,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, const u_char **pktdata, const char *funcname, const int line, const char *file) { int res = pcap_next_ex(pcap, pkthdr, pktdata); if (*pktdata && *pkthdr) { if ((*pkthdr)->len > MAXPACKET) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", file, funcname, line, (*pkthdr)->len, MAXPACKET); exit(-1); } if ((*pkthdr)->len < (*pkthdr)->caplen) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n", file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen); exit(-1); } } return res; } Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length Add check for packets that report zero packet length. Example of fix: src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets. safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0 CWE ID: CWE-125
int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, const u_char **pktdata, const char *funcname, const int line, const char *file) { int res = pcap_next_ex(pcap, pkthdr, pktdata); if (*pktdata && *pkthdr) { if ((*pkthdr)->len > MAXPACKET) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", file, funcname, line, (*pkthdr)->len, MAXPACKET); exit(-1); } if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n", file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen); exit(-1); } } return res; }
168,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p=(png_structp)png_ptr; png_uint_32 save_flags=p->flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p; png_uint_32 save_flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); p=(png_structp)png_ptr; save_flags=p->flags; if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); }
172,164
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b) { return b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24); } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b) { return (unsigned int)b[0] | ((unsigned int)b[1]<<8) | ((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24); }
168,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) { Resource::LastPluginRefWasDeleted(instance_destroyed); if (instance_destroyed) { loader_.reset(); } } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) { void PPB_URLLoader_Impl::ClearInstance() { Resource::ClearInstance(); loader_.reset(); }
170,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeContentRendererClient::ShouldFork(WebFrame* frame, const GURL& url, bool is_initial_navigation, bool* send_referrer) { DCHECK(!frame->parent()); if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url)) return true; const ExtensionSet* extensions = extension_dispatcher_->extensions(); const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension( *extensions, ExtensionURLInfo(url)); bool is_extension_url = !!new_url_extension; if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url, is_initial_navigation)) { *send_referrer = true; const Extension* extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL( ExtensionURLInfo(url)); if (extension && extension->is_app()) { UMA_HISTOGRAM_ENUMERATION( extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } return true; } if (frame->top()->document().url() == url) { if (is_extension_url != extension_dispatcher_->is_extension_process()) return true; } if (url.SchemeIs(kChromeUIScheme)) return true; return false; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeContentRendererClient::ShouldFork(WebFrame* frame, const GURL& url, bool is_initial_navigation, bool* send_referrer) { DCHECK(!frame->parent()); if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url)) return true; const ExtensionSet* extensions = extension_dispatcher_->extensions(); const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension( *extensions, ExtensionURLInfo(url)); bool is_extension_url = !!new_url_extension; if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url, is_initial_navigation)) { *send_referrer = true; const Extension* extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL( ExtensionURLInfo(url)); if (extension && extension->is_app()) { UMA_HISTOGRAM_ENUMERATION( extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } return true; } if (frame->top()->document().url() == url) { if (is_extension_url != extension_dispatcher_->is_extension_process()) return true; } return false; }
171,009
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { unsigned nbuf; unsigned idx; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_dev *fud; size_t rem; ssize_t ret; fud = fuse_get_dev(out); if (!fud) return -EPERM; pipe_lock(pipe); bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer), GFP_KERNEL); if (!bufs) { pipe_unlock(pipe); return -ENOMEM; } nbuf = 0; rem = 0; for (idx = 0; idx < pipe->nrbufs && rem < len; idx++) rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len; ret = -EINVAL; if (rem < len) { pipe_unlock(pipe); goto out; } rem = len; while (rem) { struct pipe_buffer *ibuf; struct pipe_buffer *obuf; BUG_ON(nbuf >= pipe->buffers); BUG_ON(!pipe->nrbufs); ibuf = &pipe->bufs[pipe->curbuf]; obuf = &bufs[nbuf]; if (rem >= ibuf->len) { *obuf = *ibuf; ibuf->ops = NULL; pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1); pipe->nrbufs--; } else { pipe_buf_get(pipe, ibuf); *obuf = *ibuf; obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } nbuf++; rem -= obuf->len; } pipe_unlock(pipe); fuse_copy_init(&cs, 0, NULL); cs.pipebufs = bufs; cs.nr_segs = nbuf; cs.pipe = pipe; if (flags & SPLICE_F_MOVE) cs.move_pages = 1; ret = fuse_dev_do_write(fud, &cs, len); pipe_lock(pipe); for (idx = 0; idx < nbuf; idx++) pipe_buf_release(pipe, &bufs[idx]); pipe_unlock(pipe); out: kvfree(bufs); return ret; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { unsigned nbuf; unsigned idx; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_dev *fud; size_t rem; ssize_t ret; fud = fuse_get_dev(out); if (!fud) return -EPERM; pipe_lock(pipe); bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer), GFP_KERNEL); if (!bufs) { pipe_unlock(pipe); return -ENOMEM; } nbuf = 0; rem = 0; for (idx = 0; idx < pipe->nrbufs && rem < len; idx++) rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len; ret = -EINVAL; if (rem < len) goto out_free; rem = len; while (rem) { struct pipe_buffer *ibuf; struct pipe_buffer *obuf; BUG_ON(nbuf >= pipe->buffers); BUG_ON(!pipe->nrbufs); ibuf = &pipe->bufs[pipe->curbuf]; obuf = &bufs[nbuf]; if (rem >= ibuf->len) { *obuf = *ibuf; ibuf->ops = NULL; pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1); pipe->nrbufs--; } else { if (!pipe_buf_get(pipe, ibuf)) goto out_free; *obuf = *ibuf; obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } nbuf++; rem -= obuf->len; } pipe_unlock(pipe); fuse_copy_init(&cs, 0, NULL); cs.pipebufs = bufs; cs.nr_segs = nbuf; cs.pipe = pipe; if (flags & SPLICE_F_MOVE) cs.move_pages = 1; ret = fuse_dev_do_write(fud, &cs, len); pipe_lock(pipe); out_free: for (idx = 0; idx < nbuf; idx++) pipe_buf_release(pipe, &bufs[idx]); pipe_unlock(pipe); kvfree(bufs); return ret; }
170,217
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnGraphicBufferProducer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case REQUEST_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferIdx = data.readInt32(); sp<GraphicBuffer> buffer; int result = requestBuffer(bufferIdx, &buffer); reply->writeInt32(buffer != 0); if (buffer != 0) { reply->write(*buffer); } reply->writeInt32(result); return NO_ERROR; } break; case SET_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferCount = data.readInt32(); int result = setBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } break; case DEQUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = data.readInt32(); uint32_t w = data.readInt32(); uint32_t h = data.readInt32(); uint32_t format = data.readInt32(); uint32_t usage = data.readInt32(); int buf = 0; sp<Fence> fence; int result = dequeueBuffer(&buf, &fence, async, w, h, format, usage); reply->writeInt32(buf); reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } reply->writeInt32(result); return NO_ERROR; } break; case QUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); QueueBufferInput input(data); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t result = queueBuffer(buf, input, output); reply->writeInt32(result); return NO_ERROR; } break; case CANCEL_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); sp<Fence> fence = new Fence(); data.read(*fence.get()); cancelBuffer(buf, fence); return NO_ERROR; } break; case QUERY: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int value = 0; int what = data.readInt32(); int res = query(what, &value); reply->writeInt32(value); reply->writeInt32(res); return NO_ERROR; } break; case CONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<IBinder> token = data.readStrongBinder(); int api = data.readInt32(); bool producerControlledByApp = data.readInt32(); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t res = connect(token, api, producerControlledByApp, output); reply->writeInt32(res); return NO_ERROR; } break; case DISCONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int api = data.readInt32(); status_t res = disconnect(api); reply->writeInt32(res); return NO_ERROR; } break; } return BBinder::onTransact(code, data, reply, flags); } Commit Message: IGraphicBufferProducer: fix QUEUE_BUFFER info leak Bug: 26338109 Change-Id: I8a979469bfe1e317ebdefa43685e19f9302baea8 CWE ID: CWE-254
status_t BnGraphicBufferProducer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case REQUEST_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferIdx = data.readInt32(); sp<GraphicBuffer> buffer; int result = requestBuffer(bufferIdx, &buffer); reply->writeInt32(buffer != 0); if (buffer != 0) { reply->write(*buffer); } reply->writeInt32(result); return NO_ERROR; } break; case SET_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferCount = data.readInt32(); int result = setBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } break; case DEQUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = data.readInt32(); uint32_t w = data.readInt32(); uint32_t h = data.readInt32(); uint32_t format = data.readInt32(); uint32_t usage = data.readInt32(); int buf = 0; sp<Fence> fence; int result = dequeueBuffer(&buf, &fence, async, w, h, format, usage); reply->writeInt32(buf); reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } reply->writeInt32(result); return NO_ERROR; } break; case QUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); QueueBufferInput input(data); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); memset(output, 0, sizeof(QueueBufferOutput)); status_t result = queueBuffer(buf, input, output); reply->writeInt32(result); return NO_ERROR; } break; case CANCEL_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); sp<Fence> fence = new Fence(); data.read(*fence.get()); cancelBuffer(buf, fence); return NO_ERROR; } break; case QUERY: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int value = 0; int what = data.readInt32(); int res = query(what, &value); reply->writeInt32(value); reply->writeInt32(res); return NO_ERROR; } break; case CONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<IBinder> token = data.readStrongBinder(); int api = data.readInt32(); bool producerControlledByApp = data.readInt32(); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t res = connect(token, api, producerControlledByApp, output); reply->writeInt32(res); return NO_ERROR; } break; case DISCONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int api = data.readInt32(); status_t res = disconnect(api); reply->writeInt32(res); return NO_ERROR; } break; } return BBinder::onTransact(code, data, reply, flags); }
173,932
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: init_ctx_reselect(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, OM_uint32 acc_negState, gss_OID supportedMech, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 tmpmin; size_t i; generic_gss_release_oid(&tmpmin, &sc->internal_mech); gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); /* Find supportedMech in sc->mech_set. */ for (i = 0; i < sc->mech_set->count; i++) { if (g_OID_equal(supportedMech, &sc->mech_set->elements[i])) break; } if (i == sc->mech_set->count) return GSS_S_DEFECTIVE_TOKEN; sc->internal_mech = &sc->mech_set->elements[i]; /* * Windows 2003 and earlier don't correctly send a * negState of request-mic when counter-proposing a * mechanism. They probably don't handle mechListMICs * properly either. */ if (acc_negState != REQUEST_MIC) return GSS_S_DEFECTIVE_TOKEN; sc->mech_complete = 0; sc->mic_reqd = 1; *negState = REQUEST_MIC; *tokflag = CONT_TOKEN_SEND; return GSS_S_CONTINUE_NEEDED; } Commit Message: Fix double-free in SPNEGO [CVE-2014-4343] In commit cd7d6b08 ("Verify acceptor's mech in SPNEGO initiator") the pointer sc->internal_mech became an alias into sc->mech_set->elements, which should be considered constant for the duration of the SPNEGO context. So don't free it. CVE-2014-4343: In MIT krb5 releases 1.10 and newer, an unauthenticated remote attacker with the ability to spoof packets appearing to be from a GSSAPI acceptor can cause a double-free condition in GSSAPI initiators (clients) which are using the SPNEGO mechanism, by returning a different underlying mechanism than was proposed by the initiator. At this stage of the negotiation, the acceptor is unauthenticated, and the acceptor's response could be spoofed by an attacker with the ability to inject traffic to the initiator. Historically, some double-free vulnerabilities can be translated into remote code execution, though the necessary exploits must be tailored to the individual application and are usually quite complicated. Double-frees can also be exploited to cause an application crash, for a denial of service. However, most GSSAPI client applications are not vulnerable, as the SPNEGO mechanism is not used by default (when GSS_C_NO_OID is passed as the mech_type argument to gss_init_sec_context()). The most common use of SPNEGO is for HTTP-Negotiate, used in web browsers and other web clients. Most such clients are believed to not offer HTTP-Negotiate by default, instead requiring a whitelist of sites for which it may be used to be configured. If the whitelist is configured to only allow HTTP-Negotiate over TLS connections ("https://"), a successful attacker must also spoof the web server's SSL certificate, due to the way the WWW-Authenticate header is sent in a 401 (Unauthorized) response message. Unfortunately, many instructions for enabling HTTP-Negotiate in common web browsers do not include a TLS requirement. CVSSv2 Vector: AV:N/AC:H/Au:N/C:C/I:C/A:C/E:POC/RL:OF/RC:C [[email protected]: CVE summary and CVSSv2 vector] ticket: 7969 (new) target_version: 1.12.2 tags: pullup CWE ID: CWE-415
init_ctx_reselect(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, OM_uint32 acc_negState, gss_OID supportedMech, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 tmpmin; size_t i; gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); /* Find supportedMech in sc->mech_set. */ for (i = 0; i < sc->mech_set->count; i++) { if (g_OID_equal(supportedMech, &sc->mech_set->elements[i])) break; } if (i == sc->mech_set->count) return GSS_S_DEFECTIVE_TOKEN; sc->internal_mech = &sc->mech_set->elements[i]; /* * Windows 2003 and earlier don't correctly send a * negState of request-mic when counter-proposing a * mechanism. They probably don't handle mechListMICs * properly either. */ if (acc_negState != REQUEST_MIC) return GSS_S_DEFECTIVE_TOKEN; sc->mech_complete = 0; sc->mic_reqd = 1; *negState = REQUEST_MIC; *tokflag = CONT_TOKEN_SEND; return GSS_S_CONTINUE_NEEDED; }
166,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl, ivd_video_decode_op_t *ps_dec_op, UWORD8 *pu1_buf, UWORD32 u4_length) { dec_bit_stream_t *ps_bitstrm; dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle; ivd_video_decode_ip_t *ps_dec_in = (ivd_video_decode_ip_t *)ps_dec->pv_dec_in; dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice; UWORD8 u1_first_byte, u1_nal_ref_idc; UWORD8 u1_nal_unit_type; WORD32 i_status = OK; ps_bitstrm = ps_dec->ps_bitstrm; if(pu1_buf) { if(u4_length) { ps_dec_op->u4_frame_decoded_flag = 0; ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf, u4_length); SWITCHOFFTRACE; u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8); if(NAL_FORBIDDEN_BIT(u1_first_byte)) { H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n"); } u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte); ps_dec->u1_nal_unit_type = u1_nal_unit_type; u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte)); switch(u1_nal_unit_type) { case SLICE_DATA_PARTITION_A_NAL: case SLICE_DATA_PARTITION_B_NAL: case SLICE_DATA_PARTITION_C_NAL: if(!ps_dec->i4_decode_header) ih264d_parse_slice_partition(ps_dec, ps_bitstrm); break; case IDR_SLICE_NAL: case SLICE_NAL: /* ! */ DEBUG_THREADS_PRINTF("Decoding a slice NAL\n"); if(!ps_dec->i4_decode_header) { if(ps_dec->i4_header_decoded == 3) { /* ! */ ps_dec->u4_slice_start_code_found = 1; ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_decode_slice( (UWORD8)(u1_nal_unit_type == IDR_SLICE_NAL), u1_nal_ref_idc, ps_dec); if((ps_dec->u4_first_slice_in_pic != 0)&& ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)) { /* if the first slice header was not valid set to 1 */ ps_dec->u4_first_slice_in_pic = 1; } if(i_status != OK) { return i_status; } } else { H264_DEC_DEBUG_PRINT( "\nSlice NAL Supplied but no header has been supplied\n"); } } break; case SEI_NAL: if(!ps_dec->i4_decode_header) { ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm); if(i_status != OK) return i_status; ih264d_parse_sei(ps_dec, ps_bitstrm); } break; case SEQ_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x1; break; case PIC_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_pps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x2; break; case ACCESS_UNIT_DELIMITER_RBSP: if(!ps_dec->i4_decode_header) { ih264d_access_unit_delimiter_rbsp(ps_dec); } break; case END_OF_STREAM_RBSP: if(!ps_dec->i4_decode_header) { ih264d_parse_end_of_stream(ps_dec); } break; case FILLER_DATA_NAL: if(!ps_dec->i4_decode_header) { ih264d_parse_filler_data(ps_dec, ps_bitstrm); } break; default: H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type); break; } } } return i_status; } Commit Message: Decoder: Fix slice number increment for error clips Bug: 28673410 CWE ID: CWE-119
WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl, ivd_video_decode_op_t *ps_dec_op, UWORD8 *pu1_buf, UWORD32 u4_length) { dec_bit_stream_t *ps_bitstrm; dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle; ivd_video_decode_ip_t *ps_dec_in = (ivd_video_decode_ip_t *)ps_dec->pv_dec_in; dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice; UWORD8 u1_first_byte, u1_nal_ref_idc; UWORD8 u1_nal_unit_type; WORD32 i_status = OK; ps_bitstrm = ps_dec->ps_bitstrm; if(pu1_buf) { if(u4_length) { ps_dec_op->u4_frame_decoded_flag = 0; ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf, u4_length); SWITCHOFFTRACE; u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8); if(NAL_FORBIDDEN_BIT(u1_first_byte)) { H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n"); } u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte); // if any other nal unit other than slice nal is encountered in between a // frame break out of loop without consuming header if((ps_dec->u2_total_mbs_coded != 0) && (u1_nal_unit_type > IDR_SLICE_NAL)) { return ERROR_INCOMPLETE_FRAME; } ps_dec->u1_nal_unit_type = u1_nal_unit_type; u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte)); switch(u1_nal_unit_type) { case SLICE_DATA_PARTITION_A_NAL: case SLICE_DATA_PARTITION_B_NAL: case SLICE_DATA_PARTITION_C_NAL: if(!ps_dec->i4_decode_header) ih264d_parse_slice_partition(ps_dec, ps_bitstrm); break; case IDR_SLICE_NAL: case SLICE_NAL: /* ! */ DEBUG_THREADS_PRINTF("Decoding a slice NAL\n"); if(!ps_dec->i4_decode_header) { if(ps_dec->i4_header_decoded == 3) { /* ! */ ps_dec->u4_slice_start_code_found = 1; ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_decode_slice( (UWORD8)(u1_nal_unit_type == IDR_SLICE_NAL), u1_nal_ref_idc, ps_dec); if((ps_dec->u4_first_slice_in_pic != 0)&& ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)) { /* if the first slice header was not valid set to 1 */ ps_dec->u4_first_slice_in_pic = 1; } if(i_status != OK) { return i_status; } } else { H264_DEC_DEBUG_PRINT( "\nSlice NAL Supplied but no header has been supplied\n"); } } break; case SEI_NAL: if(!ps_dec->i4_decode_header) { ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm); if(i_status != OK) return i_status; ih264d_parse_sei(ps_dec, ps_bitstrm); } break; case SEQ_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x1; break; case PIC_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_pps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x2; break; case ACCESS_UNIT_DELIMITER_RBSP: if(!ps_dec->i4_decode_header) { ih264d_access_unit_delimiter_rbsp(ps_dec); } break; case END_OF_STREAM_RBSP: if(!ps_dec->i4_decode_header) { ih264d_parse_end_of_stream(ps_dec); } break; case FILLER_DATA_NAL: if(!ps_dec->i4_decode_header) { ih264d_parse_filler_data(ps_dec, ps_bitstrm); } break; default: H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type); break; } } } return i_status; }
173,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf) { SCSIRequest *req = &r->req; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); uint64_t nb_sectors; int buflen = 0; switch (req->cmd.buf[0]) { case TEST_UNIT_READY: if (s->tray_open || !bdrv_is_inserted(s->bs)) goto not_ready; break; case INQUIRY: buflen = scsi_disk_emulate_inquiry(req, outbuf); if (buflen < 0) goto illegal_request; break; case MODE_SENSE: case MODE_SENSE_10: buflen = scsi_disk_emulate_mode_sense(r, outbuf); if (buflen < 0) goto illegal_request; break; case READ_TOC: buflen = scsi_disk_emulate_read_toc(req, outbuf); if (buflen < 0) goto illegal_request; break; case RESERVE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RESERVE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case RELEASE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RELEASE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case START_STOP: if (scsi_disk_emulate_start_stop(r) < 0) { return -1; } break; case ALLOW_MEDIUM_REMOVAL: s->tray_locked = req->cmd.buf[4] & 1; bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1); break; case READ_CAPACITY_10: /* The normal LEN field for this command is zero. */ memset(outbuf, 0, 8); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; /* Clip to 2TB, instead of returning capacity modulo 2TB. */ if (nb_sectors > UINT32_MAX) nb_sectors = UINT32_MAX; outbuf[0] = (nb_sectors >> 24) & 0xff; outbuf[1] = (nb_sectors >> 16) & 0xff; outbuf[2] = (nb_sectors >> 8) & 0xff; outbuf[3] = nb_sectors & 0xff; outbuf[4] = 0; outbuf[5] = 0; outbuf[6] = s->cluster_size * 2; outbuf[7] = 0; buflen = 8; break; case GET_CONFIGURATION: memset(outbuf, 0, 8); /* ??? This should probably return much more information. For now just return the basic header indicating the CD-ROM profile. */ outbuf[7] = 8; // CD-ROM buflen = 8; break; case SERVICE_ACTION_IN_16: /* Service Action In subcommands. */ if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) { DPRINTF("SAI READ CAPACITY(16)\n"); memset(outbuf, 0, req->cmd.xfer); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; outbuf[0] = (nb_sectors >> 56) & 0xff; outbuf[1] = (nb_sectors >> 48) & 0xff; outbuf[2] = (nb_sectors >> 40) & 0xff; outbuf[3] = (nb_sectors >> 32) & 0xff; outbuf[4] = (nb_sectors >> 24) & 0xff; outbuf[5] = (nb_sectors >> 16) & 0xff; outbuf[6] = (nb_sectors >> 8) & 0xff; outbuf[7] = nb_sectors & 0xff; outbuf[8] = 0; outbuf[9] = 0; outbuf[10] = s->cluster_size * 2; outbuf[11] = 0; outbuf[12] = 0; outbuf[13] = get_physical_block_exp(&s->qdev.conf); /* set TPE bit if the format supports discard */ if (s->qdev.conf.discard_granularity) { outbuf[14] = 0x80; } /* Protection, exponent and lowest lba field left blank. */ buflen = req->cmd.xfer; break; } DPRINTF("Unsupported Service Action In\n"); goto illegal_request; case VERIFY_10: break; default: scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return -1; } return buflen; not_ready: if (s->tray_open || !bdrv_is_inserted(s->bs)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); } else { scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY)); } return -1; illegal_request: if (r->req.status == -1) { scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); } return -1; } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf) static int scsi_disk_emulate_command(SCSIDiskReq *r) { SCSIRequest *req = &r->req; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); uint64_t nb_sectors; uint8_t *outbuf; int buflen = 0; if (!r->iov.iov_base) { /* * FIXME: we shouldn't return anything bigger than 4k, but the code * requires the buffer to be as big as req->cmd.xfer in several * places. So, do not allow CDBs with a very large ALLOCATION * LENGTH. The real fix would be to modify scsi_read_data and * dma_buf_read, so that they return data beyond the buflen * as all zeros. */ if (req->cmd.xfer > 65536) { goto illegal_request; } r->buflen = MAX(4096, req->cmd.xfer); r->iov.iov_base = qemu_blockalign(s->bs, r->buflen); } outbuf = r->iov.iov_base; switch (req->cmd.buf[0]) { case TEST_UNIT_READY: if (s->tray_open || !bdrv_is_inserted(s->bs)) goto not_ready; break; case INQUIRY: buflen = scsi_disk_emulate_inquiry(req, outbuf); if (buflen < 0) goto illegal_request; break; case MODE_SENSE: case MODE_SENSE_10: buflen = scsi_disk_emulate_mode_sense(r, outbuf); if (buflen < 0) goto illegal_request; break; case READ_TOC: buflen = scsi_disk_emulate_read_toc(req, outbuf); if (buflen < 0) goto illegal_request; break; case RESERVE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RESERVE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case RELEASE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RELEASE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case START_STOP: if (scsi_disk_emulate_start_stop(r) < 0) { return -1; } break; case ALLOW_MEDIUM_REMOVAL: s->tray_locked = req->cmd.buf[4] & 1; bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1); break; case READ_CAPACITY_10: /* The normal LEN field for this command is zero. */ memset(outbuf, 0, 8); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; /* Clip to 2TB, instead of returning capacity modulo 2TB. */ if (nb_sectors > UINT32_MAX) nb_sectors = UINT32_MAX; outbuf[0] = (nb_sectors >> 24) & 0xff; outbuf[1] = (nb_sectors >> 16) & 0xff; outbuf[2] = (nb_sectors >> 8) & 0xff; outbuf[3] = nb_sectors & 0xff; outbuf[4] = 0; outbuf[5] = 0; outbuf[6] = s->cluster_size * 2; outbuf[7] = 0; buflen = 8; break; case GET_CONFIGURATION: memset(outbuf, 0, 8); /* ??? This should probably return much more information. For now just return the basic header indicating the CD-ROM profile. */ outbuf[7] = 8; // CD-ROM buflen = 8; break; case SERVICE_ACTION_IN_16: /* Service Action In subcommands. */ if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) { DPRINTF("SAI READ CAPACITY(16)\n"); memset(outbuf, 0, req->cmd.xfer); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; outbuf[0] = (nb_sectors >> 56) & 0xff; outbuf[1] = (nb_sectors >> 48) & 0xff; outbuf[2] = (nb_sectors >> 40) & 0xff; outbuf[3] = (nb_sectors >> 32) & 0xff; outbuf[4] = (nb_sectors >> 24) & 0xff; outbuf[5] = (nb_sectors >> 16) & 0xff; outbuf[6] = (nb_sectors >> 8) & 0xff; outbuf[7] = nb_sectors & 0xff; outbuf[8] = 0; outbuf[9] = 0; outbuf[10] = s->cluster_size * 2; outbuf[11] = 0; outbuf[12] = 0; outbuf[13] = get_physical_block_exp(&s->qdev.conf); /* set TPE bit if the format supports discard */ if (s->qdev.conf.discard_granularity) { outbuf[14] = 0x80; } /* Protection, exponent and lowest lba field left blank. */ buflen = req->cmd.xfer; break; } DPRINTF("Unsupported Service Action In\n"); goto illegal_request; case VERIFY_10: break; default: scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return -1; } return buflen; not_ready: if (s->tray_open || !bdrv_is_inserted(s->bs)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); } else { scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY)); } return -1; illegal_request: if (r->req.status == -1) { scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); } return -1; }
166,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (send(client_socket_, data, length, 0) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (TEMP_FAILURE_RETRY(send(client_socket_, data, length, 0)) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); }
173,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", "notifications", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); }
173,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int hci_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr; struct sock *sk = sock->sk; struct hci_dev *hdev = hci_pi(sk)->hdev; BT_DBG("sock %p sk %p", sock, sk); if (!hdev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*haddr); haddr->hci_family = AF_BLUETOOTH; haddr->hci_dev = hdev->id; release_sock(sk); return 0; } Commit Message: Bluetooth: HCI - Fix info leak via getsockname() The HCI code fails to initialize the hci_channel member of struct sockaddr_hci and that for leaks two bytes kernel stack via the getsockname() syscall. Initialize hci_channel with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int hci_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr; struct sock *sk = sock->sk; struct hci_dev *hdev = hci_pi(sk)->hdev; BT_DBG("sock %p sk %p", sock, sk); if (!hdev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*haddr); haddr->hci_family = AF_BLUETOOTH; haddr->hci_dev = hdev->id; haddr->hci_channel= 0; release_sock(sk); return 0; }
169,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size; if (pkg->body_size > RPC_PKG_MAX_BODY_SIZE) { return -1; } pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); if (send_buf == NULL) { return -1; } } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; }
169,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_reset(struct perf_event *event) { (void)perf_event_read(event); local64_set(&event->count, 0); perf_event_update_userpage(event); } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
static void perf_event_reset(struct perf_event *event) static void _perf_event_reset(struct perf_event *event) { (void)perf_event_read(event); local64_set(&event->count, 0); perf_event_update_userpage(event); }
166,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeFrontendPath(const std::string& path) { for (size_t i = 0; i < path.length(); i++) { if (path[i] != '/' && path[i] != '-' && path[i] != '_' && path[i] != '.' && path[i] != '@' && !(path[i] >= '0' && path[i] <= '9') && !(path[i] >= 'a' && path[i] <= 'z') && !(path[i] >= 'A' && path[i] <= 'Z')) { return std::string(); } } return path; } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeFrontendPath(const std::string& path) {
172,458
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PageRequestSummary::UpdateOrAddToOrigins( const content::mojom::ResourceLoadInfo& resource_load_info) { for (const auto& redirect_info : resource_load_info.redirect_info_chain) UpdateOrAddToOrigins(redirect_info->url, redirect_info->network_info); UpdateOrAddToOrigins(resource_load_info.url, resource_load_info.network_info); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PageRequestSummary::UpdateOrAddToOrigins( const content::mojom::ResourceLoadInfo& resource_load_info) { for (const auto& redirect_info : resource_load_info.redirect_info_chain) { UpdateOrAddToOrigins(url::Origin::Create(redirect_info->url), redirect_info->network_info); } UpdateOrAddToOrigins(url::Origin::Create(resource_load_info.url), resource_load_info.network_info); }
172,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void i2c_deblock_gpio_cfg(void) { /* set I2C bus 1 deblocking GPIOs input, but 0 value for open drain */ qrio_gpio_direction_input(DEBLOCK_PORT1, DEBLOCK_SCL1); qrio_gpio_direction_input(DEBLOCK_PORT1, DEBLOCK_SDA1); qrio_set_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1, 0); qrio_set_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1, 0); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
static void i2c_deblock_gpio_cfg(void)
169,631
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } fclose(fp); return true; } Commit Message: ccpp: fix symlink race conditions Fix copy & chown race conditions Related: #1211835 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59
static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs) static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; }
170,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::Release() { DCHECK(agent_.get()); DCHECK(pairing_delegate_); VLOG(1) << object_path_.value() << ": Release"; pincode_callback_.Reset(); passkey_callback_.Reset(); confirmation_callback_.Reset(); UnregisterAgent(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::Release() {
171,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t ib_uverbs_write(struct file *filp, const char __user *buf, size_t count, loff_t *pos) { struct ib_uverbs_file *file = filp->private_data; struct ib_device *ib_dev; struct ib_uverbs_cmd_hdr hdr; __u32 command; __u32 flags; int srcu_key; ssize_t ret; if (count < sizeof hdr) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof hdr)) return -EFAULT; srcu_key = srcu_read_lock(&file->device->disassociate_srcu); ib_dev = srcu_dereference(file->device->ib_dev, &file->device->disassociate_srcu); if (!ib_dev) { ret = -EIO; goto out; } if (hdr.command & ~(__u32)(IB_USER_VERBS_CMD_FLAGS_MASK | IB_USER_VERBS_CMD_COMMAND_MASK)) { ret = -EINVAL; goto out; } command = hdr.command & IB_USER_VERBS_CMD_COMMAND_MASK; if (verify_command_mask(ib_dev, command)) { ret = -EOPNOTSUPP; goto out; } if (!file->ucontext && command != IB_USER_VERBS_CMD_GET_CONTEXT) { ret = -EINVAL; goto out; } flags = (hdr.command & IB_USER_VERBS_CMD_FLAGS_MASK) >> IB_USER_VERBS_CMD_FLAGS_SHIFT; if (!flags) { if (command >= ARRAY_SIZE(uverbs_cmd_table) || !uverbs_cmd_table[command]) { ret = -EINVAL; goto out; } if (hdr.in_words * 4 != count) { ret = -EINVAL; goto out; } ret = uverbs_cmd_table[command](file, ib_dev, buf + sizeof(hdr), hdr.in_words * 4, hdr.out_words * 4); } else if (flags == IB_USER_VERBS_CMD_FLAG_EXTENDED) { struct ib_uverbs_ex_cmd_hdr ex_hdr; struct ib_udata ucore; struct ib_udata uhw; size_t written_count = count; if (command >= ARRAY_SIZE(uverbs_ex_cmd_table) || !uverbs_ex_cmd_table[command]) { ret = -ENOSYS; goto out; } if (!file->ucontext) { ret = -EINVAL; goto out; } if (count < (sizeof(hdr) + sizeof(ex_hdr))) { ret = -EINVAL; goto out; } if (copy_from_user(&ex_hdr, buf + sizeof(hdr), sizeof(ex_hdr))) { ret = -EFAULT; goto out; } count -= sizeof(hdr) + sizeof(ex_hdr); buf += sizeof(hdr) + sizeof(ex_hdr); if ((hdr.in_words + ex_hdr.provider_in_words) * 8 != count) { ret = -EINVAL; goto out; } if (ex_hdr.cmd_hdr_reserved) { ret = -EINVAL; goto out; } if (ex_hdr.response) { if (!hdr.out_words && !ex_hdr.provider_out_words) { ret = -EINVAL; goto out; } if (!access_ok(VERIFY_WRITE, (void __user *) (unsigned long) ex_hdr.response, (hdr.out_words + ex_hdr.provider_out_words) * 8)) { ret = -EFAULT; goto out; } } else { if (hdr.out_words || ex_hdr.provider_out_words) { ret = -EINVAL; goto out; } } INIT_UDATA_BUF_OR_NULL(&ucore, buf, (unsigned long) ex_hdr.response, hdr.in_words * 8, hdr.out_words * 8); INIT_UDATA_BUF_OR_NULL(&uhw, buf + ucore.inlen, (unsigned long) ex_hdr.response + ucore.outlen, ex_hdr.provider_in_words * 8, ex_hdr.provider_out_words * 8); ret = uverbs_ex_cmd_table[command](file, ib_dev, &ucore, &uhw); if (!ret) ret = written_count; } else { ret = -ENOSYS; } out: srcu_read_unlock(&file->device->disassociate_srcu, srcu_key); return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264
static ssize_t ib_uverbs_write(struct file *filp, const char __user *buf, size_t count, loff_t *pos) { struct ib_uverbs_file *file = filp->private_data; struct ib_device *ib_dev; struct ib_uverbs_cmd_hdr hdr; __u32 command; __u32 flags; int srcu_key; ssize_t ret; if (WARN_ON_ONCE(!ib_safe_file_access(filp))) return -EACCES; if (count < sizeof hdr) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof hdr)) return -EFAULT; srcu_key = srcu_read_lock(&file->device->disassociate_srcu); ib_dev = srcu_dereference(file->device->ib_dev, &file->device->disassociate_srcu); if (!ib_dev) { ret = -EIO; goto out; } if (hdr.command & ~(__u32)(IB_USER_VERBS_CMD_FLAGS_MASK | IB_USER_VERBS_CMD_COMMAND_MASK)) { ret = -EINVAL; goto out; } command = hdr.command & IB_USER_VERBS_CMD_COMMAND_MASK; if (verify_command_mask(ib_dev, command)) { ret = -EOPNOTSUPP; goto out; } if (!file->ucontext && command != IB_USER_VERBS_CMD_GET_CONTEXT) { ret = -EINVAL; goto out; } flags = (hdr.command & IB_USER_VERBS_CMD_FLAGS_MASK) >> IB_USER_VERBS_CMD_FLAGS_SHIFT; if (!flags) { if (command >= ARRAY_SIZE(uverbs_cmd_table) || !uverbs_cmd_table[command]) { ret = -EINVAL; goto out; } if (hdr.in_words * 4 != count) { ret = -EINVAL; goto out; } ret = uverbs_cmd_table[command](file, ib_dev, buf + sizeof(hdr), hdr.in_words * 4, hdr.out_words * 4); } else if (flags == IB_USER_VERBS_CMD_FLAG_EXTENDED) { struct ib_uverbs_ex_cmd_hdr ex_hdr; struct ib_udata ucore; struct ib_udata uhw; size_t written_count = count; if (command >= ARRAY_SIZE(uverbs_ex_cmd_table) || !uverbs_ex_cmd_table[command]) { ret = -ENOSYS; goto out; } if (!file->ucontext) { ret = -EINVAL; goto out; } if (count < (sizeof(hdr) + sizeof(ex_hdr))) { ret = -EINVAL; goto out; } if (copy_from_user(&ex_hdr, buf + sizeof(hdr), sizeof(ex_hdr))) { ret = -EFAULT; goto out; } count -= sizeof(hdr) + sizeof(ex_hdr); buf += sizeof(hdr) + sizeof(ex_hdr); if ((hdr.in_words + ex_hdr.provider_in_words) * 8 != count) { ret = -EINVAL; goto out; } if (ex_hdr.cmd_hdr_reserved) { ret = -EINVAL; goto out; } if (ex_hdr.response) { if (!hdr.out_words && !ex_hdr.provider_out_words) { ret = -EINVAL; goto out; } if (!access_ok(VERIFY_WRITE, (void __user *) (unsigned long) ex_hdr.response, (hdr.out_words + ex_hdr.provider_out_words) * 8)) { ret = -EFAULT; goto out; } } else { if (hdr.out_words || ex_hdr.provider_out_words) { ret = -EINVAL; goto out; } } INIT_UDATA_BUF_OR_NULL(&ucore, buf, (unsigned long) ex_hdr.response, hdr.in_words * 8, hdr.out_words * 8); INIT_UDATA_BUF_OR_NULL(&uhw, buf + ucore.inlen, (unsigned long) ex_hdr.response + ucore.outlen, ex_hdr.provider_in_words * 8, ex_hdr.provider_out_words * 8); ret = uverbs_ex_cmd_table[command](file, ib_dev, &ucore, &uhw); if (!ret) ret = written_count; } else { ret = -ENOSYS; } out: srcu_read_unlock(&file->device->disassociate_srcu, srcu_key); return ret; }
167,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_timer_user_open(struct inode *inode, struct file *file) { struct snd_timer_user *tu; int err; err = nonseekable_open(inode, file); if (err < 0) return err; tu = kzalloc(sizeof(*tu), GFP_KERNEL); if (tu == NULL) return -ENOMEM; spin_lock_init(&tu->qlock); init_waitqueue_head(&tu->qchange_sleep); mutex_init(&tu->tread_sem); tu->ticks = 1; tu->queue_size = 128; tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) { kfree(tu); return -ENOMEM; } file->private_data = tu; return 0; } Commit Message: ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static int snd_timer_user_open(struct inode *inode, struct file *file) { struct snd_timer_user *tu; int err; err = nonseekable_open(inode, file); if (err < 0) return err; tu = kzalloc(sizeof(*tu), GFP_KERNEL); if (tu == NULL) return -ENOMEM; spin_lock_init(&tu->qlock); init_waitqueue_head(&tu->qchange_sleep); mutex_init(&tu->ioctl_lock); tu->ticks = 1; tu->queue_size = 128; tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) { kfree(tu); return -ENOMEM; } file->private_data = tu; return 0; }
167,405
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> V8TestNamedConstructorConstructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestNamedConstructor.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); Frame* frame = V8Proxy::retrieveFrameForCurrentContext(); if (!frame) return V8Proxy::throwError(V8Proxy::ReferenceError, "TestNamedConstructor constructor associated frame is unavailable", args.GetIsolate()); Document* document = frame->document(); toV8(document, args.GetIsolate()); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str3, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); RefPtr<TestNamedConstructor> impl = TestNamedConstructor::createForJSConstructor(document, str1, str2, str3, ec); v8::Handle<v8::Object> wrapper = args.Holder(); if (ec) goto fail; V8DOMWrapper::setDOMWrapper(wrapper, &V8TestNamedConstructorConstructor::info, impl.get()); V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); fail: return throwError(ec, args.GetIsolate()); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> V8TestNamedConstructorConstructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestNamedConstructor.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); Frame* frame = V8Proxy::retrieveFrameForCurrentContext(); if (!frame) return V8Proxy::throwError(V8Proxy::ReferenceError, "TestNamedConstructor constructor associated frame is unavailable", args.GetIsolate()); Document* document = frame->document(); toV8(document, args.GetIsolate()); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); ExceptionCode ec = 0; STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str3, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); RefPtr<TestNamedConstructor> impl = TestNamedConstructor::createForJSConstructor(document, str1, str2, str3, ec); v8::Handle<v8::Object> wrapper = args.Holder(); if (ec) goto fail; V8DOMWrapper::setDOMWrapper(wrapper, &V8TestNamedConstructorConstructor::info, impl.get()); V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); fail: return throwError(ec, args.GetIsolate()); }
171,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sas_eh_handle_sas_errors(struct Scsi_Host *shost, struct list_head *work_q) { struct scsi_cmnd *cmd, *n; enum task_disposition res = TASK_IS_DONE; int tmf_resp, need_reset; struct sas_internal *i = to_sas_internal(shost->transportt); unsigned long flags; struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); LIST_HEAD(done); /* clean out any commands that won the completion vs eh race */ list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_task *task; spin_lock_irqsave(&dev->done_lock, flags); /* by this point the lldd has either observed * SAS_HA_FROZEN and is leaving the task alone, or has * won the race with eh and decided to complete it */ task = TO_SAS_TASK(cmd); spin_unlock_irqrestore(&dev->done_lock, flags); if (!task) list_move_tail(&cmd->eh_entry, &done); } Again: list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct sas_task *task = TO_SAS_TASK(cmd); list_del_init(&cmd->eh_entry); spin_lock_irqsave(&task->task_state_lock, flags); need_reset = task->task_state_flags & SAS_TASK_NEED_DEV_RESET; spin_unlock_irqrestore(&task->task_state_lock, flags); if (need_reset) { SAS_DPRINTK("%s: task 0x%p requests reset\n", __func__, task); goto reset; } SAS_DPRINTK("trying to find task 0x%p\n", task); res = sas_scsi_find_task(task); switch (res) { case TASK_IS_DONE: SAS_DPRINTK("%s: task 0x%p is done\n", __func__, task); sas_eh_defer_cmd(cmd); continue; case TASK_IS_ABORTED: SAS_DPRINTK("%s: task 0x%p is aborted\n", __func__, task); sas_eh_defer_cmd(cmd); continue; case TASK_IS_AT_LU: SAS_DPRINTK("task 0x%p is at LU: lu recover\n", task); reset: tmf_resp = sas_recover_lu(task->dev, cmd); if (tmf_resp == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("dev %016llx LU %llx is " "recovered\n", SAS_ADDR(task->dev), cmd->device->lun); sas_eh_defer_cmd(cmd); sas_scsi_clear_queue_lu(work_q, cmd); goto Again; } /* fallthrough */ case TASK_IS_NOT_AT_LU: case TASK_ABORT_FAILED: SAS_DPRINTK("task 0x%p is not at LU: I_T recover\n", task); tmf_resp = sas_recover_I_T(task->dev); if (tmf_resp == TMF_RESP_FUNC_COMPLETE || tmf_resp == -ENODEV) { struct domain_device *dev = task->dev; SAS_DPRINTK("I_T %016llx recovered\n", SAS_ADDR(task->dev->sas_addr)); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_I_T(work_q, dev); goto Again; } /* Hammer time :-) */ try_to_reset_cmd_device(cmd); if (i->dft->lldd_clear_nexus_port) { struct asd_sas_port *port = task->dev->port; SAS_DPRINTK("clearing nexus for port:%d\n", port->id); res = i->dft->lldd_clear_nexus_port(port); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus port:%d " "succeeded\n", port->id); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_port(work_q, port); goto Again; } } if (i->dft->lldd_clear_nexus_ha) { SAS_DPRINTK("clear nexus ha\n"); res = i->dft->lldd_clear_nexus_ha(ha); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus ha " "succeeded\n"); sas_eh_finish_cmd(cmd); goto clear_q; } } /* If we are here -- this means that no amount * of effort could recover from errors. Quite * possibly the HA just disappeared. */ SAS_DPRINTK("error from device %llx, LUN %llx " "couldn't be recovered in any way\n", SAS_ADDR(task->dev->sas_addr), cmd->device->lun); sas_eh_finish_cmd(cmd); goto clear_q; } } out: list_splice_tail(&done, work_q); list_splice_tail_init(&ha->eh_ata_q, work_q); return; clear_q: SAS_DPRINTK("--- Exit %s -- clear_q\n", __func__); list_for_each_entry_safe(cmd, n, work_q, eh_entry) sas_eh_finish_cmd(cmd); goto out; } Commit Message: scsi: libsas: defer ata device eh commands to libata When ata device doing EH, some commands still attached with tasks are not passed to libata when abort failed or recover failed, so libata did not handle these commands. After these commands done, sas task is freed, but ata qc is not freed. This will cause ata qc leak and trigger a warning like below: WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037 ata_eh_finish+0xb4/0xcc CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1 ...... Call trace: [<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc [<ffff0000088b8420>] ata_do_eh+0xc4/0xd8 [<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c [<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694 [<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80 [<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170 [<ffff0000080ebd70>] process_one_work+0x144/0x390 [<ffff0000080ec100>] worker_thread+0x144/0x418 [<ffff0000080f2c98>] kthread+0x10c/0x138 [<ffff0000080855dc>] ret_from_fork+0x10/0x18 If ata qc leaked too many, ata tag allocation will fail and io blocked for ever. As suggested by Dan Williams, defer ata device commands to libata and merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle ata qcs correctly after this. Signed-off-by: Jason Yan <[email protected]> CC: Xiaofei Tan <[email protected]> CC: John Garry <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Dan Williams <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID:
static void sas_eh_handle_sas_errors(struct Scsi_Host *shost, struct list_head *work_q) { struct scsi_cmnd *cmd, *n; enum task_disposition res = TASK_IS_DONE; int tmf_resp, need_reset; struct sas_internal *i = to_sas_internal(shost->transportt); unsigned long flags; struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); LIST_HEAD(done); /* clean out any commands that won the completion vs eh race */ list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_task *task; spin_lock_irqsave(&dev->done_lock, flags); /* by this point the lldd has either observed * SAS_HA_FROZEN and is leaving the task alone, or has * won the race with eh and decided to complete it */ task = TO_SAS_TASK(cmd); spin_unlock_irqrestore(&dev->done_lock, flags); if (!task) list_move_tail(&cmd->eh_entry, &done); } Again: list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct sas_task *task = TO_SAS_TASK(cmd); list_del_init(&cmd->eh_entry); spin_lock_irqsave(&task->task_state_lock, flags); need_reset = task->task_state_flags & SAS_TASK_NEED_DEV_RESET; spin_unlock_irqrestore(&task->task_state_lock, flags); if (need_reset) { SAS_DPRINTK("%s: task 0x%p requests reset\n", __func__, task); goto reset; } SAS_DPRINTK("trying to find task 0x%p\n", task); res = sas_scsi_find_task(task); switch (res) { case TASK_IS_DONE: SAS_DPRINTK("%s: task 0x%p is done\n", __func__, task); sas_eh_finish_cmd(cmd); continue; case TASK_IS_ABORTED: SAS_DPRINTK("%s: task 0x%p is aborted\n", __func__, task); sas_eh_finish_cmd(cmd); continue; case TASK_IS_AT_LU: SAS_DPRINTK("task 0x%p is at LU: lu recover\n", task); reset: tmf_resp = sas_recover_lu(task->dev, cmd); if (tmf_resp == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("dev %016llx LU %llx is " "recovered\n", SAS_ADDR(task->dev), cmd->device->lun); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_lu(work_q, cmd); goto Again; } /* fallthrough */ case TASK_IS_NOT_AT_LU: case TASK_ABORT_FAILED: SAS_DPRINTK("task 0x%p is not at LU: I_T recover\n", task); tmf_resp = sas_recover_I_T(task->dev); if (tmf_resp == TMF_RESP_FUNC_COMPLETE || tmf_resp == -ENODEV) { struct domain_device *dev = task->dev; SAS_DPRINTK("I_T %016llx recovered\n", SAS_ADDR(task->dev->sas_addr)); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_I_T(work_q, dev); goto Again; } /* Hammer time :-) */ try_to_reset_cmd_device(cmd); if (i->dft->lldd_clear_nexus_port) { struct asd_sas_port *port = task->dev->port; SAS_DPRINTK("clearing nexus for port:%d\n", port->id); res = i->dft->lldd_clear_nexus_port(port); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus port:%d " "succeeded\n", port->id); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_port(work_q, port); goto Again; } } if (i->dft->lldd_clear_nexus_ha) { SAS_DPRINTK("clear nexus ha\n"); res = i->dft->lldd_clear_nexus_ha(ha); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus ha " "succeeded\n"); sas_eh_finish_cmd(cmd); goto clear_q; } } /* If we are here -- this means that no amount * of effort could recover from errors. Quite * possibly the HA just disappeared. */ SAS_DPRINTK("error from device %llx, LUN %llx " "couldn't be recovered in any way\n", SAS_ADDR(task->dev->sas_addr), cmd->device->lun); sas_eh_finish_cmd(cmd); goto clear_q; } } out: list_splice_tail(&done, work_q); list_splice_tail_init(&ha->eh_ata_q, work_q); return; clear_q: SAS_DPRINTK("--- Exit %s -- clear_q\n", __func__); list_for_each_entry_safe(cmd, n, work_q, eh_entry) sas_eh_finish_cmd(cmd); goto out; }
169,262
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) { assert(socket != NULL); assert(buf != NULL); return send(socket->fd, buf, count, MSG_DONTWAIT); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) { assert(socket != NULL); assert(buf != NULL); return TEMP_FAILURE_RETRY(send(socket->fd, buf, count, MSG_DONTWAIT)); }
173,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer) : mGraphicBuffer(graphicBuffer), mIsBackup(false) { } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
BufferMeta(const sp<GraphicBuffer> &graphicBuffer) BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mIsBackup(false), mPortIndex(portIndex) { }
173,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t ratio; uint32_t time; t_reverb_settings *pProperties; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; if (pContext->preset) { if (param != REVERB_PARAM_PRESET) { return -EINVAL; } uint16_t preset = *(uint16_t *)pValue; ALOGV("set REVERB_PARAM_PRESET, preset %d", preset); if (preset > REVERB_PRESET_LAST) { return -EINVAL; } pContext->nextPreset = preset; return 0; } switch (param){ case REVERB_PARAM_PROPERTIES: ALOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES"); pProperties = (t_reverb_settings *) pValue; ReverbSetRoomLevel(pContext, pProperties->roomLevel); ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel); ReverbSetDecayTime(pContext, pProperties->decayTime); ReverbSetDecayHfRatio(pContext, pProperties->decayHFRatio); ReverbSetReverbLevel(pContext, pProperties->reverbLevel); ReverbSetDiffusion(pContext, pProperties->diffusion); ReverbSetDensity(pContext, pProperties->density); break; case REVERB_PARAM_ROOM_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomLevel(pContext, level); break; case REVERB_PARAM_ROOM_HF_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomHfLevel(pContext, level); break; case REVERB_PARAM_DECAY_TIME: time = *(uint32_t *)pValue; ReverbSetDecayTime(pContext, time); break; case REVERB_PARAM_DECAY_HF_RATIO: ratio = *(int16_t *)pValue; ReverbSetDecayHfRatio(pContext, ratio); break; case REVERB_PARAM_REVERB_LEVEL: level = *(int16_t *)pValue; ReverbSetReverbLevel(pContext, level); break; case REVERB_PARAM_DIFFUSION: ratio = *(int16_t *)pValue; ReverbSetDiffusion(pContext, ratio); break; case REVERB_PARAM_DENSITY: ratio = *(int16_t *)pValue; ReverbSetDensity(pContext, ratio); break; break; case REVERB_PARAM_REFLECTIONS_LEVEL: case REVERB_PARAM_REFLECTIONS_DELAY: case REVERB_PARAM_REVERB_DELAY: break; default: ALOGV("\tLVM_ERROR : Reverb_setParameter() invalid param %d", param); break; } return status; } /* end Reverb_setParameter */ Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking to Downmix and Reverb Bug: 63662938 Bug: 63526567 Test: Added CTS tests Change-Id: I8ed398cd62a9f461b0590e37f593daa3d8e4dbc4 (cherry picked from commit 804632afcdda6e80945bf27c384757bda50560cb) CWE ID: CWE-200
int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue){ int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue, int vsize){ int status = 0; int16_t level; int16_t ratio; uint32_t time; t_reverb_settings *pProperties; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; if (pContext->preset) { if (param != REVERB_PARAM_PRESET) { return -EINVAL; } uint16_t preset = *(uint16_t *)pValue; ALOGV("set REVERB_PARAM_PRESET, preset %d", preset); if (preset > REVERB_PRESET_LAST) { return -EINVAL; } pContext->nextPreset = preset; return 0; } if (vsize < Reverb_paramValueSize(param)) { android_errorWriteLog(0x534e4554, "63526567"); return -EINVAL; } switch (param){ case REVERB_PARAM_PROPERTIES: ALOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES"); pProperties = (t_reverb_settings *) pValue; ReverbSetRoomLevel(pContext, pProperties->roomLevel); ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel); ReverbSetDecayTime(pContext, pProperties->decayTime); ReverbSetDecayHfRatio(pContext, pProperties->decayHFRatio); ReverbSetReverbLevel(pContext, pProperties->reverbLevel); ReverbSetDiffusion(pContext, pProperties->diffusion); ReverbSetDensity(pContext, pProperties->density); break; case REVERB_PARAM_ROOM_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomLevel(pContext, level); break; case REVERB_PARAM_ROOM_HF_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomHfLevel(pContext, level); break; case REVERB_PARAM_DECAY_TIME: time = *(uint32_t *)pValue; ReverbSetDecayTime(pContext, time); break; case REVERB_PARAM_DECAY_HF_RATIO: ratio = *(int16_t *)pValue; ReverbSetDecayHfRatio(pContext, ratio); break; case REVERB_PARAM_REVERB_LEVEL: level = *(int16_t *)pValue; ReverbSetReverbLevel(pContext, level); break; case REVERB_PARAM_DIFFUSION: ratio = *(int16_t *)pValue; ReverbSetDiffusion(pContext, ratio); break; case REVERB_PARAM_DENSITY: ratio = *(int16_t *)pValue; ReverbSetDensity(pContext, ratio); break; break; case REVERB_PARAM_REFLECTIONS_LEVEL: case REVERB_PARAM_REFLECTIONS_DELAY: case REVERB_PARAM_REVERB_DELAY: break; default: ALOGV("\tLVM_ERROR : Reverb_setParameter() invalid param %d", param); break; } return status; } /* end Reverb_setParameter */
173,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Load_SBit_Png( FT_GlyphSlot slot, FT_Int x_offset, FT_Int y_offset, FT_Int pix_bits, TT_SBit_Metrics metrics, FT_Memory memory, FT_Byte* data, FT_UInt png_len, FT_Bool populate_map_and_metrics ) { FT_Bitmap *map = &slot->bitmap; FT_Error error = FT_Err_Ok; FT_StreamRec stream; png_structp png; png_infop info; png_uint_32 imgWidth, imgHeight; int bitdepth, color_type, interlace; FT_Int i; png_byte* *rows = NULL; /* pacify compiler */ if ( x_offset < 0 || y_offset < 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( !populate_map_and_metrics && ( x_offset + metrics->width > map->width || y_offset + metrics->height > map->rows || pix_bits != 32 || map->pixel_mode != FT_PIXEL_MODE_BGRA ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_Stream_OpenMemory( &stream, data, png_len ); png = png_create_read_struct( PNG_LIBPNG_VER_STRING, &error, error_callback, warning_callback ); if ( !png ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } info = png_create_info_struct( png ); if ( !info ) { error = FT_THROW( Out_Of_Memory ); png_destroy_read_struct( &png, NULL, NULL ); goto Exit; } if ( ft_setjmp( png_jmpbuf( png ) ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } png_set_read_fn( png, &stream, read_data_from_FT_Stream ); png_read_info( png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( error || ( !populate_map_and_metrics && ( (FT_Int)imgWidth != metrics->width || (FT_Int)imgHeight != metrics->height ) ) ) goto DestroyExit; if ( populate_map_and_metrics ) { FT_Long size; metrics->width = (FT_Int)imgWidth; metrics->height = (FT_Int)imgHeight; map->width = metrics->width; map->rows = metrics->height; map->pixel_mode = FT_PIXEL_MODE_BGRA; map->pitch = map->width * 4; map->num_grays = 256; /* reject too large bitmaps similarly to the rasterizer */ if ( map->rows > 0x7FFF || map->width > 0x7FFF ) { error = FT_THROW( Array_Too_Large ); goto DestroyExit; } size = map->rows * map->pitch; error = ft_glyphslot_alloc_bitmap( slot, size ); if ( error ) goto DestroyExit; } /* convert palette/gray image to rgb */ if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png ); /* expand gray bit depth if needed */ if ( color_type == PNG_COLOR_TYPE_GRAY ) { #if PNG_LIBPNG_VER >= 10209 png_set_expand_gray_1_2_4_to_8( png ); #else png_set_gray_1_2_4_to_8( png ); #endif } /* transform transparency to alpha */ if ( png_get_valid(png, info, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png ); if ( bitdepth == 16 ) png_set_strip_16( png ); if ( bitdepth < 8 ) png_set_packing( png ); /* convert grayscale to RGB */ if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb( png ); if ( interlace != PNG_INTERLACE_NONE ) png_set_interlace_handling( png ); png_set_filler( png, 0xFF, PNG_FILLER_AFTER ); /* recheck header after setting EXPAND options */ png_read_update_info(png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( bitdepth != 8 || !( color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } switch ( color_type ) { default: /* Shouldn't happen, but fall through. */ case PNG_COLOR_TYPE_RGB_ALPHA: png_set_read_user_transform_fn( png, premultiply_data ); break; case PNG_COLOR_TYPE_RGB: /* Humm, this smells. Carry on though. */ png_set_read_user_transform_fn( png, convert_bytes_to_data ); break; } if ( FT_NEW_ARRAY( rows, imgHeight ) ) { error = FT_THROW( Out_Of_Memory ); goto DestroyExit; } for ( i = 0; i < (FT_Int)imgHeight; i++ ) rows[i] = map->buffer + ( y_offset + i ) * map->pitch + x_offset * 4; png_read_image( png, rows ); FT_FREE( rows ); png_read_end( png, info ); DestroyExit: png_destroy_read_struct( &png, &info, NULL ); FT_Stream_Close( &stream ); Exit: return error; } Commit Message: CWE ID: CWE-119
Load_SBit_Png( FT_GlyphSlot slot, FT_Int x_offset, FT_Int y_offset, FT_Int pix_bits, TT_SBit_Metrics metrics, FT_Memory memory, FT_Byte* data, FT_UInt png_len, FT_Bool populate_map_and_metrics ) { FT_Bitmap *map = &slot->bitmap; FT_Error error = FT_Err_Ok; FT_StreamRec stream; png_structp png; png_infop info; png_uint_32 imgWidth, imgHeight; int bitdepth, color_type, interlace; FT_Int i; png_byte* *rows = NULL; /* pacify compiler */ if ( x_offset < 0 || y_offset < 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( !populate_map_and_metrics && ( (FT_UInt)x_offset + metrics->width > map->width || (FT_UInt)y_offset + metrics->height > map->rows || pix_bits != 32 || map->pixel_mode != FT_PIXEL_MODE_BGRA ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_Stream_OpenMemory( &stream, data, png_len ); png = png_create_read_struct( PNG_LIBPNG_VER_STRING, &error, error_callback, warning_callback ); if ( !png ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } info = png_create_info_struct( png ); if ( !info ) { error = FT_THROW( Out_Of_Memory ); png_destroy_read_struct( &png, NULL, NULL ); goto Exit; } if ( ft_setjmp( png_jmpbuf( png ) ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } png_set_read_fn( png, &stream, read_data_from_FT_Stream ); png_read_info( png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( error || ( !populate_map_and_metrics && ( (FT_Int)imgWidth != metrics->width || (FT_Int)imgHeight != metrics->height ) ) ) goto DestroyExit; if ( populate_map_and_metrics ) { FT_Long size; metrics->width = (FT_Int)imgWidth; metrics->height = (FT_Int)imgHeight; map->width = metrics->width; map->rows = metrics->height; map->pixel_mode = FT_PIXEL_MODE_BGRA; map->pitch = map->width * 4; map->num_grays = 256; /* reject too large bitmaps similarly to the rasterizer */ if ( map->rows > 0x7FFF || map->width > 0x7FFF ) { error = FT_THROW( Array_Too_Large ); goto DestroyExit; } size = map->rows * map->pitch; error = ft_glyphslot_alloc_bitmap( slot, size ); if ( error ) goto DestroyExit; } /* convert palette/gray image to rgb */ if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png ); /* expand gray bit depth if needed */ if ( color_type == PNG_COLOR_TYPE_GRAY ) { #if PNG_LIBPNG_VER >= 10209 png_set_expand_gray_1_2_4_to_8( png ); #else png_set_gray_1_2_4_to_8( png ); #endif } /* transform transparency to alpha */ if ( png_get_valid(png, info, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png ); if ( bitdepth == 16 ) png_set_strip_16( png ); if ( bitdepth < 8 ) png_set_packing( png ); /* convert grayscale to RGB */ if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb( png ); if ( interlace != PNG_INTERLACE_NONE ) png_set_interlace_handling( png ); png_set_filler( png, 0xFF, PNG_FILLER_AFTER ); /* recheck header after setting EXPAND options */ png_read_update_info(png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( bitdepth != 8 || !( color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } switch ( color_type ) { default: /* Shouldn't happen, but fall through. */ case PNG_COLOR_TYPE_RGB_ALPHA: png_set_read_user_transform_fn( png, premultiply_data ); break; case PNG_COLOR_TYPE_RGB: /* Humm, this smells. Carry on though. */ png_set_read_user_transform_fn( png, convert_bytes_to_data ); break; } if ( FT_NEW_ARRAY( rows, imgHeight ) ) { error = FT_THROW( Out_Of_Memory ); goto DestroyExit; } for ( i = 0; i < (FT_Int)imgHeight; i++ ) rows[i] = map->buffer + ( y_offset + i ) * map->pitch + x_offset * 4; png_read_image( png, rows ); FT_FREE( rows ); png_read_end( png, info ); DestroyExit: png_destroy_read_struct( &png, &info, NULL ); FT_Stream_Close( &stream ); Exit: return error; }
164,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: htmlInitParserCtxt(htmlParserCtxtPtr ctxt) { htmlSAXHandler *sax; if (ctxt == NULL) return(-1); memset(ctxt, 0, sizeof(htmlParserCtxt)); ctxt->dict = xmlDictCreate(); if (ctxt->dict == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); return(-1); } sax = (htmlSAXHandler *) xmlMalloc(sizeof(htmlSAXHandler)); if (sax == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); return(-1); } else memset(sax, 0, sizeof(htmlSAXHandler)); /* Allocate the Input stack */ ctxt->inputTab = (htmlParserInputPtr *) xmlMalloc(5 * sizeof(htmlParserInputPtr)); if (ctxt->inputTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->inputNr = 0; ctxt->inputMax = 5; ctxt->input = NULL; ctxt->version = NULL; ctxt->encoding = NULL; ctxt->standalone = -1; ctxt->instate = XML_PARSER_START; /* Allocate the Node stack */ ctxt->nodeTab = (htmlNodePtr *) xmlMalloc(10 * sizeof(htmlNodePtr)); if (ctxt->nodeTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nodeNr = 0; ctxt->nodeMax = 10; ctxt->node = NULL; /* Allocate the Name stack */ ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *)); if (ctxt->nameTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->nameNr = 0; ctxt->nameMax = 0; ctxt->name = NULL; ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nameNr = 0; ctxt->nameMax = 10; ctxt->name = NULL; ctxt->nodeInfoTab = NULL; ctxt->nodeInfoNr = 0; ctxt->nodeInfoMax = 0; if (sax == NULL) ctxt->sax = (xmlSAXHandlerPtr) &htmlDefaultSAXHandler; else { ctxt->sax = sax; memcpy(sax, &htmlDefaultSAXHandler, sizeof(xmlSAXHandlerV1)); } ctxt->userData = ctxt; ctxt->myDoc = NULL; ctxt->wellFormed = 1; ctxt->replaceEntities = 0; ctxt->linenumbers = xmlLineNumbersDefaultValue; ctxt->html = 1; ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0; ctxt->vctxt.userData = ctxt; ctxt->vctxt.error = xmlParserValidityError; ctxt->vctxt.warning = xmlParserValidityWarning; ctxt->record_info = 0; ctxt->validate = 0; ctxt->nbChars = 0; ctxt->checkIndex = 0; ctxt->catalogs = NULL; xmlInitNodeInfoSeq(&ctxt->node_seq); return(0); } Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9 Removes a few patches fixed upstream: https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3 https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882 Stops using the NOXXE flag which was reverted upstream: https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d Changes the patch to uri.c to not add limits.h, which is included upstream. Bug: 722079 Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac Reviewed-on: https://chromium-review.googlesource.com/535233 Reviewed-by: Scott Graham <[email protected]> Commit-Queue: Dominic Cooney <[email protected]> Cr-Commit-Position: refs/heads/master@{#480755} CWE ID: CWE-787
htmlInitParserCtxt(htmlParserCtxtPtr ctxt) { htmlSAXHandler *sax; if (ctxt == NULL) return(-1); memset(ctxt, 0, sizeof(htmlParserCtxt)); ctxt->dict = xmlDictCreate(); if (ctxt->dict == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); return(-1); } sax = (htmlSAXHandler *) xmlMalloc(sizeof(htmlSAXHandler)); if (sax == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); return(-1); } else memset(sax, 0, sizeof(htmlSAXHandler)); /* Allocate the Input stack */ ctxt->inputTab = (htmlParserInputPtr *) xmlMalloc(5 * sizeof(htmlParserInputPtr)); if (ctxt->inputTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->inputNr = 0; ctxt->inputMax = 5; ctxt->input = NULL; ctxt->version = NULL; ctxt->encoding = NULL; ctxt->standalone = -1; ctxt->instate = XML_PARSER_START; /* Allocate the Node stack */ ctxt->nodeTab = (htmlNodePtr *) xmlMalloc(10 * sizeof(htmlNodePtr)); if (ctxt->nodeTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nodeNr = 0; ctxt->nodeMax = 10; ctxt->node = NULL; /* Allocate the Name stack */ ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *)); if (ctxt->nameTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->nameNr = 0; ctxt->nameMax = 0; ctxt->name = NULL; ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nameNr = 0; ctxt->nameMax = 10; ctxt->name = NULL; ctxt->nodeInfoTab = NULL; ctxt->nodeInfoNr = 0; ctxt->nodeInfoMax = 0; if (sax == NULL) ctxt->sax = (xmlSAXHandlerPtr) &htmlDefaultSAXHandler; else { ctxt->sax = sax; memcpy(sax, &htmlDefaultSAXHandler, sizeof(xmlSAXHandlerV1)); } ctxt->userData = ctxt; ctxt->myDoc = NULL; ctxt->wellFormed = 1; ctxt->replaceEntities = 0; ctxt->linenumbers = xmlLineNumbersDefaultValue; ctxt->keepBlanks = xmlKeepBlanksDefaultValue; ctxt->html = 1; ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0; ctxt->vctxt.userData = ctxt; ctxt->vctxt.error = xmlParserValidityError; ctxt->vctxt.warning = xmlParserValidityWarning; ctxt->record_info = 0; ctxt->validate = 0; ctxt->nbChars = 0; ctxt->checkIndex = 0; ctxt->catalogs = NULL; xmlInitNodeInfoSeq(&ctxt->node_seq); return(0); }
172,946
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", *offset, depth); uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); uint32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth); #if 0 static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); #endif PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = *offset + chunk_size - data_offset; if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): { if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } cur->next = NULL; delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (pssh.datalen + 20 > chunk_size) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { mHasVideo = true; uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { int32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || !mLastTrack->meta->findInt32(kKeyHeight, &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } break; } case FOURCC('s', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('\xA9', 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset += chunk_size; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset += chunk_size; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset += chunk_size; return OK; } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; convertTimeToDate(creationTime, &s); mFileMetaData->setCString(kKeyDate, s.string()); break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } uint32_t duration; Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } if (SIZE_MAX - chunk_size <= size) { return ERROR_MALFORMED; } uint8_t *buffer = new uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %lld and data_offset = %lld", chunk_data_size, data_offset); sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { parseSegmentIndex(data_offset, chunk_data_size); *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } default: { *offset += chunk_size; break; } } return OK; } Commit Message: Prevent integer overflow when processing covr MPEG4 atoms If the 'chunk_data_size' value is SIZE_MAX, an integer overflow will occur and cause an undersized buffer to be allocated. The following processing then overfills the resulting memory and creates a potentially exploitable condition. Ensure that integer overflow does not occur. Bug: 20923261 Change-Id: I75cce323aec04a612e5a230ecd7c2077ce06035f CWE ID: CWE-189
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", *offset, depth); uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); uint32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth); #if 0 static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); #endif PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = *offset + chunk_size - data_offset; if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): { if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } cur->next = NULL; delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (pssh.datalen + 20 > chunk_size) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { mHasVideo = true; uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { int32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || !mLastTrack->meta->findInt32(kKeyHeight, &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } break; } case FOURCC('s', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('\xA9', 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset += chunk_size; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset += chunk_size; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset += chunk_size; return OK; } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; convertTimeToDate(creationTime, &s); mFileMetaData->setCString(kKeyDate, s.string()); break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } uint32_t duration; Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } if (SIZE_MAX - chunk_size <= size) { return ERROR_MALFORMED; } uint8_t *buffer = new uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %lld and data_offset = %lld", chunk_data_size, data_offset); if (chunk_data_size >= SIZE_MAX - 1) { return ERROR_MALFORMED; } sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { parseSegmentIndex(data_offset, chunk_data_size); *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } default: { *offset += chunk_size; break; } } return OK; }
173,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; struct crypto_blkcipher *tfm = desc->tfm; struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm); int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt_block(desc, &walk, 64); salsa20_ivsetup(ctx, walk.iv); if (likely(walk.nbytes == nbytes)) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, nbytes); return blkcipher_walk_done(desc, &walk, 0); } while (walk.nbytes >= 64) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, walk.nbytes - (walk.nbytes % 64)); err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64); } if (walk.nbytes) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, walk.nbytes); err = blkcipher_walk_done(desc, &walk, 0); } return err; } Commit Message: crypto: salsa20 - fix blkcipher_walk API usage When asked to encrypt or decrypt 0 bytes, both the generic and x86 implementations of Salsa20 crash in blkcipher_walk_done(), either when doing 'kfree(walk->buffer)' or 'free_page((unsigned long)walk->page)', because walk->buffer and walk->page have not been initialized. The bug is that Salsa20 is calling blkcipher_walk_done() even when nothing is in 'walk.nbytes'. But blkcipher_walk_done() is only meant to be called when a nonzero number of bytes have been provided. The broken code is part of an optimization that tries to make only one call to salsa20_encrypt_bytes() to process inputs that are not evenly divisible by 64 bytes. To fix the bug, just remove this "optimization" and use the blkcipher_walk API the same way all the other users do. Reproducer: #include <linux/if_alg.h> #include <sys/socket.h> #include <unistd.h> int main() { int algfd, reqfd; struct sockaddr_alg addr = { .salg_type = "skcipher", .salg_name = "salsa20", }; char key[16] = { 0 }; algfd = socket(AF_ALG, SOCK_SEQPACKET, 0); bind(algfd, (void *)&addr, sizeof(addr)); reqfd = accept(algfd, 0, 0); setsockopt(algfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key)); read(reqfd, key, sizeof(key)); } Reported-by: syzbot <[email protected]> Fixes: eb6f13eb9f81 ("[CRYPTO] salsa20_generic: Fix multi-page processing") Cc: <[email protected]> # v2.6.25+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-20
static int encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; struct crypto_blkcipher *tfm = desc->tfm; struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm); int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt_block(desc, &walk, 64); salsa20_ivsetup(ctx, walk.iv); while (walk.nbytes >= 64) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, walk.nbytes - (walk.nbytes % 64)); err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64); } if (walk.nbytes) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, walk.nbytes); err = blkcipher_walk_done(desc, &walk, 0); } return err; }
167,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GLSurfaceEGLSurfaceControl::ScheduleOverlayPlane( int z_order, gfx::OverlayTransform transform, GLImage* image, const gfx::Rect& bounds_rect, const gfx::RectF& crop_rect, bool enable_blend, std::unique_ptr<gfx::GpuFence> gpu_fence) { if (!pending_transaction_) pending_transaction_.emplace(); bool uninitialized = false; if (pending_surfaces_count_ == surface_list_.size()) { uninitialized = true; surface_list_.emplace_back(*root_surface_); } pending_surfaces_count_++; auto& surface_state = surface_list_.at(pending_surfaces_count_ - 1); if (uninitialized || surface_state.z_order != z_order) { surface_state.z_order = z_order; pending_transaction_->SetZOrder(*surface_state.surface, z_order); } AHardwareBuffer* hardware_buffer = nullptr; base::ScopedFD fence_fd; auto scoped_hardware_buffer = image->GetAHardwareBuffer(); if (scoped_hardware_buffer) { hardware_buffer = scoped_hardware_buffer->buffer(); fence_fd = scoped_hardware_buffer->TakeFence(); auto* a_surface = surface_state.surface->surface(); DCHECK_EQ(pending_frame_resources_.count(a_surface), 0u); auto& resource_ref = pending_frame_resources_[a_surface]; resource_ref.surface = surface_state.surface; resource_ref.scoped_buffer = std::move(scoped_hardware_buffer); } if (uninitialized || surface_state.hardware_buffer != hardware_buffer) { surface_state.hardware_buffer = hardware_buffer; if (!fence_fd.is_valid() && gpu_fence && surface_state.hardware_buffer) { auto fence_handle = gfx::CloneHandleForIPC(gpu_fence->GetGpuFenceHandle()); DCHECK(!fence_handle.is_null()); fence_fd = base::ScopedFD(fence_handle.native_fd.fd); } pending_transaction_->SetBuffer(*surface_state.surface, surface_state.hardware_buffer, std::move(fence_fd)); } if (hardware_buffer) { gfx::Rect dst = bounds_rect; gfx::Size buffer_size = GetBufferSize(hardware_buffer); gfx::RectF scaled_rect = gfx::RectF(crop_rect.x() * buffer_size.width(), crop_rect.y() * buffer_size.height(), crop_rect.width() * buffer_size.width(), crop_rect.height() * buffer_size.height()); gfx::Rect src = gfx::ToEnclosedRect(scaled_rect); if (uninitialized || surface_state.src != src || surface_state.dst != dst || surface_state.transform != transform) { surface_state.src = src; surface_state.dst = dst; surface_state.transform = transform; pending_transaction_->SetGeometry(*surface_state.surface, src, dst, transform); } } bool opaque = !enable_blend; if (uninitialized || surface_state.opaque != opaque) { surface_state.opaque = opaque; pending_transaction_->SetOpaque(*surface_state.surface, opaque); } return true; } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID:
bool GLSurfaceEGLSurfaceControl::ScheduleOverlayPlane( int z_order, gfx::OverlayTransform transform, GLImage* image, const gfx::Rect& bounds_rect, const gfx::RectF& crop_rect, bool enable_blend, std::unique_ptr<gfx::GpuFence> gpu_fence) { if (!pending_transaction_) pending_transaction_.emplace(); bool uninitialized = false; if (pending_surfaces_count_ == surface_list_.size()) { uninitialized = true; surface_list_.emplace_back(*root_surface_); } pending_surfaces_count_++; auto& surface_state = surface_list_.at(pending_surfaces_count_ - 1); if (uninitialized || surface_state.z_order != z_order) { surface_state.z_order = z_order; pending_transaction_->SetZOrder(*surface_state.surface, z_order); } AHardwareBuffer* hardware_buffer = nullptr; base::ScopedFD fence_fd; auto scoped_hardware_buffer = image->GetAHardwareBuffer(); if (scoped_hardware_buffer) { hardware_buffer = scoped_hardware_buffer->buffer(); fence_fd = scoped_hardware_buffer->TakeFence(); auto* a_surface = surface_state.surface->surface(); DCHECK_EQ(pending_frame_resources_.count(a_surface), 0u); auto& resource_ref = pending_frame_resources_[a_surface]; resource_ref.surface = surface_state.surface; resource_ref.scoped_buffer = std::move(scoped_hardware_buffer); } surface_state.buffer_updated_in_pending_transaction = uninitialized || surface_state.hardware_buffer != hardware_buffer; if (surface_state.buffer_updated_in_pending_transaction) { surface_state.hardware_buffer = hardware_buffer; if (!fence_fd.is_valid() && gpu_fence && surface_state.hardware_buffer) { auto fence_handle = gfx::CloneHandleForIPC(gpu_fence->GetGpuFenceHandle()); DCHECK(!fence_handle.is_null()); fence_fd = base::ScopedFD(fence_handle.native_fd.fd); } pending_transaction_->SetBuffer(*surface_state.surface, surface_state.hardware_buffer, std::move(fence_fd)); } if (hardware_buffer) { gfx::Rect dst = bounds_rect; gfx::Size buffer_size = GetBufferSize(hardware_buffer); gfx::RectF scaled_rect = gfx::RectF(crop_rect.x() * buffer_size.width(), crop_rect.y() * buffer_size.height(), crop_rect.width() * buffer_size.width(), crop_rect.height() * buffer_size.height()); gfx::Rect src = gfx::ToEnclosedRect(scaled_rect); if (uninitialized || surface_state.src != src || surface_state.dst != dst || surface_state.transform != transform) { surface_state.src = src; surface_state.dst = dst; surface_state.transform = transform; pending_transaction_->SetGeometry(*surface_state.surface, src, dst, transform); } } bool opaque = !enable_blend; if (uninitialized || surface_state.opaque != opaque) { surface_state.opaque = opaque; pending_transaction_->SetOpaque(*surface_state.surface, opaque); } return true; }
172,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); } Commit Message: KEYS: add missing permission check for request_key() destination When the request_key() syscall is not passed a destination keyring, it links the requested key (if constructed) into the "default" request-key keyring. This should require Write permission to the keyring. However, there is actually no permission check. This can be abused to add keys to any keyring to which only Search permission is granted. This is because Search permission allows joining the keyring. keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_SESSION_KEYRING) then will set the default request-key keyring to the session keyring. Then, request_key() can be used to add keys to the keyring. Both negatively and positively instantiated keys can be added using this method. Adding negative keys is trivial. Adding a positive key is a bit trickier. It requires that either /sbin/request-key positively instantiates the key, or that another thread adds the key to the process keyring at just the right time, such that request_key() misses it initially but then finds it in construct_alloc_key(). Fix this bug by checking for Write permission to the keyring in construct_get_dest_keyring() when the default keyring is being used. We don't do the permission check for non-default keyrings because that was already done by the earlier call to lookup_user_key(). Also, request_key_and_link() is currently passed a 'struct key *' rather than a key_ref_t, so the "possessed" bit is unavailable. We also don't do the permission check for the "requestor keyring", to continue to support the use case described by commit 8bbf4976b59f ("KEYS: Alter use of key instantiation link-to-keyring argument") where /sbin/request-key recursively calls request_key() to add keys to the original requestor's destination keyring. (I don't know of any users who actually do that, though...) Fixes: 3e30148c3d52 ("[PATCH] Keys: Make request-key create an authorisation key") Cc: <[email protected]> # v2.6.13+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: CWE-862
static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); ret = construct_get_dest_keyring(&dest_keyring); if (ret) goto error; user = key_user_lookup(current_fsuid()); if (!user) { ret = -ENOMEM; goto error_put_dest_keyring; } ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto error_put_dest_keyring; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); error_put_dest_keyring: key_put(dest_keyring); error: kleave(" = %d", ret); return ERR_PTR(ret); }
167,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= cctx->M; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } Commit Message: crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-125
static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) { if (len < cctx->M) return 0; len -= cctx->M; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } }
168,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void __file_sb_list_add(struct file *file, struct super_block *sb) { struct list_head *list; #ifdef CONFIG_SMP int cpu; cpu = smp_processor_id(); file->f_sb_list_cpu = cpu; list = per_cpu_ptr(sb->s_files, cpu); #else list = &sb->s_files; #endif list_add(&file->f_u.fu_list, list); } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
static inline void __file_sb_list_add(struct file *file, struct super_block *sb)
166,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message, bool* message_was_ok) { bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) #if !defined(DISABLE_NACL) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD, OnGetReadonlyPnaclFd) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile, OnNaClCreateTemporaryFile) #endif IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats, OnResourceTypeStats) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats, OnUpdatedCacheStats) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension, OnOpenChannelToExtension) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab) IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, OnGetExtensionMessageBundle) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener, OnExtensionRemoveListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener, OnExtensionAddLazyListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener, OnExtensionRemoveLazyListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener, OnExtensionAddFilteredListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener, OnExtensionRemoveFilteredListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread, OnExtensionRequestForIOThread) IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck, OnExtensionShouldUnloadAck) IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID, OnExtensionGenerateUniqueID) IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck) IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests, OnExtensionResumeRequests); #if defined(USE_TCMALLOC) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK, OnWriteTcmallocHeapProfile) #endif IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead, OnCanTriggerClipboardRead) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite, OnCanTriggerClipboardWrite) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() #if defined(ENABLE_AUTOMATION) if ((message.type() == ChromeViewHostMsg_GetCookies::ID || message.type() == ChromeViewHostMsg_SetCookie::ID) && AutomationResourceMessageFilter::ShouldFilterCookieMessages( render_process_id_, message.routing_id())) { IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies, OnGetCookies) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie) IPC_END_MESSAGE_MAP() handled = true; } #endif return handled; } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message, bool* message_was_ok) { bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) #if !defined(DISABLE_NACL) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD, OnGetReadonlyPnaclFd) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile, OnNaClCreateTemporaryFile) #endif IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats, OnResourceTypeStats) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats, OnUpdatedCacheStats) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension, OnOpenChannelToExtension) IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab) IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, OnGetExtensionMessageBundle) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener, OnExtensionRemoveListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener, OnExtensionAddLazyListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener, OnExtensionRemoveLazyListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener, OnExtensionAddFilteredListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener, OnExtensionRemoveFilteredListener) IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel) IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread, OnExtensionRequestForIOThread) IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck, OnExtensionShouldUnloadAck) IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID, OnExtensionGenerateUniqueID) IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck) IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests, OnExtensionResumeRequests); IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead, OnCanTriggerClipboardRead) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite, OnCanTriggerClipboardWrite) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() #if defined(ENABLE_AUTOMATION) if ((message.type() == ChromeViewHostMsg_GetCookies::ID || message.type() == ChromeViewHostMsg_SetCookie::ID) && AutomationResourceMessageFilter::ShouldFilterCookieMessages( render_process_id_, message.routing_id())) { IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies, OnGetCookies) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie) IPC_END_MESSAGE_MAP() handled = true; } #endif return handled; }
170,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { const tuple<int, int, SubpelVarianceFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; subpel_variance_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); sec_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_ + width_ + height_ + 1]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(sec_ != NULL); ASSERT_TRUE(ref_ != NULL); } 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
virtual void SetUp() { const tuple<int, int, MseFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; mse_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(ref_ != NULL); }
174,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void fwnet_receive_broadcast(struct fw_iso_context *context, u32 cycle, size_t header_length, void *header, void *data) { struct fwnet_device *dev; struct fw_iso_packet packet; __be16 *hdr_ptr; __be32 *buf_ptr; int retval; u32 length; u16 source_node_id; u32 specifier_id; u32 ver; unsigned long offset; unsigned long flags; dev = data; hdr_ptr = header; length = be16_to_cpup(hdr_ptr); spin_lock_irqsave(&dev->lock, flags); offset = dev->rcv_buffer_size * dev->broadcast_rcv_next_ptr; buf_ptr = dev->broadcast_rcv_buffer_ptrs[dev->broadcast_rcv_next_ptr++]; if (dev->broadcast_rcv_next_ptr == dev->num_broadcast_rcv_ptrs) dev->broadcast_rcv_next_ptr = 0; spin_unlock_irqrestore(&dev->lock, flags); specifier_id = (be32_to_cpu(buf_ptr[0]) & 0xffff) << 8 | (be32_to_cpu(buf_ptr[1]) & 0xff000000) >> 24; ver = be32_to_cpu(buf_ptr[1]) & 0xffffff; source_node_id = be32_to_cpu(buf_ptr[0]) >> 16; if (specifier_id == IANA_SPECIFIER_ID && (ver == RFC2734_SW_VERSION #if IS_ENABLED(CONFIG_IPV6) || ver == RFC3146_SW_VERSION #endif )) { buf_ptr += 2; length -= IEEE1394_GASP_HDR_SIZE; fwnet_incoming_packet(dev, buf_ptr, length, source_node_id, context->card->generation, true); } packet.payload_length = dev->rcv_buffer_size; packet.interrupt = 1; packet.skip = 0; packet.tag = 3; packet.sy = 0; packet.header_length = IEEE1394_GASP_HDR_SIZE; spin_lock_irqsave(&dev->lock, flags); retval = fw_iso_context_queue(dev->broadcast_rcv_context, &packet, &dev->broadcast_rcv_buffer, offset); spin_unlock_irqrestore(&dev->lock, flags); if (retval >= 0) fw_iso_context_queue_flush(dev->broadcast_rcv_context); else dev_err(&dev->netdev->dev, "requeue failed\n"); } Commit Message: firewire: net: guard against rx buffer overflows The IP-over-1394 driver firewire-net lacked input validation when handling incoming fragmented datagrams. A maliciously formed fragment with a respectively large datagram_offset would cause a memcpy past the datagram buffer. So, drop any packets carrying a fragment with offset + length larger than datagram_size. In addition, ensure that - GASP header, unfragmented encapsulation header, or fragment encapsulation header actually exists before we access it, - the encapsulated datagram or fragment is of nonzero size. Reported-by: Eyal Itkin <[email protected]> Reviewed-by: Eyal Itkin <[email protected]> Fixes: CVE 2016-8633 Cc: [email protected] Signed-off-by: Stefan Richter <[email protected]> CWE ID: CWE-119
static void fwnet_receive_broadcast(struct fw_iso_context *context, u32 cycle, size_t header_length, void *header, void *data) { struct fwnet_device *dev; struct fw_iso_packet packet; __be16 *hdr_ptr; __be32 *buf_ptr; int retval; u32 length; unsigned long offset; unsigned long flags; dev = data; hdr_ptr = header; length = be16_to_cpup(hdr_ptr); spin_lock_irqsave(&dev->lock, flags); offset = dev->rcv_buffer_size * dev->broadcast_rcv_next_ptr; buf_ptr = dev->broadcast_rcv_buffer_ptrs[dev->broadcast_rcv_next_ptr++]; if (dev->broadcast_rcv_next_ptr == dev->num_broadcast_rcv_ptrs) dev->broadcast_rcv_next_ptr = 0; spin_unlock_irqrestore(&dev->lock, flags); if (length > IEEE1394_GASP_HDR_SIZE && gasp_specifier_id(buf_ptr) == IANA_SPECIFIER_ID && (gasp_version(buf_ptr) == RFC2734_SW_VERSION #if IS_ENABLED(CONFIG_IPV6) || gasp_version(buf_ptr) == RFC3146_SW_VERSION #endif )) fwnet_incoming_packet(dev, buf_ptr + 2, length - IEEE1394_GASP_HDR_SIZE, gasp_source_id(buf_ptr), context->card->generation, true); packet.payload_length = dev->rcv_buffer_size; packet.interrupt = 1; packet.skip = 0; packet.tag = 3; packet.sy = 0; packet.header_length = IEEE1394_GASP_HDR_SIZE; spin_lock_irqsave(&dev->lock, flags); retval = fw_iso_context_queue(dev->broadcast_rcv_context, &packet, &dev->broadcast_rcv_buffer, offset); spin_unlock_irqrestore(&dev->lock, flags); if (retval >= 0) fw_iso_context_queue_flush(dev->broadcast_rcv_context); else dev_err(&dev->netdev->dev, "requeue failed\n"); }
166,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_rgb_to_gray_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0) { double gray, err; if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); /* Image now has RGB channels... */ # if DIGITIZE { PNG_CONST png_modifier *pm = display->pm; const unsigned int sample_depth = that->sample_depth; const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 : sample_depth); const unsigned int gamma_depth = (sample_depth == 16 ? 16 : (pm->assume_16_bit_calculations ? PNG_MAX_GAMMA_8 : sample_depth)); int isgray; double r, g, b; double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi; /* Do this using interval arithmetic, otherwise it is too difficult to * handle the errors correctly. * * To handle the gamma correction work out the upper and lower bounds * of the digitized value. Assume rounding here - normally the values * will be identical after this operation if there is only one * transform, feel free to delete the png_error checks on this below in * the future (this is just me trying to ensure it works!) */ r = rlo = rhi = that->redf; rlo -= that->rede; rlo = digitize(rlo, calc_depth, 1/*round*/); rhi += that->rede; rhi = digitize(rhi, calc_depth, 1/*round*/); g = glo = ghi = that->greenf; glo -= that->greene; glo = digitize(glo, calc_depth, 1/*round*/); ghi += that->greene; ghi = digitize(ghi, calc_depth, 1/*round*/); b = blo = bhi = that->bluef; blo -= that->bluee; blo = digitize(blo, calc_depth, 1/*round*/); bhi += that->greene; bhi = digitize(bhi, calc_depth, 1/*round*/); isgray = r==g && g==b; if (data.gamma != 1) { PNG_CONST double power = 1/data.gamma; PNG_CONST double abse = calc_depth == 16 ? .5/65535 : .5/255; /* 'abse' is the absolute error permitted in linear calculations. It * is used here to capture the error permitted in the handling * (undoing) of the gamma encoding. Once again digitization occurs * to handle the upper and lower bounds of the values. This is * where the real errors are introduced. */ r = pow(r, power); rlo = digitize(pow(rlo, power)-abse, calc_depth, 1); rhi = digitize(pow(rhi, power)+abse, calc_depth, 1); g = pow(g, power); glo = digitize(pow(glo, power)-abse, calc_depth, 1); ghi = digitize(pow(ghi, power)+abse, calc_depth, 1); b = pow(b, power); blo = digitize(pow(blo, power)-abse, calc_depth, 1); bhi = digitize(pow(bhi, power)+abse, calc_depth, 1); } /* Now calculate the actual gray values. Although the error in the * coefficients depends on whether they were specified on the command * line (in which case truncation to 15 bits happened) or not (rounding * was used) the maxium error in an individual coefficient is always * 1/32768, because even in the rounding case the requirement that * coefficients add up to 32768 can cause a larger rounding error. * * The only time when rounding doesn't occur in 1.5.5 and later is when * the non-gamma code path is used for less than 16 bit data. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; { PNG_CONST int do_round = data.gamma != 1 || calc_depth == 16; PNG_CONST double ce = 1. / 32768; graylo = digitize(rlo * (data.red_coefficient-ce) + glo * (data.green_coefficient-ce) + blo * (data.blue_coefficient-ce), gamma_depth, do_round); if (graylo <= 0) graylo = 0; grayhi = digitize(rhi * (data.red_coefficient+ce) + ghi * (data.green_coefficient+ce) + bhi * (data.blue_coefficient+ce), gamma_depth, do_round); if (grayhi >= 1) grayhi = 1; } /* And invert the gamma. */ if (data.gamma != 1) { PNG_CONST double power = data.gamma; gray = pow(gray, power); graylo = digitize(pow(graylo, power), sample_depth, 1); grayhi = digitize(pow(grayhi, power), sample_depth, 1); } /* Now the error can be calculated. * * If r==g==b because there is no overall gamma correction libpng * currently preserves the original value. */ if (isgray) err = (that->rede + that->greene + that->bluee)/3; else { err = fabs(grayhi-gray); if (fabs(gray - graylo) > err) err = fabs(graylo-gray); /* Check that this worked: */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_error(pp, buffer); } } } # else /* DIGITIZE */ { double r = that->redf; double re = that->rede; double g = that->greenf; double ge = that->greene; double b = that->bluef; double be = that->bluee; /* The true gray case involves no math. */ if (r == g && r == b) { gray = r; err = re; if (err < ge) err = ge; if (err < be) err = be; } else if (data.gamma == 1) { /* There is no need to do the conversions to and from linear space, * so the calculation should be a lot more accurate. There is a * built in 1/32768 error in the coefficients because they only have * 15 bits and are adjusted to make sure they add up to 32768, so * the result may have an additional error up to 1/32768. (Note * that adding the 1/32768 here avoids needing to increase the * global error limits to take this into account.) */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; err = re * data.red_coefficient + ge * data.green_coefficient + be * data.blue_coefficient + 1./32768 + gray * 5 * DBL_EPSILON; } else { /* The calculation happens in linear space, and this produces much * wider errors in the encoded space. These are handled here by * factoring the errors in to the calculation. There are two table * lookups in the calculation and each introduces a quantization * error defined by the table size. */ PNG_CONST png_modifier *pm = display->pm; double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255); double out_qe = (that->sample_depth > 8 ? .5/65535 : (pm->assume_16_bit_calculations ? .5/(1<<PNG_MAX_GAMMA_8) : .5/255)); double rhi, ghi, bhi, grayhi; double g1 = 1/data.gamma; rhi = r + re + in_qe; if (rhi > 1) rhi = 1; r -= re + in_qe; if (r < 0) r = 0; ghi = g + ge + in_qe; if (ghi > 1) ghi = 1; g -= ge + in_qe; if (g < 0) g = 0; bhi = b + be + in_qe; if (bhi > 1) bhi = 1; b -= be + in_qe; if (b < 0) b = 0; r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON); g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON); b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON); /* Work out the lower and upper bounds for the gray value in the * encoded space, then work out an average and error. Remove the * previously added input quantization error at this point. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient - 1./32768 - out_qe; if (gray <= 0) gray = 0; else { gray *= (1 - 6 * DBL_EPSILON); gray = pow(gray, data.gamma) * (1-DBL_EPSILON); } grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient + bhi * data.blue_coefficient + 1./32768 + out_qe; grayhi *= (1 + 6 * DBL_EPSILON); if (grayhi >= 1) grayhi = 1; else grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON); err = (grayhi - gray) / 2; gray = (grayhi + gray) / 2; if (err <= in_qe) err = gray * DBL_EPSILON; else err -= in_qe; /* Validate that the error is within limits (this has caused * problems before, it's much easier to detect them here.) */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_error(pp, buffer); } } } # endif /* !DIGITIZE */ that->bluef = that->greenf = that->redf = gray; that->bluee = that->greene = that->rede = err; /* The sBIT is the minium of the three colour channel sBITs. */ if (that->red_sBIT > that->green_sBIT) that->red_sBIT = that->green_sBIT; if (that->red_sBIT > that->blue_sBIT) that->red_sBIT = that->blue_sBIT; that->blue_sBIT = that->green_sBIT = that->red_sBIT; /* And remove the colour bit in the type: */ if (that->colour_type == PNG_COLOR_TYPE_RGB) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_rgb_to_gray_mod(PNG_CONST image_transform *this, image_transform_png_set_rgb_to_gray_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0) { double gray, err; # if PNG_LIBPNG_VER < 10700 if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); # endif /* Image now has RGB channels... */ # if DIGITIZE { const png_modifier *pm = display->pm; const unsigned int sample_depth = that->sample_depth; const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 : sample_depth); const unsigned int gamma_depth = (sample_depth == 16 ? display->max_gamma_8 : (pm->assume_16_bit_calculations ? display->max_gamma_8 : sample_depth)); int isgray; double r, g, b; double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi; /* Do this using interval arithmetic, otherwise it is too difficult to * handle the errors correctly. * * To handle the gamma correction work out the upper and lower bounds * of the digitized value. Assume rounding here - normally the values * will be identical after this operation if there is only one * transform, feel free to delete the png_error checks on this below in * the future (this is just me trying to ensure it works!) * * Interval arithmetic is exact, but to implement it it must be * possible to control the floating point implementation rounding mode. * This cannot be done in ANSI-C, so instead I reduce the 'lo' values * by DBL_EPSILON and increase the 'hi' values by the same. */ # define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON)) # define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON)) r = rlo = rhi = that->redf; rlo -= that->rede; rlo = DD(rlo, calc_depth, 1/*round*/); rhi += that->rede; rhi = DU(rhi, calc_depth, 1/*round*/); g = glo = ghi = that->greenf; glo -= that->greene; glo = DD(glo, calc_depth, 1/*round*/); ghi += that->greene; ghi = DU(ghi, calc_depth, 1/*round*/); b = blo = bhi = that->bluef; blo -= that->bluee; blo = DD(blo, calc_depth, 1/*round*/); bhi += that->bluee; bhi = DU(bhi, calc_depth, 1/*round*/); isgray = r==g && g==b; if (data.gamma != 1) { const double power = 1/data.gamma; const double abse = .5/(sample_depth == 16 ? 65535 : 255); /* If a gamma calculation is done it is done using lookup tables of * precision gamma_depth, so the already digitized value above may * need to be further digitized here. */ if (gamma_depth != calc_depth) { rlo = DD(rlo, gamma_depth, 0/*truncate*/); rhi = DU(rhi, gamma_depth, 0/*truncate*/); glo = DD(glo, gamma_depth, 0/*truncate*/); ghi = DU(ghi, gamma_depth, 0/*truncate*/); blo = DD(blo, gamma_depth, 0/*truncate*/); bhi = DU(bhi, gamma_depth, 0/*truncate*/); } /* 'abse' is the error in the gamma table calculation itself. */ r = pow(r, power); rlo = DD(pow(rlo, power)-abse, calc_depth, 1); rhi = DU(pow(rhi, power)+abse, calc_depth, 1); g = pow(g, power); glo = DD(pow(glo, power)-abse, calc_depth, 1); ghi = DU(pow(ghi, power)+abse, calc_depth, 1); b = pow(b, power); blo = DD(pow(blo, power)-abse, calc_depth, 1); bhi = DU(pow(bhi, power)+abse, calc_depth, 1); } /* Now calculate the actual gray values. Although the error in the * coefficients depends on whether they were specified on the command * line (in which case truncation to 15 bits happened) or not (rounding * was used) the maxium error in an individual coefficient is always * 2/32768, because even in the rounding case the requirement that * coefficients add up to 32768 can cause a larger rounding error. * * The only time when rounding doesn't occur in 1.5.5 and later is when * the non-gamma code path is used for less than 16 bit data. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; { const int do_round = data.gamma != 1 || calc_depth == 16; const double ce = 2. / 32768; graylo = DD(rlo * (data.red_coefficient-ce) + glo * (data.green_coefficient-ce) + blo * (data.blue_coefficient-ce), calc_depth, do_round); if (graylo > gray) /* always accept the right answer */ graylo = gray; grayhi = DU(rhi * (data.red_coefficient+ce) + ghi * (data.green_coefficient+ce) + bhi * (data.blue_coefficient+ce), calc_depth, do_round); if (grayhi < gray) grayhi = gray; } /* And invert the gamma. */ if (data.gamma != 1) { const double power = data.gamma; /* And this happens yet again, shifting the values once more. */ if (gamma_depth != sample_depth) { rlo = DD(rlo, gamma_depth, 0/*truncate*/); rhi = DU(rhi, gamma_depth, 0/*truncate*/); glo = DD(glo, gamma_depth, 0/*truncate*/); ghi = DU(ghi, gamma_depth, 0/*truncate*/); blo = DD(blo, gamma_depth, 0/*truncate*/); bhi = DU(bhi, gamma_depth, 0/*truncate*/); } gray = pow(gray, power); graylo = DD(pow(graylo, power), sample_depth, 1); grayhi = DU(pow(grayhi, power), sample_depth, 1); } # undef DD # undef DU /* Now the error can be calculated. * * If r==g==b because there is no overall gamma correction libpng * currently preserves the original value. */ if (isgray) err = (that->rede + that->greene + that->bluee)/3; else { err = fabs(grayhi-gray); if (fabs(gray - graylo) > err) err = fabs(graylo-gray); /* Check that this worked: */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_error(pp, buffer); } } } # else /* DIGITIZE */ { double r = that->redf; double re = that->rede; double g = that->greenf; double ge = that->greene; double b = that->bluef; double be = that->bluee; # if PNG_LIBPNG_VER < 10700 /* The true gray case involves no math in earlier versions (not * true, there was some if gamma correction was happening too.) */ if (r == g && r == b) { gray = r; err = re; if (err < ge) err = ge; if (err < be) err = be; } else # endif /* before 1.7 */ if (data.gamma == 1) { /* There is no need to do the conversions to and from linear space, * so the calculation should be a lot more accurate. There is a * built in error in the coefficients because they only have 15 bits * and are adjusted to make sure they add up to 32768. This * involves a integer calculation with truncation of the form: * * ((int)(coefficient * 100000) * 32768)/100000 * * This is done to the red and green coefficients (the ones * provided to the API) then blue is calculated from them so the * result adds up to 32768. In the worst case this can result in * a -1 error in red and green and a +2 error in blue. Consequently * the worst case in the calculation below is 2/32768 error. * * TODO: consider fixing this in libpng by rounding the calculation * limiting the error to 1/32768. * * Handling this by adding 2/32768 here avoids needing to increase * the global error limits to take this into account.) */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; err = re * data.red_coefficient + ge * data.green_coefficient + be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON; } else { /* The calculation happens in linear space, and this produces much * wider errors in the encoded space. These are handled here by * factoring the errors in to the calculation. There are two table * lookups in the calculation and each introduces a quantization * error defined by the table size. */ const png_modifier *pm = display->pm; double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255); double out_qe = (that->sample_depth > 8 ? .5/65535 : (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) : .5/255)); double rhi, ghi, bhi, grayhi; double g1 = 1/data.gamma; rhi = r + re + in_qe; if (rhi > 1) rhi = 1; r -= re + in_qe; if (r < 0) r = 0; ghi = g + ge + in_qe; if (ghi > 1) ghi = 1; g -= ge + in_qe; if (g < 0) g = 0; bhi = b + be + in_qe; if (bhi > 1) bhi = 1; b -= be + in_qe; if (b < 0) b = 0; r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON); g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON); b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON); /* Work out the lower and upper bounds for the gray value in the * encoded space, then work out an average and error. Remove the * previously added input quantization error at this point. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient - 2./32768 - out_qe; if (gray <= 0) gray = 0; else { gray *= (1 - 6 * DBL_EPSILON); gray = pow(gray, data.gamma) * (1-DBL_EPSILON); } grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient + bhi * data.blue_coefficient + 2./32768 + out_qe; grayhi *= (1 + 6 * DBL_EPSILON); if (grayhi >= 1) grayhi = 1; else grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON); err = (grayhi - gray) / 2; gray = (grayhi + gray) / 2; if (err <= in_qe) err = gray * DBL_EPSILON; else err -= in_qe; /* Validate that the error is within limits (this has caused * problems before, it's much easier to detect them here.) */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_error(pp, buffer); } } } # endif /* !DIGITIZE */ that->bluef = that->greenf = that->redf = gray; that->bluee = that->greene = that->rede = err; /* The sBIT is the minium of the three colour channel sBITs. */ if (that->red_sBIT > that->green_sBIT) that->red_sBIT = that->green_sBIT; if (that->red_sBIT > that->blue_sBIT) that->red_sBIT = that->blue_sBIT; that->blue_sBIT = that->green_sBIT = that->red_sBIT; /* And remove the colour bit in the type: */ if (that->colour_type == PNG_COLOR_TYPE_RGB) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } this->next->mod(this->next, that, pp, display); }
173,643
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState, OnUpdateUserActivationState) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking, OnSetNeedsOcclusionTracking); IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame, OnBubbleLogicalScrollInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess, OnRenderFallbackContentInParentProcess) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState, OnUpdateUserActivationState) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking, OnSetNeedsOcclusionTracking); IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame, OnBubbleLogicalScrollInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess, OnRenderFallbackContentInParentProcess) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_END_MESSAGE_MAP() return handled; }
172,486