instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <zzoru007@gmail.com> Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Willem de Bruijn <willemb@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-125
void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && SKB_EXT_ERR(skb)->opt_stats) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } }
170,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: decnet_print(netdissect_options *ndo, register const u_char *ap, register u_int length, register u_int caplen) { register const union routehdr *rhp; register int mflags; int dst, src, hops; u_int nsplen, pktlen; const u_char *nspp; if (length < sizeof(struct shorthdr)) { ND_PRINT((ndo, "%s", tstr)); return; } ND_TCHECK2(*ap, sizeof(short)); pktlen = EXTRACT_LE_16BITS(ap); if (pktlen < sizeof(struct shorthdr)) { ND_PRINT((ndo, "%s", tstr)); return; } if (pktlen > length) { ND_PRINT((ndo, "%s", tstr)); return; } length = pktlen; rhp = (const union routehdr *)&(ap[sizeof(short)]); ND_TCHECK(rhp->rh_short.sh_flags); mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags); if (mflags & RMF_PAD) { /* pad bytes of some sort in front of message */ u_int padlen = mflags & RMF_PADMASK; if (ndo->ndo_vflag) ND_PRINT((ndo, "[pad:%d] ", padlen)); if (length < padlen + 2) { ND_PRINT((ndo, "%s", tstr)); return; } ND_TCHECK2(ap[sizeof(short)], padlen); ap += padlen; length -= padlen; caplen -= padlen; rhp = (const union routehdr *)&(ap[sizeof(short)]); mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags); } if (mflags & RMF_FVER) { ND_PRINT((ndo, "future-version-decnet")); ND_DEFAULTPRINT(ap, min(length, caplen)); return; } /* is it a control message? */ if (mflags & RMF_CTLMSG) { if (!print_decnet_ctlmsg(ndo, rhp, length, caplen)) goto trunc; return; } switch (mflags & RMF_MASK) { case RMF_LONG: if (length < sizeof(struct longhdr)) { ND_PRINT((ndo, "%s", tstr)); return; } ND_TCHECK(rhp->rh_long); dst = EXTRACT_LE_16BITS(rhp->rh_long.lg_dst.dne_remote.dne_nodeaddr); src = EXTRACT_LE_16BITS(rhp->rh_long.lg_src.dne_remote.dne_nodeaddr); hops = EXTRACT_LE_8BITS(rhp->rh_long.lg_visits); nspp = &(ap[sizeof(short) + sizeof(struct longhdr)]); nsplen = length - sizeof(struct longhdr); break; case RMF_SHORT: ND_TCHECK(rhp->rh_short); dst = EXTRACT_LE_16BITS(rhp->rh_short.sh_dst); src = EXTRACT_LE_16BITS(rhp->rh_short.sh_src); hops = (EXTRACT_LE_8BITS(rhp->rh_short.sh_visits) & VIS_MASK)+1; nspp = &(ap[sizeof(short) + sizeof(struct shorthdr)]); nsplen = length - sizeof(struct shorthdr); break; default: ND_PRINT((ndo, "unknown message flags under mask")); ND_DEFAULTPRINT((const u_char *)ap, min(length, caplen)); return; } ND_PRINT((ndo, "%s > %s %d ", dnaddr_string(ndo, src), dnaddr_string(ndo, dst), pktlen)); if (ndo->ndo_vflag) { if (mflags & RMF_RQR) ND_PRINT((ndo, "RQR ")); if (mflags & RMF_RTS) ND_PRINT((ndo, "RTS ")); if (mflags & RMF_IE) ND_PRINT((ndo, "IE ")); ND_PRINT((ndo, "%d hops ", hops)); } if (!print_nsp(ndo, nspp, nsplen)) goto trunc; return; trunc: ND_PRINT((ndo, "%s", tstr)); return; } Commit Message: CVE-2017-12899/DECnet: Fix bounds checking. If we're skipping over padding before the *real* flags, check whether the real flags are in the captured data before fetching it. This fixes a buffer over-read discovered by Kamil Frankowicz. Note one place where we don't need to do bounds checking as it's already been done. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
decnet_print(netdissect_options *ndo, register const u_char *ap, register u_int length, register u_int caplen) { register const union routehdr *rhp; register int mflags; int dst, src, hops; u_int nsplen, pktlen; const u_char *nspp; if (length < sizeof(struct shorthdr)) { ND_PRINT((ndo, "%s", tstr)); return; } ND_TCHECK2(*ap, sizeof(short)); pktlen = EXTRACT_LE_16BITS(ap); if (pktlen < sizeof(struct shorthdr)) { ND_PRINT((ndo, "%s", tstr)); return; } if (pktlen > length) { ND_PRINT((ndo, "%s", tstr)); return; } length = pktlen; rhp = (const union routehdr *)&(ap[sizeof(short)]); ND_TCHECK(rhp->rh_short.sh_flags); mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags); if (mflags & RMF_PAD) { /* pad bytes of some sort in front of message */ u_int padlen = mflags & RMF_PADMASK; if (ndo->ndo_vflag) ND_PRINT((ndo, "[pad:%d] ", padlen)); if (length < padlen + 2) { ND_PRINT((ndo, "%s", tstr)); return; } ND_TCHECK2(ap[sizeof(short)], padlen); ap += padlen; length -= padlen; caplen -= padlen; rhp = (const union routehdr *)&(ap[sizeof(short)]); ND_TCHECK(rhp->rh_short.sh_flags); mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags); } if (mflags & RMF_FVER) { ND_PRINT((ndo, "future-version-decnet")); ND_DEFAULTPRINT(ap, min(length, caplen)); return; } /* is it a control message? */ if (mflags & RMF_CTLMSG) { if (!print_decnet_ctlmsg(ndo, rhp, length, caplen)) goto trunc; return; } switch (mflags & RMF_MASK) { case RMF_LONG: if (length < sizeof(struct longhdr)) { ND_PRINT((ndo, "%s", tstr)); return; } ND_TCHECK(rhp->rh_long); dst = EXTRACT_LE_16BITS(rhp->rh_long.lg_dst.dne_remote.dne_nodeaddr); src = EXTRACT_LE_16BITS(rhp->rh_long.lg_src.dne_remote.dne_nodeaddr); hops = EXTRACT_LE_8BITS(rhp->rh_long.lg_visits); nspp = &(ap[sizeof(short) + sizeof(struct longhdr)]); nsplen = length - sizeof(struct longhdr); break; case RMF_SHORT: ND_TCHECK(rhp->rh_short); dst = EXTRACT_LE_16BITS(rhp->rh_short.sh_dst); src = EXTRACT_LE_16BITS(rhp->rh_short.sh_src); hops = (EXTRACT_LE_8BITS(rhp->rh_short.sh_visits) & VIS_MASK)+1; nspp = &(ap[sizeof(short) + sizeof(struct shorthdr)]); nsplen = length - sizeof(struct shorthdr); break; default: ND_PRINT((ndo, "unknown message flags under mask")); ND_DEFAULTPRINT((const u_char *)ap, min(length, caplen)); return; } ND_PRINT((ndo, "%s > %s %d ", dnaddr_string(ndo, src), dnaddr_string(ndo, dst), pktlen)); if (ndo->ndo_vflag) { if (mflags & RMF_RQR) ND_PRINT((ndo, "RQR ")); if (mflags & RMF_RTS) ND_PRINT((ndo, "RTS ")); if (mflags & RMF_IE) ND_PRINT((ndo, "IE ")); ND_PRINT((ndo, "%d hops ", hops)); } if (!print_nsp(ndo, nspp, nsplen)) goto trunc; return; trunc: ND_PRINT((ndo, "%s", tstr)); return; }
170,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EntrySync::remove(ExceptionState& exceptionState) const { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->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
void EntrySync::remove(ExceptionState& exceptionState) const { VoidSyncCallbackHelper* helper = VoidSyncCallbackHelper::create(); m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); }
171,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int SpdyProxyClientSocket::DoReadReplyComplete(int result) { if (result < 0) return result; if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) return ERR_TUNNEL_CONNECTION_FAILED; net_log_.AddEvent( NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS, base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers)); switch (response_.headers->response_code()) { case 200: // OK next_state_ = STATE_OPEN; return OK; case 302: // Found / Moved Temporarily if (SanitizeProxyRedirect(&response_, request_.url)) { redirect_has_load_timing_info_ = spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_); spdy_stream_->DetachDelegate(); next_state_ = STATE_DISCONNECTED; return ERR_HTTPS_PROXY_TUNNEL_RESPONSE; } else { LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } case 407: // Proxy Authentication Required next_state_ = STATE_OPEN; return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_); default: LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19
int SpdyProxyClientSocket::DoReadReplyComplete(int result) { if (result < 0) return result; if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) return ERR_TUNNEL_CONNECTION_FAILED; net_log_.AddEvent( NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS, base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers)); switch (response_.headers->response_code()) { case 200: // OK next_state_ = STATE_OPEN; return OK; case 302: // Found / Moved Temporarily if (!SanitizeProxyRedirect(&response_)) { LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } redirect_has_load_timing_info_ = spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_); // Note that this triggers a RST_STREAM_CANCEL. spdy_stream_->DetachDelegate(); next_state_ = STATE_DISCONNECTED; return ERR_HTTPS_PROXY_TUNNEL_RESPONSE; case 407: // Proxy Authentication Required next_state_ = STATE_OPEN; if (!SanitizeProxyAuth(&response_)) { LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_); default: LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } }
172,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _gnutls_server_name_recv_params (gnutls_session_t session, const opaque * data, size_t _data_size) { int i; const unsigned char *p; uint16_t len, type; ssize_t data_size = _data_size; int server_names = 0; if (session->security_parameters.entity == GNUTLS_SERVER) { DECR_LENGTH_RET (data_size, 2, 0); len = _gnutls_read_uint16 (data); if (len != data_size) { /* This is unexpected packet length, but * just ignore it, for now. */ gnutls_assert (); return 0; } p = data + 2; /* Count all server_names in the packet. */ while (data_size > 0) { DECR_LENGTH_RET (data_size, 1, 0); p++; DECR_LEN (data_size, 2); len = _gnutls_read_uint16 (p); p += 2; DECR_LENGTH_RET (data_size, len, 0); server_names++; p += len; } session->security_parameters.extensions.server_names_size = if (server_names == 0) return 0; /* no names found */ /* we cannot accept more server names. */ if (server_names > MAX_SERVER_NAME_EXTENSIONS) server_names = MAX_SERVER_NAME_EXTENSIONS; p = data + 2; for (i = 0; i < server_names; i++) server_names[i].name, p, len); session->security_parameters.extensions. server_names[i].name_length = len; session->security_parameters.extensions. server_names[i].type = GNUTLS_NAME_DNS; break; } } Commit Message: CWE ID: CWE-189
_gnutls_server_name_recv_params (gnutls_session_t session, const opaque * data, size_t _data_size) { int i; const unsigned char *p; uint16_t len, type; ssize_t data_size = _data_size; int server_names = 0; if (session->security_parameters.entity == GNUTLS_SERVER) { DECR_LENGTH_RET (data_size, 2, 0); len = _gnutls_read_uint16 (data); if (len != data_size) { /* This is unexpected packet length, but * just ignore it, for now. */ gnutls_assert (); return 0; } p = data + 2; /* Count all server_names in the packet. */ while (data_size > 0) { DECR_LENGTH_RET (data_size, 1, 0); p++; DECR_LEN (data_size, 2); len = _gnutls_read_uint16 (p); p += 2; if (len > 0) { DECR_LENGTH_RET (data_size, len, 0); server_names++; p += len; } else _gnutls_handshake_log ("HSK[%x]: Received zero size server name (under attack?)\n", session); } /* we cannot accept more server names. */ if (server_names > MAX_SERVER_NAME_EXTENSIONS) { _gnutls_handshake_log ("HSK[%x]: Too many server names received (under attack?)\n", session); server_names = MAX_SERVER_NAME_EXTENSIONS; } session->security_parameters.extensions.server_names_size = if (server_names == 0) return 0; /* no names found */ p = data + 2; for (i = 0; i < server_names; i++) server_names[i].name, p, len); session->security_parameters.extensions. server_names[i].name_length = len; session->security_parameters.extensions. server_names[i].type = GNUTLS_NAME_DNS; break; } }
165,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort) return res; if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <yhindin@rehat.com> CWE ID: CWE-20
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, BOOLEAN verifyLength, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength, verifyLength); if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort) return res; if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; }
170,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NaClProcessHost::SendStart() { if (!enable_ipc_proxy_) { if (!ReplyToRenderer(IPC::ChannelHandle())) return false; } return StartNaClExecution(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool NaClProcessHost::SendStart() {
170,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: smb2_flush(smb_request_t *sr) { smb_ofile_t *of = NULL; uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, "wwlqq", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } of = sr->fid_ofile; /* * XXX - todo: * Flush named pipe should drain writes. */ if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0) (void) smb_fsop_commit(sr, of->f_cr, of->f_node); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, "wwl", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); } Commit Message: 7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv Reviewed by: Gordon Ross <gwr@nexenta.com> Reviewed by: Matt Barden <matt.barden@nexenta.com> Reviewed by: Evan Layton <evan.layton@nexenta.com> Reviewed by: Dan McDonald <danmcd@omniti.com> Approved by: Gordon Ross <gwr@nexenta.com> CWE ID: CWE-476
smb2_flush(smb_request_t *sr) { uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, "wwlqq", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } smb_ofile_flush(sr, sr->fid_ofile); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, "wwl", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); }
168,825
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val - 1); } Commit Message: CWE ID: CWE-20
void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); }
165,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int genl_register_family(struct genl_family *family) { int err, i; int start = GENL_START_ALLOC, end = GENL_MAX_ID; err = genl_validate_ops(family); if (err) return err; genl_lock_all(); if (genl_family_find_byname(family->name)) { err = -EEXIST; goto errout_locked; } /* * Sadly, a few cases need to be special-cased * due to them having previously abused the API * and having used their family ID also as their * multicast group ID, so we use reserved IDs * for both to be sure we can do that mapping. */ if (family == &genl_ctrl) { /* and this needs to be special for initial family lookups */ start = end = GENL_ID_CTRL; } else if (strcmp(family->name, "pmcraid") == 0) { start = end = GENL_ID_PMCRAID; } else if (strcmp(family->name, "VFS_DQUOT") == 0) { start = end = GENL_ID_VFS_DQUOT; } if (family->maxattr && !family->parallel_ops) { family->attrbuf = kmalloc_array(family->maxattr + 1, sizeof(struct nlattr *), GFP_KERNEL); if (family->attrbuf == NULL) { err = -ENOMEM; goto errout_locked; } } else family->attrbuf = NULL; family->id = idr_alloc(&genl_fam_idr, family, start, end + 1, GFP_KERNEL); if (family->id < 0) { err = family->id; goto errout_locked; } err = genl_validate_assign_mc_groups(family); if (err) goto errout_remove; genl_unlock_all(); /* send all events */ genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0); for (i = 0; i < family->n_mcgrps; i++) genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family, &family->mcgrps[i], family->mcgrp_offset + i); return 0; errout_remove: idr_remove(&genl_fam_idr, family->id); kfree(family->attrbuf); errout_locked: genl_unlock_all(); return err; } Commit Message: genetlink: Fix a memory leak on error path In genl_register_family(), when idr_alloc() fails, we forget to free the memory we possibly allocate for family->attrbuf. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: 2ae0f17df1cd ("genetlink: use idr to track families") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Reviewed-by: Kirill Tkhai <ktkhai@virtuozzo.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
int genl_register_family(struct genl_family *family) { int err, i; int start = GENL_START_ALLOC, end = GENL_MAX_ID; err = genl_validate_ops(family); if (err) return err; genl_lock_all(); if (genl_family_find_byname(family->name)) { err = -EEXIST; goto errout_locked; } /* * Sadly, a few cases need to be special-cased * due to them having previously abused the API * and having used their family ID also as their * multicast group ID, so we use reserved IDs * for both to be sure we can do that mapping. */ if (family == &genl_ctrl) { /* and this needs to be special for initial family lookups */ start = end = GENL_ID_CTRL; } else if (strcmp(family->name, "pmcraid") == 0) { start = end = GENL_ID_PMCRAID; } else if (strcmp(family->name, "VFS_DQUOT") == 0) { start = end = GENL_ID_VFS_DQUOT; } if (family->maxattr && !family->parallel_ops) { family->attrbuf = kmalloc_array(family->maxattr + 1, sizeof(struct nlattr *), GFP_KERNEL); if (family->attrbuf == NULL) { err = -ENOMEM; goto errout_locked; } } else family->attrbuf = NULL; family->id = idr_alloc(&genl_fam_idr, family, start, end + 1, GFP_KERNEL); if (family->id < 0) { err = family->id; goto errout_free; } err = genl_validate_assign_mc_groups(family); if (err) goto errout_remove; genl_unlock_all(); /* send all events */ genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0); for (i = 0; i < family->n_mcgrps; i++) genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family, &family->mcgrps[i], family->mcgrp_offset + i); return 0; errout_remove: idr_remove(&genl_fam_idr, family->id); errout_free: kfree(family->attrbuf); errout_locked: genl_unlock_all(); return err; }
169,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void usage_exit() { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n", exec_name); exit(EXIT_FAILURE); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void usage_exit() { void usage_exit(void) { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n", exec_name); exit(EXIT_FAILURE); }
174,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG(php_gd_error("Reading gd2 header info")); for (i = 0; i < 4; i++) { ch = gdGetC(in); if (ch == EOF) { goto fail1; } id[i] = ch; } id[4] = 0; GD2_DBG(php_gd_error("Got file code: %s", id)); /* Equiv. of 'magick'. */ if (strcmp(id, GD2_ID) != 0) { GD2_DBG(php_gd_error("Not a valid gd2 file")); goto fail1; } /* Version */ if (gdGetWord(vers, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("Version: %d", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG(php_gd_error("Bad version: %d", *vers)); goto fail1; } /* Image Size */ if (!gdGetWord(sx, in)) { GD2_DBG(php_gd_error("Could not get x-size")); goto fail1; } if (!gdGetWord(sy, in)) { GD2_DBG(php_gd_error("Could not get y-size")); goto fail1; } GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord(cs, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("ChunkSize: %d", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG(php_gd_error("Bad chunk size: %d", *cs)); goto fail1; } /* Data Format */ if (gdGetWord(fmt, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("Format: %d", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG(php_gd_error("Bad data format: %d", *fmt)); goto fail1; } /* # of chunks wide */ if (gdGetWord(ncx, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("%d Chunks Wide", *ncx)); /* # of chunks high */ if (gdGetWord(ncy, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("%d Chunks vertically", *ncy)); if (gd2_compressed(*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG(php_gd_error("Reading %d chunk index entries", nc)); sidx = sizeof(t_chunk_info) * nc; if (sidx <= 0) { goto fail1; } cidx = gdCalloc(sidx, 1); for (i = 0; i < nc; i++) { if (gdGetInt(&cidx[i].offset, in) != 1) { gdFree(cidx); goto fail1; } if (gdGetInt(&cidx[i].size, in) != 1) { gdFree(cidx); goto fail1; } if (cidx[i].offset < 0 || cidx[i].size < 0) { gdFree(cidx); goto fail1; } } *chunkIdx = cidx; } GD2_DBG(php_gd_error("gd2 header complete")); return 1; fail1: return 0; } Commit Message: Fixed #72339 Integer Overflow in _gd2GetHeader() resulting in heap overflow CWE ID: CWE-190
static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG(php_gd_error("Reading gd2 header info")); for (i = 0; i < 4; i++) { ch = gdGetC(in); if (ch == EOF) { goto fail1; } id[i] = ch; } id[4] = 0; GD2_DBG(php_gd_error("Got file code: %s", id)); /* Equiv. of 'magick'. */ if (strcmp(id, GD2_ID) != 0) { GD2_DBG(php_gd_error("Not a valid gd2 file")); goto fail1; } /* Version */ if (gdGetWord(vers, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("Version: %d", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG(php_gd_error("Bad version: %d", *vers)); goto fail1; } /* Image Size */ if (!gdGetWord(sx, in)) { GD2_DBG(php_gd_error("Could not get x-size")); goto fail1; } if (!gdGetWord(sy, in)) { GD2_DBG(php_gd_error("Could not get y-size")); goto fail1; } GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord(cs, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("ChunkSize: %d", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG(php_gd_error("Bad chunk size: %d", *cs)); goto fail1; } /* Data Format */ if (gdGetWord(fmt, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("Format: %d", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG(php_gd_error("Bad data format: %d", *fmt)); goto fail1; } /* # of chunks wide */ if (gdGetWord(ncx, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("%d Chunks Wide", *ncx)); /* # of chunks high */ if (gdGetWord(ncy, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("%d Chunks vertically", *ncy)); if (gd2_compressed(*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG(php_gd_error("Reading %d chunk index entries", nc)); if (overflow2(sidx, nc)) { goto fail1; } sidx = sizeof(t_chunk_info) * nc; if (sidx <= 0) { goto fail1; } cidx = gdCalloc(sidx, 1); if (cidx == NULL) { goto fail1; } for (i = 0; i < nc; i++) { if (gdGetInt(&cidx[i].offset, in) != 1) { gdFree(cidx); goto fail1; } if (gdGetInt(&cidx[i].size, in) != 1) { gdFree(cidx); goto fail1; } if (cidx[i].offset < 0 || cidx[i].size < 0) { gdFree(cidx); goto fail1; } } *chunkIdx = cidx; } GD2_DBG(php_gd_error("gd2 header complete")); return 1; fail1: return 0; }
167,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fpDiff(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; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } 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
fpDiff(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; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; }
166,881
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: string_modifier_check(struct magic_set *ms, struct magic *m) { if ((ms->flags & MAGIC_CHECK) == 0) return 0; if (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0) { file_magwarn(ms, "'/BHhLl' modifiers are only allowed for pascal strings\n"); return -1; } switch (m->type) { case FILE_BESTRING16: case FILE_LESTRING16: if (m->str_flags != 0) { file_magwarn(ms, "no modifiers allowed for 16-bit strings\n"); return -1; } break; case FILE_STRING: case FILE_PSTRING: if ((m->str_flags & REGEX_OFFSET_START) != 0) { file_magwarn(ms, "'/%c' only allowed on regex and search\n", CHAR_REGEX_OFFSET_START); return -1; } break; case FILE_SEARCH: if (m->str_range == 0) { file_magwarn(ms, "missing range; defaulting to %d\n", STRING_DEFAULT_RANGE); m->str_range = STRING_DEFAULT_RANGE; return -1; } break; case FILE_REGEX: if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) { file_magwarn(ms, "'/%c' not allowed on regex\n", CHAR_COMPACT_WHITESPACE); return -1; } if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) { file_magwarn(ms, "'/%c' not allowed on regex\n", CHAR_COMPACT_OPTIONAL_WHITESPACE); return -1; } break; default: file_magwarn(ms, "coding error: m->type=%d\n", m->type); return -1; } return 0; } Commit Message: * Enforce limit of 8K on regex searches that have no limits * Allow the l modifier for regex to mean line count. Default to byte count. If line count is specified, assume a max of 80 characters per line to limit the byte count. * Don't allow conversions to be used for dates, allowing the mask field to be used as an offset. * Bump the version of the magic format so that regex changes are visible. CWE ID: CWE-399
string_modifier_check(struct magic_set *ms, struct magic *m) { if ((ms->flags & MAGIC_CHECK) == 0) return 0; if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) && (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) { file_magwarn(ms, "'/BHhLl' modifiers are only allowed for pascal strings\n"); return -1; } switch (m->type) { case FILE_BESTRING16: case FILE_LESTRING16: if (m->str_flags != 0) { file_magwarn(ms, "no modifiers allowed for 16-bit strings\n"); return -1; } break; case FILE_STRING: case FILE_PSTRING: if ((m->str_flags & REGEX_OFFSET_START) != 0) { file_magwarn(ms, "'/%c' only allowed on regex and search\n", CHAR_REGEX_OFFSET_START); return -1; } break; case FILE_SEARCH: if (m->str_range == 0) { file_magwarn(ms, "missing range; defaulting to %d\n", STRING_DEFAULT_RANGE); m->str_range = STRING_DEFAULT_RANGE; return -1; } break; case FILE_REGEX: if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) { file_magwarn(ms, "'/%c' not allowed on regex\n", CHAR_COMPACT_WHITESPACE); return -1; } if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) { file_magwarn(ms, "'/%c' not allowed on regex\n", CHAR_COMPACT_OPTIONAL_WHITESPACE); return -1; } break; default: file_magwarn(ms, "coding error: m->type=%d\n", m->type); return -1; } return 0; }
166,356
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *name = d->name; struct device dev = d->udev->dev; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); dev_info(&dev, "%s: '%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, name); } Commit Message: [media] dvb-usb-v2: avoid use-after-free I ran into a stack frame size warning because of the on-stack copy of the USB device structure: drivers/media/usb/dvb-usb-v2/dvb_usb_core.c: In function 'dvb_usbv2_disconnect': drivers/media/usb/dvb-usb-v2/dvb_usb_core.c:1029:1: error: the frame size of 1104 bytes is larger than 1024 bytes [-Werror=frame-larger-than=] Copying a device structure like this is wrong for a number of other reasons too aside from the possible stack overflow. One of them is that the dev_info() call will print the name of the device later, but AFAICT we have only copied a pointer to the name earlier and the actual name has been freed by the time it gets printed. This removes the on-stack copy of the device and instead copies the device name using kstrdup(). I'm ignoring the possible failure here as both printk() and kfree() are able to deal with NULL pointers. Signed-off-by: Arnd Bergmann <arnd@arndb.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com> CWE ID: CWE-119
void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *devname = kstrdup(dev_name(&d->udev->dev), GFP_KERNEL); const char *drvname = d->name; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); pr_info("%s: '%s:%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, drvname, devname); kfree(devname); }
168,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; } Commit Message: udf: avoid info leak on export For type 0x51 the udf.parent_partref member in struct fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-200
static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.parent_partref = 0; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; }
166,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Block::Block(long long start, long long size_, long long discard_padding) : m_start(start), m_size(size_), m_track(0), m_timecode(-1), m_flags(0), m_frames(NULL), m_frame_count(-1), m_discard_padding(discard_padding) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Block::Block(long long start, long long size_, long long discard_padding) :
174,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int get_scl(void) { return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1); } 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
int get_scl(void)
169,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeOSChangeInputMethod( InputMethodStatusConnection* connection, const char* name) { DCHECK(name); DLOG(INFO) << "ChangeInputMethod: " << name; g_return_val_if_fail(connection, false); return connection->ChangeInputMethod(name); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeOSChangeInputMethod(
170,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ContextualSearchDelegate::DecodeSearchTermFromJsonResponse( const std::string& response, std::string* search_term, std::string* display_text, std::string* alternate_term, std::string* mid, std::string* prevent_preload, int* mention_start, int* mention_end, std::string* lang, std::string* thumbnail_url, std::string* caption) { bool contains_xssi_escape = base::StartsWith(response, kXssiEscape, base::CompareCase::SENSITIVE); const std::string& proper_json = contains_xssi_escape ? response.substr(sizeof(kXssiEscape) - 1) : response; JSONStringValueDeserializer deserializer(proper_json); std::unique_ptr<base::Value> root = deserializer.Deserialize(nullptr, nullptr); const std::unique_ptr<base::DictionaryValue> dict = base::DictionaryValue::From(std::move(root)); if (!dict) return; dict->GetString(kContextualSearchPreventPreload, prevent_preload); dict->GetString(kContextualSearchResponseSearchTermParam, search_term); dict->GetString(kContextualSearchResponseLanguageParam, lang); if (!dict->GetString(kContextualSearchResponseDisplayTextParam, display_text)) { *display_text = *search_term; } dict->GetString(kContextualSearchResponseMidParam, mid); if (!field_trial_->IsDecodeMentionsDisabled()) { base::ListValue* mentions_list = nullptr; dict->GetList(kContextualSearchMentions, &mentions_list); if (mentions_list && mentions_list->GetSize() >= 2) ExtractMentionsStartEnd(*mentions_list, mention_start, mention_end); } std::string selected_text; dict->GetString(kContextualSearchResponseSelectedTextParam, &selected_text); if (selected_text != *search_term) { *alternate_term = selected_text; } else { std::string resolved_term; dict->GetString(kContextualSearchResponseResolvedTermParam, &resolved_term); if (resolved_term != *search_term) { *alternate_term = resolved_term; } } if (field_trial_->IsNowOnTapBarIntegrationEnabled()) { dict->GetString(kContextualSearchCaption, caption); dict->GetString(kContextualSearchThumbnail, thumbnail_url); } } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
void ContextualSearchDelegate::DecodeSearchTermFromJsonResponse( const std::string& response, std::string* search_term, std::string* display_text, std::string* alternate_term, std::string* mid, std::string* prevent_preload, int* mention_start, int* mention_end, std::string* lang, std::string* thumbnail_url, std::string* caption) { bool contains_xssi_escape = base::StartsWith(response, kXssiEscape, base::CompareCase::SENSITIVE); const std::string& proper_json = contains_xssi_escape ? response.substr(sizeof(kXssiEscape) - 1) : response; JSONStringValueDeserializer deserializer(proper_json); std::unique_ptr<base::Value> root = deserializer.Deserialize(nullptr, nullptr); const std::unique_ptr<base::DictionaryValue> dict = base::DictionaryValue::From(std::move(root)); if (!dict) return; dict->GetString(kContextualSearchPreventPreload, prevent_preload); dict->GetString(kContextualSearchResponseSearchTermParam, search_term); dict->GetString(kContextualSearchResponseLanguageParam, lang); if (!dict->GetString(kContextualSearchResponseDisplayTextParam, display_text)) { *display_text = *search_term; } dict->GetString(kContextualSearchResponseMidParam, mid); if (!field_trial_->IsDecodeMentionsDisabled()) { base::ListValue* mentions_list = nullptr; dict->GetList(kContextualSearchMentions, &mentions_list); if (mentions_list && mentions_list->GetSize() >= 2) ExtractMentionsStartEnd(*mentions_list, mention_start, mention_end); } std::string selected_text; dict->GetString(kContextualSearchResponseSelectedTextParam, &selected_text); if (selected_text != *search_term) { *alternate_term = selected_text; } else { std::string resolved_term; dict->GetString(kContextualSearchResponseResolvedTermParam, &resolved_term); if (resolved_term != *search_term) { *alternate_term = resolved_term; } } if (field_trial_->IsContextualCardsBarIntegrationEnabled()) { // Get the basic Bar data for Contextual Cards integration directly // from the root. dict->GetString(kContextualSearchCaption, caption); dict->GetString(kContextualSearchThumbnail, thumbnail_url); } }
171,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) { if (paintingDisabled()) return; notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) { if (paintingDisabled()) return; #if USE(WXGC) Path path; path.addRoundedRect(rect, topLeft, topRight, bottomLeft, bottomRight); m_data->context->SetBrush(wxBrush(color)); wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); gc->FillPath(*path.platformPath()); #endif }
170,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void __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 <viro@zeniv.linux.org.uk> 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *parse_string( cJSON *item, const char *str ) { const char *ptr = str + 1; char *ptr2; char *out; int len = 0; unsigned uc, uc2; if ( *str != '\"' ) { /* Not a string! */ ep = str; return 0; } /* Skip escaped quotes. */ while ( *ptr != '\"' && *ptr && ++len ) if ( *ptr++ == '\\' ) ptr++; if ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) ) return 0; ptr = str + 1; ptr2 = out; while ( *ptr != '\"' && *ptr ) { if ( *ptr != '\\' ) *ptr2++ = *ptr++; else { ptr++; switch ( *ptr ) { case 'b': *ptr2++ ='\b'; break; case 'f': *ptr2++ ='\f'; break; case 'n': *ptr2++ ='\n'; break; case 'r': *ptr2++ ='\r'; break; case 't': *ptr2++ ='\t'; break; case 'u': /* Transcode utf16 to utf8. */ /* Get the unicode char. */ sscanf( ptr + 1,"%4x", &uc ); ptr += 4; /* Check for invalid. */ if ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 ) break; /* UTF16 surrogate pairs. */ if ( uc >= 0xD800 && uc <= 0xDBFF ) { if ( ptr[1] != '\\' || ptr[2] != 'u' ) /* Missing second-half of surrogate. */ break; sscanf( ptr + 3, "%4x", &uc2 ); ptr += 6; if ( uc2 < 0xDC00 || uc2 > 0xDFFF ) /* Invalid second-half of surrogate. */ break; uc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF ); } len = 4; if ( uc < 0x80 ) len = 1; else if ( uc < 0x800 ) len = 2; else if ( uc < 0x10000 ) len = 3; ptr2 += len; switch ( len ) { case 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 1: *--ptr2 = ( uc | firstByteMark[len] ); } ptr2 += len; break; default: *ptr2++ = *ptr; break; } ++ptr; } } *ptr2 = 0; if ( *ptr == '\"' ) ++ptr; item->valuestring = out; item->type = cJSON_String; return ptr; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
static const char *parse_string( cJSON *item, const char *str ) static const char *parse_string(cJSON *item,const char *str,const char **ep) { const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\"') {*ep=str;return 0;} /* not a string! */ while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */ out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */ item->type=cJSON_String; ptr=str+1;ptr2=out; while (ptr < end_ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */ if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ { if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */ if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */ uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\"') ptr++; return ptr; }
167,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeNetworkDelegate::AccumulateContentLength( int64 received_content_length, int64 original_content_length, bool via_data_reduction_proxy) { DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); StoreAccumulatedContentLength(received_content_length, original_content_length, via_data_reduction_proxy); received_content_length_ += received_content_length; original_content_length_ += original_content_length; } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void ChromeNetworkDelegate::AccumulateContentLength( int64 received_content_length, int64 original_content_length, chrome_browser_net::DataReductionRequestType data_reduction_type) { DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); StoreAccumulatedContentLength(received_content_length, original_content_length, data_reduction_type); received_content_length_ += received_content_length; original_content_length_ += original_content_length; }
171,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { /* Allow mapping to your own filesystem ids */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, current_fsuid())) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (gid_eq(gid, current_fsgid())) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. * And the opener of the id file also had the approprpiate capability. */ if (ns_capable(ns->parent, cap_setid) && file_ns_capable(file, ns->parent, cap_setid)) return true; return false; } Commit Message: userns: Check uid_map's opener's fsuid, not the current fsuid Signed-off-by: Andy Lutomirski <luto@amacapital.net> CWE ID: CWE-264
static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { /* Allow mapping to your own filesystem ids */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, file->f_cred->fsuid)) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (gid_eq(gid, file->f_cred->fsgid)) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. * And the opener of the id file also had the approprpiate capability. */ if (ns_capable(ns->parent, cap_setid) && file_ns_capable(file, ns->parent, cap_setid)) return true; return false; }
169,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fpDiff(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; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; } Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in previous commit (fix for MSVR 35105) CWE ID: CWE-119
fpDiff(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; uint8 *cp = (uint8 *) cp0; uint8 *tmp; if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } tmp = (uint8 *)_TIFFmalloc(cc); if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; }
169,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void coroutine_fn v9fs_wstat(void *opaque) { int32_t fid; int err = 0; int16_t unused; V9fsStat v9stat; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; v9fs_stat_init(&v9stat); err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); goto out_nofid; } Commit Message: CWE ID: CWE-362
static void coroutine_fn v9fs_wstat(void *opaque) { int32_t fid; int err = 0; int16_t unused; V9fsStat v9stat; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; v9fs_stat_init(&v9stat); err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); goto out_nofid; }
164,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } }
167,035
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unix_client_connect(hsm_com_client_hdl_t *hdl) { int fd, len; struct sockaddr_un unix_addr; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { return HSM_COM_ERROR; } memset(&unix_addr,0,sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; if(strlen(hdl->c_path) >= sizeof(unix_addr.sun_path)) { close(fd); return HSM_COM_PATH_ERR; } snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s", hdl->c_path); len = SUN_LEN(&unix_addr); unlink(unix_addr.sun_path); if(bind(fd, (struct sockaddr *)&unix_addr, len) < 0) { unlink(hdl->c_path); close(fd); return HSM_COM_BIND_ERR; } if(chmod(unix_addr.sun_path, S_IRWXU) < 0) { unlink(hdl->c_path); close(fd); return HSM_COM_CHMOD_ERR; } memset(&unix_addr,0,sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; strncpy(unix_addr.sun_path, hdl->s_path, sizeof(unix_addr.sun_path)); unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0; len = SUN_LEN(&unix_addr); if (connect(fd, (struct sockaddr *) &unix_addr, len) < 0) { unlink(hdl->c_path); close(fd); return HSM_COM_CONX_ERR; } hdl->client_fd = fd; hdl->client_state = HSM_COM_C_STATE_CT; if(unix_sck_send_conn(hdl, 2) != HSM_COM_OK) { hdl->client_state = HSM_COM_C_STATE_IN; return HSM_COM_SEND_ERR; } return HSM_COM_OK; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362
unix_client_connect(hsm_com_client_hdl_t *hdl) { int fd, len; struct sockaddr_un unix_addr; hsm_com_errno_t res = HSM_COM_OK; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { return HSM_COM_ERROR; } memset(&unix_addr,0,sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; if(strlen(hdl->c_path) >= sizeof(unix_addr.sun_path)) { res = HSM_COM_PATH_ERR; goto cleanup; } snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s", hdl->c_path); len = SUN_LEN(&unix_addr); unlink(unix_addr.sun_path); if(bind(fd, (struct sockaddr *)&unix_addr, len) < 0) { res = HSM_COM_BIND_ERR; goto cleanup; } if(chmod(unix_addr.sun_path, S_IRWXU) < 0) { res = HSM_COM_CHMOD_ERR; goto cleanup; } memset(&unix_addr,0,sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; strncpy(unix_addr.sun_path, hdl->s_path, sizeof(unix_addr.sun_path)); unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0; len = SUN_LEN(&unix_addr); if (connect(fd, (struct sockaddr *) &unix_addr, len) < 0) { res = HSM_COM_CONX_ERR; goto cleanup; } hdl->client_fd = fd; hdl->client_state = HSM_COM_C_STATE_CT; if(unix_sck_send_conn(hdl, 2) != HSM_COM_OK) { hdl->client_state = HSM_COM_C_STATE_IN; res = HSM_COM_SEND_ERR; } return res; cleanup: close(fd); return res; }
170,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeContentUtilityClient::OnMessageReceived( const IPC::Message& message) { if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type())) return false; bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage) #if defined(OS_CHROMEOS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage, OnRobustJPEGDecodeImage) #endif // defined(OS_CHROMEOS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff, OnPatchFileBsdiff) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette, OnPatchFileCourgette) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing) #if defined(FULL_SAFE_BROWSING) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection, OnAnalyzeZipFileForDownloadProtection) #endif #if defined(ENABLE_EXTENSIONS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata, OnParseMediaMetadata) #endif #if defined(OS_CHROMEOS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile) #endif IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() for (Handlers::iterator it = handlers_.begin(); !handled && it != handlers_.end(); ++it) { handled = (*it)->OnMessageReceived(message); } return handled; } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 R=isherman@chromium.org, kenrb@chromium.org, mattm@chromium.org, thestig@chromium.org Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
bool ChromeContentUtilityClient::OnMessageReceived( const IPC::Message& message) { if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type())) return false; bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage) #if defined(OS_CHROMEOS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage, OnRobustJPEGDecodeImage) #endif // defined(OS_CHROMEOS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff, OnPatchFileBsdiff) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette, OnPatchFileCourgette) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing) #if defined(FULL_SAFE_BROWSING) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection, OnAnalyzeZipFileForDownloadProtection) #if defined(OS_MACOSX) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeDmgFileForDownloadProtection, OnAnalyzeDmgFileForDownloadProtection) #endif #endif #if defined(ENABLE_EXTENSIONS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata, OnParseMediaMetadata) #endif #if defined(OS_CHROMEOS) IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile) #endif IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() for (Handlers::iterator it = handlers_.begin(); !handled && it != handlers_.end(); ++it) { handled = (*it)->OnMessageReceived(message); } return handled; }
171,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name); exit(FPM_EXIT_SOFTWARE); } } /* }}} */ Commit Message: Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that. CWE ID: CWE-400
static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; fpm_globals.listening_socket = dup(wp->listening_socket); if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name); exit(FPM_EXIT_SOFTWARE); } } /* }}} */
169,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } img->color_space = OPJ_CLRSPC_SRGB; }/* color_sycc_to_rgb() */ Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726 CWE ID: CWE-125
void color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } }/* color_sycc_to_rgb() */
168,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool_t auth_gssapi_unwrap_data( OM_uint32 *major, OM_uint32 *minor, gss_ctx_id_t context, uint32_t seq_num, XDR *in_xdrs, bool_t (*xdr_func)(), caddr_t xdr_ptr) { gss_buffer_desc in_buf, out_buf; XDR temp_xdrs; uint32_t verf_seq_num; int conf, qop; unsigned int length; PRINTF(("gssapi_unwrap_data: starting\n")); *major = GSS_S_COMPLETE; *minor = 0; /* assumption */ in_buf.value = NULL; out_buf.value = NULL; if (! xdr_bytes(in_xdrs, (char **) &in_buf.value, &length, (unsigned int) -1)) { PRINTF(("gssapi_unwrap_data: deserializing encrypted data failed\n")); temp_xdrs.x_op = XDR_FREE; (void)xdr_bytes(&temp_xdrs, (char **) &in_buf.value, &length, (unsigned int) -1); return FALSE; } in_buf.length = length; *major = gss_unseal(minor, context, &in_buf, &out_buf, &conf, &qop); free(in_buf.value); if (*major != GSS_S_COMPLETE) return FALSE; PRINTF(("gssapi_unwrap_data: %llu bytes data, %llu bytes sealed\n", (unsigned long long)out_buf.length, (unsigned long long)in_buf.length)); xdrmem_create(&temp_xdrs, out_buf.value, out_buf.length, XDR_DECODE); /* deserialize the sequence number */ if (! xdr_u_int32(&temp_xdrs, &verf_seq_num)) { PRINTF(("gssapi_unwrap_data: deserializing verf_seq_num failed\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } if (verf_seq_num != seq_num) { PRINTF(("gssapi_unwrap_data: seq %d specified, read %d\n", seq_num, verf_seq_num)); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } PRINTF(("gssapi_unwrap_data: unwrap seq_num %d okay\n", verf_seq_num)); /* deserialize the arguments into xdr_ptr */ if (! (*xdr_func)(&temp_xdrs, xdr_ptr)) { PRINTF(("gssapi_unwrap_data: deserializing arguments failed\n")); gss_release_buffer(minor, &out_buf); xdr_free(xdr_func, xdr_ptr); XDR_DESTROY(&temp_xdrs); return FALSE; } PRINTF(("gssapi_unwrap_data: succeeding\n\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return TRUE; } Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421] [MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free partial deserialization results upon failure to deserialize. This responsibility belongs to the callers, svctcp_getargs() and svcudp_getargs(); doing it in the unwrap function results in freeing the results twice. In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers we are freeing, as other XDR functions such as xdr_bytes() and xdr_string(). ticket: 8056 (new) target_version: 1.13.1 tags: pullup CWE ID:
bool_t auth_gssapi_unwrap_data( OM_uint32 *major, OM_uint32 *minor, gss_ctx_id_t context, uint32_t seq_num, XDR *in_xdrs, bool_t (*xdr_func)(), caddr_t xdr_ptr) { gss_buffer_desc in_buf, out_buf; XDR temp_xdrs; uint32_t verf_seq_num; int conf, qop; unsigned int length; PRINTF(("gssapi_unwrap_data: starting\n")); *major = GSS_S_COMPLETE; *minor = 0; /* assumption */ in_buf.value = NULL; out_buf.value = NULL; if (! xdr_bytes(in_xdrs, (char **) &in_buf.value, &length, (unsigned int) -1)) { PRINTF(("gssapi_unwrap_data: deserializing encrypted data failed\n")); temp_xdrs.x_op = XDR_FREE; (void)xdr_bytes(&temp_xdrs, (char **) &in_buf.value, &length, (unsigned int) -1); return FALSE; } in_buf.length = length; *major = gss_unseal(minor, context, &in_buf, &out_buf, &conf, &qop); free(in_buf.value); if (*major != GSS_S_COMPLETE) return FALSE; PRINTF(("gssapi_unwrap_data: %llu bytes data, %llu bytes sealed\n", (unsigned long long)out_buf.length, (unsigned long long)in_buf.length)); xdrmem_create(&temp_xdrs, out_buf.value, out_buf.length, XDR_DECODE); /* deserialize the sequence number */ if (! xdr_u_int32(&temp_xdrs, &verf_seq_num)) { PRINTF(("gssapi_unwrap_data: deserializing verf_seq_num failed\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } if (verf_seq_num != seq_num) { PRINTF(("gssapi_unwrap_data: seq %d specified, read %d\n", seq_num, verf_seq_num)); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } PRINTF(("gssapi_unwrap_data: unwrap seq_num %d okay\n", verf_seq_num)); /* deserialize the arguments into xdr_ptr */ if (! (*xdr_func)(&temp_xdrs, xdr_ptr)) { PRINTF(("gssapi_unwrap_data: deserializing arguments failed\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return FALSE; } PRINTF(("gssapi_unwrap_data: succeeding\n\n")); gss_release_buffer(minor, &out_buf); XDR_DESTROY(&temp_xdrs); return TRUE; }
166,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[3],b[3],c1,c2,c3); r[6]=c1; r[7]=c2; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org> CWE ID: CWE-310
void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[3],b[3],c1,c2,c3); r[6]=c1; r[7]=c2; }
166,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } } Commit Message: CWE ID: CWE-119
void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } }
165,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StorageHandler::GetUsageAndQuota( const String& origin, std::unique_ptr<GetUsageAndQuotaCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); GURL origin_url(origin); if (!origin_url.is_valid()) { return callback->sendFailure( Response::Error(origin + " is not a valid URL")); } storage::QuotaManager* manager = process_->GetStoragePartition()->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager), origin_url, 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 <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void StorageHandler::GetUsageAndQuota( const String& origin, std::unique_ptr<GetUsageAndQuotaCallback> callback) { if (!storage_partition_) return callback->sendFailure(Response::InternalError()); GURL origin_url(origin); if (!origin_url.is_valid()) { return callback->sendFailure( Response::Error(origin + " is not a valid URL")); } storage::QuotaManager* manager = storage_partition_->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager), origin_url, base::Passed(std::move(callback)))); }
172,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *isk = inet_sk(sk); int family = sk->sk_family; struct sk_buff *skb; int copied, err; pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num); err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; if (flags & MSG_ERRQUEUE) { if (family == AF_INET) { return ip_recv_error(sk, msg, len); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { return pingv6_ops.ipv6_recv_error(sk, msg, len); #endif } } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* Don't bother checking the checksum */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address and add cmsg data. */ if (family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; sin->sin_family = AF_INET; sin->sin_port = 0 /* skb->h.uh->source */; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); if (isk->cmsg_flags) ip_cmsg_recv(msg, skb); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *ip6 = ipv6_hdr(skb); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ip6->saddr; sin6->sin6_flowinfo = 0; if (np->sndflow) sin6->sin6_flowinfo = ip6_flowinfo(ip6); sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); *addr_len = sizeof(*sin6); if (inet6_sk(sk)->rxopt.all) pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb); #endif } else { BUG(); } err = copied; done: skb_free_datagram(sk, skb); out: pr_debug("ping_recvmsg -> %d\n", err); return err; } Commit Message: ping: prevent NULL pointer dereference on write to msg_name A plain read() on a socket does set msg->msg_name to NULL. So check for NULL pointer first. Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *isk = inet_sk(sk); int family = sk->sk_family; struct sk_buff *skb; int copied, err; pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num); err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; if (flags & MSG_ERRQUEUE) { if (family == AF_INET) { return ip_recv_error(sk, msg, len); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { return pingv6_ops.ipv6_recv_error(sk, msg, len); #endif } } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* Don't bother checking the checksum */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address and add cmsg data. */ if (family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; if (sin) { sin->sin_family = AF_INET; sin->sin_port = 0 /* skb->h.uh->source */; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (isk->cmsg_flags) ip_cmsg_recv(msg, skb); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *ip6 = ipv6_hdr(skb); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; if (sin6) { sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ip6->saddr; sin6->sin6_flowinfo = 0; if (np->sndflow) sin6->sin6_flowinfo = ip6_flowinfo(ip6); sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); *addr_len = sizeof(*sin6); } if (inet6_sk(sk)->rxopt.all) pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb); #endif } else { BUG(); } err = copied; done: skb_free_datagram(sk, skb); out: pr_debug("ping_recvmsg -> %d\n", err); return err; }
165,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: normalize_color_encoding(color_encoding *encoding) { PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y + encoding->blue.Y; if (whiteY != 1) { encoding->red.X /= whiteY; encoding->red.Y /= whiteY; encoding->red.Z /= whiteY; encoding->green.X /= whiteY; encoding->green.Y /= whiteY; encoding->green.Z /= whiteY; encoding->blue.X /= whiteY; encoding->blue.Y /= whiteY; encoding->blue.Z /= whiteY; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
normalize_color_encoding(color_encoding *encoding) { const double whiteY = encoding->red.Y + encoding->green.Y + encoding->blue.Y; if (whiteY != 1) { encoding->red.X /= whiteY; encoding->red.Y /= whiteY; encoding->red.Z /= whiteY; encoding->green.X /= whiteY; encoding->green.Y /= whiteY; encoding->green.Z /= whiteY; encoding->blue.X /= whiteY; encoding->blue.Y /= whiteY; encoding->blue.Z /= whiteY; } }
173,673
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerContainer::registerServiceWorkerImpl(ExecutionContext* executionContext, const KURL& rawScriptURL, const KURL& scope, PassOwnPtr<RegistrationCallbacks> callbacks) { if (!m_provider) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeState, "Failed to register a ServiceWorker: The document is in an invalid state.")); return; } RefPtr<SecurityOrigin> documentOrigin = executionContext->getSecurityOrigin(); String errorMessage; if (!executionContext->isSecureContext(errorMessage)) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, errorMessage)); return; } KURL pageURL = KURL(KURL(), documentOrigin->toString()); if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(pageURL.protocol())) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the current origin ('" + documentOrigin->toString() + "') is not supported."))); return; } KURL scriptURL = rawScriptURL; scriptURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(scriptURL)) { RefPtr<SecurityOrigin> scriptOrigin = SecurityOrigin::create(scriptURL); callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scriptURL ('" + scriptOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "')."))); return; } if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(scriptURL.protocol())) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the script ('" + scriptURL.getString() + "') is not supported."))); return; } KURL patternURL = scope; patternURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(patternURL)) { RefPtr<SecurityOrigin> patternOrigin = SecurityOrigin::create(patternURL); callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scope ('" + patternOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "')."))); return; } if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(patternURL.protocol())) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the scope ('" + patternURL.getString() + "') is not supported."))); return; } WebString webErrorMessage; if (!m_provider->validateScopeAndScriptURL(patternURL, scriptURL, &webErrorMessage)) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeType, WebString::fromUTF8("Failed to register a ServiceWorker: " + webErrorMessage.utf8()))); return; } m_provider->registerServiceWorker(patternURL, scriptURL, callbacks.leakPtr()); } Commit Message: Check CSP before registering ServiceWorkers Service Worker registrations should be subject to the same CSP checks as other workers. The spec doesn't say this explicitly (https://www.w3.org/TR/CSP2/#directive-child-src-workers says "Worker or SharedWorker constructors"), but it seems to be in the spirit of things, and it matches Firefox's behavior. BUG=579801 Review URL: https://codereview.chromium.org/1861253004 Cr-Commit-Position: refs/heads/master@{#385775} CWE ID: CWE-284
void ServiceWorkerContainer::registerServiceWorkerImpl(ExecutionContext* executionContext, const KURL& rawScriptURL, const KURL& scope, PassOwnPtr<RegistrationCallbacks> callbacks) { if (!m_provider) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeState, "Failed to register a ServiceWorker: The document is in an invalid state.")); return; } RefPtr<SecurityOrigin> documentOrigin = executionContext->getSecurityOrigin(); String errorMessage; if (!executionContext->isSecureContext(errorMessage)) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, errorMessage)); return; } KURL pageURL = KURL(KURL(), documentOrigin->toString()); if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(pageURL.protocol())) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the current origin ('" + documentOrigin->toString() + "') is not supported."))); return; } KURL scriptURL = rawScriptURL; scriptURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(scriptURL)) { RefPtr<SecurityOrigin> scriptOrigin = SecurityOrigin::create(scriptURL); callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scriptURL ('" + scriptOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "')."))); return; } if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(scriptURL.protocol())) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the script ('" + scriptURL.getString() + "') is not supported."))); return; } KURL patternURL = scope; patternURL.removeFragmentIdentifier(); if (!documentOrigin->canRequest(patternURL)) { RefPtr<SecurityOrigin> patternOrigin = SecurityOrigin::create(patternURL); callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scope ('" + patternOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "')."))); return; } if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(patternURL.protocol())) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the scope ('" + patternURL.getString() + "') is not supported."))); return; } WebString webErrorMessage; if (!m_provider->validateScopeAndScriptURL(patternURL, scriptURL, &webErrorMessage)) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeType, WebString::fromUTF8("Failed to register a ServiceWorker: " + webErrorMessage.utf8()))); return; } ContentSecurityPolicy* csp = executionContext->contentSecurityPolicy(); if (csp) { if (!csp->allowWorkerContextFromSource(scriptURL, ContentSecurityPolicy::DidNotRedirect, ContentSecurityPolicy::SendReport)) { callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The provided scriptURL ('" + scriptURL.getString() + "') violates the Content Security Policy."))); return; } } m_provider->registerServiceWorker(patternURL, scriptURL, callbacks.leakPtr()); }
173,285
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: print_trans(netdissect_options *ndo, const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf) { u_int bcc; const char *f1, *f2, *f3, *f4; const u_char *data, *param; const u_char *w = words + 1; int datalen, paramlen; if (request) { ND_TCHECK2(w[12 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); datalen = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n"; f2 = "|Name=[S]\n"; f3 = "|Param "; f4 = "|Data "; } else { ND_TCHECK2(w[7 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); datalen = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n"; f2 = "|Unknown "; f3 = "|Param "; f4 = "|Data "; } smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf), unicodestr); ND_TCHECK2(*data1, 2); bcc = EXTRACT_LE_16BITS(data1); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr); if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) { print_browse(ndo, param, paramlen, data, datalen); return; } if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) { print_ipc(ndo, param, paramlen, data, datalen); return; } if (paramlen) smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr); if (datalen) smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: (for 4.9.3) SMB: Add two missing bounds checks CWE ID: CWE-125
print_trans(netdissect_options *ndo, const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf) { u_int bcc; const char *f1, *f2, *f3, *f4; const u_char *data, *param; const u_char *w = words + 1; int datalen, paramlen; if (request) { ND_TCHECK2(w[12 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); datalen = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n"; f2 = "|Name=[S]\n"; f3 = "|Param "; f4 = "|Data "; } else { ND_TCHECK2(w[7 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); datalen = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n"; f2 = "|Unknown "; f3 = "|Param "; f4 = "|Data "; } smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf), unicodestr); ND_TCHECK2(*data1, 2); bcc = EXTRACT_LE_16BITS(data1); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr); #define MAILSLOT_BROWSE_STR "\\MAILSLOT\\BROWSE" ND_TCHECK2(*(data1 + 2), strlen(MAILSLOT_BROWSE_STR) + 1); if (strcmp((const char *)(data1 + 2), MAILSLOT_BROWSE_STR) == 0) { print_browse(ndo, param, paramlen, data, datalen); return; } #undef MAILSLOT_BROWSE_STR #define PIPE_LANMAN_STR "\\PIPE\\LANMAN" ND_TCHECK2(*(data1 + 2), strlen(PIPE_LANMAN_STR) + 1); if (strcmp((const char *)(data1 + 2), PIPE_LANMAN_STR) == 0) { print_ipc(ndo, param, paramlen, data, datalen); return; } #undef PIPE_LANMAN_STR if (paramlen) smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr); if (datalen) smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); }
169,815
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } }
167,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: linkaddr_string(netdissect_options *ndo, const u_char *ep, const unsigned int type, const unsigned int len) { register u_int i; register char *cp; register struct enamemem *tp; if (len == 0) return ("<empty>"); if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN) return (etheraddr_string(ndo, ep)); if (type == LINKADDR_FRELAY) return (q922_string(ndo, ep, len)); tp = lookup_bytestring(ndo, ep, len); if (tp->e_name) return (tp->e_name); tp->e_name = cp = (char *)malloc(len*3); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "linkaddr_string: malloc"); *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; for (i = len-1; i > 0 ; --i) { *cp++ = ':'; *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; } *cp = '\0'; return (tp->e_name); } Commit Message: CVE-2017-12894/In lookup_bytestring(), take the length of the byte string into account. Otherwise, if, in our search of the hash table, we come across a byte string that's shorter than the string we're looking for, we'll search past the end of the string in the hash table. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
linkaddr_string(netdissect_options *ndo, const u_char *ep, const unsigned int type, const unsigned int len) { register u_int i; register char *cp; register struct bsnamemem *tp; if (len == 0) return ("<empty>"); if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN) return (etheraddr_string(ndo, ep)); if (type == LINKADDR_FRELAY) return (q922_string(ndo, ep, len)); tp = lookup_bytestring(ndo, ep, len); if (tp->bs_name) return (tp->bs_name); tp->bs_name = cp = (char *)malloc(len*3); if (tp->bs_name == NULL) (*ndo->ndo_error)(ndo, "linkaddr_string: malloc"); *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; for (i = len-1; i > 0 ; --i) { *cp++ = ':'; *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; } *cp = '\0'; return (tp->bs_name); }
167,959
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct *desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; desc = get_desc(sel); if (!desc) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc->type & BIT(3))) return -EINVAL; switch ((desc->l << 1) | desc->d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: stable@vger.kernel.org Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; if (!get_desc(&desc, sel)) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc.type & BIT(3))) return -EINVAL; switch ((desc.l << 1) | desc.d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } }
169,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { std::string flags = command_line->GetSwitchValueASCII( switches::kDevToolsFlags); flags = net::EscapeQueryParamValue(flags, false); url_string += "&flags=" + flags; } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); } Commit Message: [DevTools] Move sanitize url to devtools_ui.cc. Compatibility script is not reliable enough. BUG=653134 Review-Url: https://codereview.chromium.org/2403633002 Cr-Commit-Position: refs/heads/master@{#425814} CWE ID: CWE-200
GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { url_string += "&" + command_line->GetSwitchValueASCII( switches::kDevToolsFlags); } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); }
172,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: chrand_principal_2_svc(chrand_arg *arg, struct svc_req *rqstp) { static chrand_ret ret; krb5_keyblock *k; int nkeys; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_chrand_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_randkey_principal"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ, FALSE, 0, NULL, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal((void *)handle, arg->princ, &k, &nkeys); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code == KADM5_OK) { ret.keys = k; ret.n_keys = nkeys; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
chrand_principal_2_svc(chrand_arg *arg, struct svc_req *rqstp) { static chrand_ret ret; krb5_keyblock *k; int nkeys; char *prime_arg, *funcname; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_chrand_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_randkey_principal"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ, FALSE, 0, NULL, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal((void *)handle, arg->princ, &k, &nkeys); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code == KADM5_OK) { ret.keys = k; ret.n_keys = nkeys; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionTtsSpeakCompletedFunction::RunImpl() { int request_id; std::string error_message; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id)); if (args_->GetSize() >= 2) EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &error_message)); ExtensionTtsController::GetInstance()->OnSpeechFinished( request_id, error_message); return true; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool ExtensionTtsSpeakCompletedFunction::RunImpl() { bool ExtensionTtsGetVoicesFunction::RunImpl() { result_.reset(ExtensionTtsController::GetInstance()->GetVoices(profile())); return true; }
170,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProcessControlLaunched() { base::ScopedAllowBlockingForTesting allow_blocking; base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); #if defined(OS_WIN) service_process_ = base::Process::OpenWithAccess(service_pid, SYNCHRONIZE | PROCESS_QUERY_INFORMATION); #else service_process_ = base::Process::Open(service_pid); #endif EXPECT_TRUE(service_process_.IsValid()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <wez@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
void ProcessControlLaunched() { void ProcessControlLaunched(base::OnceClosure on_done) { base::ScopedAllowBlockingForTesting allow_blocking; base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); #if defined(OS_WIN) service_process_ = base::Process::OpenWithAccess(service_pid, SYNCHRONIZE | PROCESS_QUERY_INFORMATION); #else service_process_ = base::Process::Open(service_pid); #endif EXPECT_TRUE(service_process_.IsValid()); std::move(on_done).Run(); }
172,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CronTab::initRegexObject() { if ( ! CronTab::regex.isInitialized() ) { const char *errptr; int erroffset; MyString pattern( CRONTAB_PARAMETER_PATTERN ) ; if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) { MyString error = "CronTab: Failed to compile Regex - "; error += pattern; EXCEPT( const_cast<char*>(error.Value())); } } } Commit Message: CWE ID: CWE-134
CronTab::initRegexObject() { if ( ! CronTab::regex.isInitialized() ) { const char *errptr; int erroffset; MyString pattern( CRONTAB_PARAMETER_PATTERN ) ; if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) { MyString error = "CronTab: Failed to compile Regex - "; error += pattern; EXCEPT( "%s", const_cast<char*>(error.Value()) ); } } }
165,383
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UserSelectionScreen::UpdateAndReturnUserListForMojo() { std::vector<ash::mojom::LoginUserInfoPtr> user_info_list; const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (user_manager::UserList::const_iterator it = users_to_send_.begin(); it != users_to_send_.end(); ++it) { const AccountId& account_id = (*it)->GetAccountId(); bool is_owner = owner == account_id; const bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(*it) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; ash::mojom::LoginUserInfoPtr login_user_info = ash::mojom::LoginUserInfo::New(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserMojoStruct(*it, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, login_user_info.get()); login_user_info->can_remove = CanRemoveUser(*it); if (is_public_account && LoginScreenClient::HasInstance()) { LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts( account_id, login_user_info->public_account_info->default_locale); } user_info_list.push_back(std::move(login_user_info)); } return user_info_list; } 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 <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
UserSelectionScreen::UpdateAndReturnUserListForMojo() { std::vector<ash::mojom::LoginUserInfoPtr> user_info_list; const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (const user_manager::User* user : users_to_send_) { const AccountId& account_id = user->GetAccountId(); bool is_owner = owner == account_id; const bool is_public_account = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(user) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; ash::mojom::LoginUserInfoPtr user_info = ash::mojom::LoginUserInfo::New(); user_info->basic_user_info = ash::mojom::UserInfo::New(); user_info->basic_user_info->type = user->GetType(); user_info->basic_user_info->account_id = user->GetAccountId(); user_info->basic_user_info->display_name = base::UTF16ToUTF8(user->GetDisplayName()); user_info->basic_user_info->display_email = user->display_email(); user_info->basic_user_info->avatar = BuildMojoUserAvatarForUser(user); user_info->auth_type = initial_auth_type; user_info->is_signed_in = user->is_logged_in(); user_info->is_device_owner = is_owner; user_info->can_remove = CanRemoveUser(user); user_info->allow_fingerprint_unlock = AllowFingerprintForUser(user); // Fill multi-profile data. if (!is_signin_to_add) { user_info->is_multiprofile_allowed = true; } else { GetMultiProfilePolicy(user, &user_info->is_multiprofile_allowed, &user_info->multiprofile_policy); } // Fill public session data. if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { user_info->public_account_info = ash::mojom::PublicAccountInfo::New(); std::string domain; if (GetEnterpriseDomain(&domain)) user_info->public_account_info->enterprise_domain = domain; const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; std::string selected_locale; bool has_multiple_locales; std::unique_ptr<base::ListValue> available_locales = GetPublicSessionLocales(public_session_recommended_locales, &selected_locale, &has_multiple_locales); DCHECK(available_locales); user_info->public_account_info->available_locales = lock_screen_utils::FromListValueToLocaleItem( std::move(available_locales)); user_info->public_account_info->default_locale = selected_locale; user_info->public_account_info->show_advanced_view = has_multiple_locales; } user_info->can_remove = CanRemoveUser(user); if (is_public_account && LoginScreenClient::HasInstance()) { LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts( account_id, user_info->public_account_info->default_locale); } user_info_list.push_back(std::move(user_info)); } return user_info_list; }
172,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); box->ops = &boxinfo->ops; if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jp2_box_create0())) { goto error; } if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: " "type=%c%s%c (0x%08x); length=%"PRIuFAST32"\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { JAS_DBGLOG(10, ("big length\n")); if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); box->ops = &boxinfo->ops; if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; }
168,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg) { void *choice; struct menu *m; int err; #ifdef CONFIG_CMD_BMP /* display BMP if available */ if (cfg->bmp) { if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) { run_command("cls", 0); bmp_display(image_load_addr, BMP_ALIGN_CENTER, BMP_ALIGN_CENTER); } else { printf("Skipping background bmp %s for failure\n", cfg->bmp); } } #endif m = pxe_menu_to_menu(cfg); if (!m) return; err = menu_get_choice(m, &choice); menu_destroy(m); /* * err == 1 means we got a choice back from menu_get_choice. * * err == -ENOENT if the menu was setup to select the default but no * default was set. in that case, we should continue trying to boot * labels that haven't been attempted yet. * * otherwise, the user interrupted or there was some other error and * we give up. */ if (err == 1) { err = label_boot(cmdtp, choice); if (!err) return; } else if (err != -ENOENT) { return; } boot_unattempted_labels(cmdtp, cfg); } 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
void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg) { void *choice; struct menu *m; int err; #ifdef CONFIG_CMD_BMP /* display BMP if available */ if (cfg->bmp) { if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) { if (CONFIG_IS_ENABLED(CMD_CLS)) run_command("cls", 0); bmp_display(image_load_addr, BMP_ALIGN_CENTER, BMP_ALIGN_CENTER); } else { printf("Skipping background bmp %s for failure\n", cfg->bmp); } } #endif m = pxe_menu_to_menu(cfg); if (!m) return; err = menu_get_choice(m, &choice); menu_destroy(m); /* * err == 1 means we got a choice back from menu_get_choice. * * err == -ENOENT if the menu was setup to select the default but no * default was set. in that case, we should continue trying to boot * labels that haven't been attempted yet. * * otherwise, the user interrupted or there was some other error and * we give up. */ if (err == 1) { err = label_boot(cmdtp, choice); if (!err) return; } else if (err != -ENOENT) { return; } boot_unattempted_labels(cmdtp, cfg); }
169,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnReusePreviewData(int preview_request_id) { base::StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier, ui_preview_request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnReusePreviewData(int preview_request_id) { base::FundamentalValue ui_identifier(id_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier, ui_preview_request_id); }
170,840
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) { TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram"); SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime"); api()->glLinkProgramFn(GetProgramServiceID(program, resources_)); ExitCommandProcessingEarly(); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) { TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram"); SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime"); GLuint program_service_id = GetProgramServiceID(program, resources_); api()->glLinkProgramFn(program_service_id); ExitCommandProcessingEarly(); linking_program_service_id_ = program_service_id; return error::kNoError; }
172,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, serial->len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); }
169,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool glfs_check_config(const char *cfgstring, char **reason) { char *path; glfs_t *fs = NULL; glfs_fd_t *gfd = NULL; gluster_server *hosts = NULL; /* gluster server defination */ bool result = true; path = strchr(cfgstring, '/'); if (!path) { if (asprintf(reason, "No path found") == -1) *reason = NULL; result = false; goto done; } path += 1; /* get past '/' */ fs = tcmu_create_glfs_object(path, &hosts); if (!fs) { tcmu_err("tcmu_create_glfs_object failed\n"); goto done; } gfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS); if (!gfd) { if (asprintf(reason, "glfs_open failed: %m") == -1) *reason = NULL; result = false; goto unref; } if (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) { if (asprintf(reason, "glfs_access file not present, or not writable") == -1) *reason = NULL; result = false; goto unref; } goto done; unref: gluster_cache_refresh(fs, path); done: if (gfd) glfs_close(gfd); gluster_free_server(&hosts); return result; } Commit Message: glfs: discard glfs_check_config Signed-off-by: Prasanna Kumar Kalever <prasanna.kalever@redhat.com> CWE ID: CWE-119
static bool glfs_check_config(const char *cfgstring, char **reason)
167,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = vt_verify_kbmode(fd); if (r == -EBUSY) { log_warning_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", name); return 0; } else if (r < 0) return log_warning_errno(r, "Failed to verify kbdmode on %s: %m", name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; }
169,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Display::Init() { m_string = NULL; m_language = NULL; m_country = NULL; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Display::Init()
174,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw) { PyObject *logical = NULL; /* input unicode or string object */ FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */ const char *encoding = "utf-8"; /* optional input string encoding */ int clean = 0; /* optional flag to clean the string */ int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/ static char *kwargs[] = { "logical", "base_direction", "encoding", "clean", "reordernsm", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kw, "O|isii", kwargs, &logical, &base, &encoding, &clean, &reordernsm)) return NULL; /* Validate base */ if (!(base == FRIBIDI_TYPE_RTL || base == FRIBIDI_TYPE_LTR || base == FRIBIDI_TYPE_ON)) return PyErr_Format (PyExc_ValueError, "invalid value %d: use either RTL, LTR or ON", base); /* Check object type and delegate to one of the log2vis functions */ if (PyUnicode_Check (logical)) return log2vis_unicode (logical, base, clean, reordernsm); else if (PyString_Check (logical)) return log2vis_encoded_string (logical, encoding, base, clean, reordernsm); else return PyErr_Format (PyExc_TypeError, "expected unicode or str, not %s", logical->ob_type->tp_name); } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119
_pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw) unicode_log2vis (PyUnicodeObject* string, FriBidiParType base_direction, int clean, int reordernsm) { int i; int length = string->length; FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyUnicodeObject *result = NULL; /* Allocate fribidi unicode buffers TODO - Don't copy strings if sizeof(FriBidiChar) == sizeof(Py_UNICODE) */ logical = PyMem_New (FriBidiChar, length + 1); if (logical == NULL) { PyErr_NoMemory(); goto cleanup; } visual = PyMem_New (FriBidiChar, length + 1); if (visual == NULL) { PyErr_NoMemory(); goto cleanup; } for (i=0; i<length; ++i) { logical[i] = string->str[i]; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); if (!fribidi_log2vis (logical, length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) { length = fribidi_remove_bidi_marks (visual, length, NULL, NULL, NULL); } result = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, length); if (result == NULL) { goto cleanup; } for (i=0; i<length; ++i) { result->str[i] = visual[i]; } cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); return (PyObject *)result; }
165,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lrmd_remote_listen(gpointer data) { int csock = 0; int flag = 0; unsigned laddr = 0; struct sockaddr addr; gnutls_session_t *session = NULL; crm_client_t *new_client = NULL; static struct mainloop_fd_callbacks lrmd_remote_fd_cb = { .dispatch = lrmd_remote_client_msg, .destroy = lrmd_remote_client_destroy, }; laddr = sizeof(addr); memset(&addr, 0, sizeof(addr)); getsockname(ssock, &addr, &laddr); /* accept the connection */ if (addr.sa_family == AF_INET6) { struct sockaddr_in6 sa; char addr_str[INET6_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } else { struct sockaddr_in sa; char addr_str[INET_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } if (csock == -1) { crm_err("accept socket failed"); return TRUE; } if ((flag = fcntl(csock, F_GETFL)) >= 0) { if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) { crm_err("fcntl() write failed"); close(csock); return TRUE; } } else { crm_err("fcntl() read failed"); close(csock); return TRUE; } session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s); if (session == NULL) { crm_err("TLS session creation failed"); close(csock); return TRUE; } new_client = calloc(1, sizeof(crm_client_t)); new_client->remote = calloc(1, sizeof(crm_remote_t)); new_client->kind = CRM_CLIENT_TLS; new_client->remote->tls_session = session; new_client->id = crm_generate_uuid(); new_client->remote->auth_timeout = g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client); crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id); new_client->remote->source = mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client, &lrmd_remote_fd_cb); g_hash_table_insert(client_connections, new_client->id, new_client); /* Alert other clients of the new connection */ notify_of_new_client(new_client); return TRUE; } Commit Message: Fix: remote: cl#5269 - Notify other clients of a new connection only if the handshake has completed (bsc#967388) CWE ID: CWE-254
lrmd_remote_listen(gpointer data) { int csock = 0; int flag = 0; unsigned laddr = 0; struct sockaddr addr; gnutls_session_t *session = NULL; crm_client_t *new_client = NULL; static struct mainloop_fd_callbacks lrmd_remote_fd_cb = { .dispatch = lrmd_remote_client_msg, .destroy = lrmd_remote_client_destroy, }; laddr = sizeof(addr); memset(&addr, 0, sizeof(addr)); getsockname(ssock, &addr, &laddr); /* accept the connection */ if (addr.sa_family == AF_INET6) { struct sockaddr_in6 sa; char addr_str[INET6_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } else { struct sockaddr_in sa; char addr_str[INET_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } if (csock == -1) { crm_err("accept socket failed"); return TRUE; } if ((flag = fcntl(csock, F_GETFL)) >= 0) { if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) { crm_err("fcntl() write failed"); close(csock); return TRUE; } } else { crm_err("fcntl() read failed"); close(csock); return TRUE; } session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s); if (session == NULL) { crm_err("TLS session creation failed"); close(csock); return TRUE; } new_client = calloc(1, sizeof(crm_client_t)); new_client->remote = calloc(1, sizeof(crm_remote_t)); new_client->kind = CRM_CLIENT_TLS; new_client->remote->tls_session = session; new_client->id = crm_generate_uuid(); new_client->remote->auth_timeout = g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client); crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id); new_client->remote->source = mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client, &lrmd_remote_fd_cb); g_hash_table_insert(client_connections, new_client->id, new_client); return TRUE; }
168,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t in_read(struct audio_stream_in *stream, void* buffer, size_t bytes) { struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream; int read; DEBUG("read %zu bytes, state: %d", bytes, in->common.state); if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED) { DEBUG("stream suspended"); return -1; } /* only allow autostarting if we are in stopped or standby */ if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) || (in->common.state == AUDIO_A2DP_STATE_STANDBY)) { pthread_mutex_lock(&in->common.lock); if (start_audio_datapath(&in->common) < 0) { /* emulate time this write represents to avoid very fast write failures during transition periods or remote suspend */ int us_delay = calc_audiotime(in->common.cfg, bytes); DEBUG("emulate a2dp read delay (%d us)", us_delay); usleep(us_delay); pthread_mutex_unlock(&in->common.lock); return -1; } pthread_mutex_unlock(&in->common.lock); } else if (in->common.state != AUDIO_A2DP_STATE_STARTED) { ERROR("stream not in stopped or standby"); return -1; } read = skt_read(in->common.audio_fd, buffer, bytes); if (read == -1) { skt_disconnect(in->common.audio_fd); in->common.audio_fd = AUDIO_SKT_DISCONNECTED; in->common.state = AUDIO_A2DP_STATE_STOPPED; } else if (read == 0) { DEBUG("read time out - return zeros"); memset(buffer, 0, bytes); read = bytes; } DEBUG("read %d bytes out of %zu bytes", read, bytes); return read; } 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
static ssize_t in_read(struct audio_stream_in *stream, void* buffer, size_t bytes) { struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream; int read; DEBUG("read %zu bytes, state: %d", bytes, in->common.state); if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED) { DEBUG("stream suspended"); return -1; } /* only allow autostarting if we are in stopped or standby */ if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) || (in->common.state == AUDIO_A2DP_STATE_STANDBY)) { pthread_mutex_lock(&in->common.lock); if (start_audio_datapath(&in->common) < 0) { /* emulate time this write represents to avoid very fast write failures during transition periods or remote suspend */ int us_delay = calc_audiotime(in->common.cfg, bytes); DEBUG("emulate a2dp read delay (%d us)", us_delay); TEMP_FAILURE_RETRY(usleep(us_delay)); pthread_mutex_unlock(&in->common.lock); return -1; } pthread_mutex_unlock(&in->common.lock); } else if (in->common.state != AUDIO_A2DP_STATE_STARTED) { ERROR("stream not in stopped or standby"); return -1; } read = skt_read(in->common.audio_fd, buffer, bytes); if (read == -1) { skt_disconnect(in->common.audio_fd); in->common.audio_fd = AUDIO_SKT_DISCONNECTED; in->common.state = AUDIO_A2DP_STATE_STOPPED; } else if (read == 0) { DEBUG("read time out - return zeros"); memset(buffer, 0, bytes); read = bytes; } DEBUG("read %d bytes out of %zu bytes", read, bytes); return read; }
173,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_part_of_packet(AVFormatContext *s, int64_t *pts, int *len, int *strid, int read_packet) { AVIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int syncword, streamid, reserved, flags, length, pts_flag; int64_t pva_pts = AV_NOPTS_VALUE, startpos; int ret; recover: startpos = avio_tell(pb); syncword = avio_rb16(pb); streamid = avio_r8(pb); avio_r8(pb); /* counter not used */ reserved = avio_r8(pb); flags = avio_r8(pb); length = avio_rb16(pb); pts_flag = flags & 0x10; if (syncword != PVA_MAGIC) { pva_log(s, AV_LOG_ERROR, "invalid syncword\n"); return AVERROR(EIO); } if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) { pva_log(s, AV_LOG_ERROR, "invalid streamid\n"); return AVERROR(EIO); } if (reserved != 0x55) { pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n"); } if (length > PVA_MAX_PAYLOAD_LENGTH) { pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length); return AVERROR(EIO); } if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) { pva_pts = avio_rb32(pb); length -= 4; } else if (streamid == PVA_AUDIO_PAYLOAD) { /* PVA Audio Packets either start with a signaled PES packet or * are a continuation of the previous PES packet. New PES packets * always start at the beginning of a PVA Packet, never somewhere in * the middle. */ if (!pvactx->continue_pes) { int pes_signal, pes_header_data_length, pes_packet_length, pes_flags; unsigned char pes_header_data[256]; pes_signal = avio_rb24(pb); avio_r8(pb); pes_packet_length = avio_rb16(pb); pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, " "trying to recover\n"); avio_skip(pb, length - 9); if (!read_packet) return AVERROR(EIO); goto recover; } ret = avio_read(pb, pes_header_data, pes_header_data_length); if (ret != pes_header_data_length) return ret < 0 ? ret : AVERROR_INVALIDDATA; length -= 9 + pes_header_data_length; pes_packet_length -= 3 + pes_header_data_length; pvactx->continue_pes = pes_packet_length; if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) { if (pes_header_data_length < 5) { pva_log(s, AV_LOG_ERROR, "header too short\n"); avio_skip(pb, length); return AVERROR_INVALIDDATA; } pva_pts = ff_parse_pes_pts(pes_header_data); } } pvactx->continue_pes -= length; if (pvactx->continue_pes < 0) { pva_log(s, AV_LOG_WARNING, "audio data corruption\n"); pvactx->continue_pes = 0; } } if (pva_pts != AV_NOPTS_VALUE) av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME); *pts = pva_pts; *len = length; *strid = streamid; return 0; } Commit Message: avformat/pva: Check for EOF before retrying in read_part_of_packet() Fixes: Infinite loop Fixes: pva-4b1835dbc2027bf3c567005dcc78e85199240d06 Found-by: Paul Ch <paulcher@icloud.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-835
static int read_part_of_packet(AVFormatContext *s, int64_t *pts, int *len, int *strid, int read_packet) { AVIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int syncword, streamid, reserved, flags, length, pts_flag; int64_t pva_pts = AV_NOPTS_VALUE, startpos; int ret; recover: startpos = avio_tell(pb); syncword = avio_rb16(pb); streamid = avio_r8(pb); avio_r8(pb); /* counter not used */ reserved = avio_r8(pb); flags = avio_r8(pb); length = avio_rb16(pb); pts_flag = flags & 0x10; if (syncword != PVA_MAGIC) { pva_log(s, AV_LOG_ERROR, "invalid syncword\n"); return AVERROR(EIO); } if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) { pva_log(s, AV_LOG_ERROR, "invalid streamid\n"); return AVERROR(EIO); } if (reserved != 0x55) { pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n"); } if (length > PVA_MAX_PAYLOAD_LENGTH) { pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length); return AVERROR(EIO); } if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) { pva_pts = avio_rb32(pb); length -= 4; } else if (streamid == PVA_AUDIO_PAYLOAD) { /* PVA Audio Packets either start with a signaled PES packet or * are a continuation of the previous PES packet. New PES packets * always start at the beginning of a PVA Packet, never somewhere in * the middle. */ if (!pvactx->continue_pes) { int pes_signal, pes_header_data_length, pes_packet_length, pes_flags; unsigned char pes_header_data[256]; pes_signal = avio_rb24(pb); avio_r8(pb); pes_packet_length = avio_rb16(pb); pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); if (avio_feof(pb)) { return AVERROR_EOF; } if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, " "trying to recover\n"); avio_skip(pb, length - 9); if (!read_packet) return AVERROR(EIO); goto recover; } ret = avio_read(pb, pes_header_data, pes_header_data_length); if (ret != pes_header_data_length) return ret < 0 ? ret : AVERROR_INVALIDDATA; length -= 9 + pes_header_data_length; pes_packet_length -= 3 + pes_header_data_length; pvactx->continue_pes = pes_packet_length; if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) { if (pes_header_data_length < 5) { pva_log(s, AV_LOG_ERROR, "header too short\n"); avio_skip(pb, length); return AVERROR_INVALIDDATA; } pva_pts = ff_parse_pes_pts(pes_header_data); } } pvactx->continue_pes -= length; if (pvactx->continue_pes < 0) { pva_log(s, AV_LOG_WARNING, "audio data corruption\n"); pvactx->continue_pes = 0; } } if (pva_pts != AV_NOPTS_VALUE) av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME); *pts = pva_pts; *len = length; *strid = streamid; return 0; }
168,925
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t snd_timer_user_read(struct file *file, char __user *buffer, size_t count, loff_t *offset) { struct snd_timer_user *tu; long result = 0, unit; int qhead; int err = 0; tu = file->private_data; unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read); spin_lock_irq(&tu->qlock); while ((long)count - result >= unit) { while (!tu->qused) { wait_queue_t wait; if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) { err = -EAGAIN; goto _error; } set_current_state(TASK_INTERRUPTIBLE); init_waitqueue_entry(&wait, current); add_wait_queue(&tu->qchange_sleep, &wait); spin_unlock_irq(&tu->qlock); schedule(); spin_lock_irq(&tu->qlock); remove_wait_queue(&tu->qchange_sleep, &wait); if (tu->disconnected) { err = -ENODEV; goto _error; } if (signal_pending(current)) { err = -ERESTARTSYS; goto _error; } } qhead = tu->qhead++; tu->qhead %= tu->queue_size; tu->qused--; spin_unlock_irq(&tu->qlock); mutex_lock(&tu->ioctl_lock); if (tu->tread) { if (copy_to_user(buffer, &tu->tqueue[qhead], sizeof(struct snd_timer_tread))) err = -EFAULT; } else { if (copy_to_user(buffer, &tu->queue[qhead], sizeof(struct snd_timer_read))) err = -EFAULT; } mutex_unlock(&tu->ioctl_lock); spin_lock_irq(&tu->qlock); if (err < 0) goto _error; result += unit; buffer += unit; } _error: spin_unlock_irq(&tu->qlock); return result > 0 ? result : err; } Commit Message: ALSA: timer: Fix race between read and ioctl The read from ALSA timer device, the function snd_timer_user_tread(), may access to an uninitialized struct snd_timer_user fields when the read is concurrently performed while the ioctl like snd_timer_user_tselect() is invoked. We have already fixed the races among ioctls via a mutex, but we seem to have forgotten the race between read vs ioctl. This patch simply applies (more exactly extends the already applied range of) tu->ioctl_lock in snd_timer_user_tread() for closing the race window. Reported-by: Alexander Potapenko <glider@google.com> Tested-by: Alexander Potapenko <glider@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-200
static ssize_t snd_timer_user_read(struct file *file, char __user *buffer, size_t count, loff_t *offset) { struct snd_timer_user *tu; long result = 0, unit; int qhead; int err = 0; tu = file->private_data; unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read); mutex_lock(&tu->ioctl_lock); spin_lock_irq(&tu->qlock); while ((long)count - result >= unit) { while (!tu->qused) { wait_queue_t wait; if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) { err = -EAGAIN; goto _error; } set_current_state(TASK_INTERRUPTIBLE); init_waitqueue_entry(&wait, current); add_wait_queue(&tu->qchange_sleep, &wait); spin_unlock_irq(&tu->qlock); mutex_unlock(&tu->ioctl_lock); schedule(); mutex_lock(&tu->ioctl_lock); spin_lock_irq(&tu->qlock); remove_wait_queue(&tu->qchange_sleep, &wait); if (tu->disconnected) { err = -ENODEV; goto _error; } if (signal_pending(current)) { err = -ERESTARTSYS; goto _error; } } qhead = tu->qhead++; tu->qhead %= tu->queue_size; tu->qused--; spin_unlock_irq(&tu->qlock); if (tu->tread) { if (copy_to_user(buffer, &tu->tqueue[qhead], sizeof(struct snd_timer_tread))) err = -EFAULT; } else { if (copy_to_user(buffer, &tu->queue[qhead], sizeof(struct snd_timer_read))) err = -EFAULT; } spin_lock_irq(&tu->qlock); if (err < 0) goto _error; result += unit; buffer += unit; } _error: spin_unlock_irq(&tu->qlock); mutex_unlock(&tu->ioctl_lock); return result > 0 ? result : err; }
170,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); } 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
void qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); }
169,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MaybeStartInputMethodDaemon(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList && !value.string_list_value.empty()) { if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) { return; } const bool just_started = StartInputMethodDaemon(); if (!just_started) { return; } if (tentative_current_input_method_id_.empty()) { tentative_current_input_method_id_ = current_input_method_.id; } if (std::find(value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_) == value.string_list_value.end()) { tentative_current_input_method_id_.clear(); } } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeStartInputMethodDaemon(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == input_method::ImeConfigValue::kValueTypeStringList && !value.string_list_value.empty()) { if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) { return; } const bool just_started = StartInputMethodDaemon(); if (!just_started) { return; } if (tentative_current_input_method_id_.empty()) { tentative_current_input_method_id_ = current_input_method_.id; } if (std::find(value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_) == value.string_list_value.end()) { tentative_current_input_method_id_.clear(); } } }
170,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void numtostr(js_State *J, const char *fmt, int w, double n) { char buf[32], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); } Commit Message: Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed(). 32 is not enough to fit sprintf("%.20f", 1e20). We need at least 43 bytes to fit that format. Bump the static buffer size. CWE ID: CWE-119
static void numtostr(js_State *J, const char *fmt, int w, double n) { /* buf needs to fit printf("%.20f", 1e20) */ char buf[50], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); }
169,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } Commit Message: * tools/tiffcp.c: fix uint32 underflow/overflow that can cause heap-based buffer overflow. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2610 CWE ID: CWE-190
cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int64 inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } }
168,533
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SProcXResQueryResourceBytes (ClientPtr client) { REQUEST(xXResQueryResourceBytesReq); int c; xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff)); int c; xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff)); swapl(&stuff->numSpecs); REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq); REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq, stuff->numSpecs * sizeof(specs[0])); } Commit Message: CWE ID: CWE-20
SProcXResQueryResourceBytes (ClientPtr client) { REQUEST(xXResQueryResourceBytesReq); int c; xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff)); int c; xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff)); REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq); swapl(&stuff->numSpecs); REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq, stuff->numSpecs * sizeof(specs[0])); }
165,435
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateObject( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_Object; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_CreateObject( void )
167,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s) { static const char module[] = "NeXTDecode"; unsigned char *bp, *op; tmsize_t cc; uint8* row; tmsize_t scanline, n; (void) s; /* * Each scanline is assumed to start off as all * white (we assume a PhotometricInterpretation * of ``min-is-black''). */ for (op = (unsigned char*) buf, cc = occ; cc-- > 0;) *op++ = 0xff; bp = (unsigned char *)tif->tif_rawcp; cc = tif->tif_rawcc; scanline = tif->tif_scanlinesize; if (occ % scanline) { TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read"); return (0); } for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) { n = *bp++, cc--; switch (n) { case LITERALROW: /* * The entire scanline is given as literal values. */ if (cc < scanline) goto bad; _TIFFmemcpy(row, bp, scanline); bp += scanline; cc -= scanline; break; case LITERALSPAN: { tmsize_t off; /* * The scanline has a literal span that begins at some * offset. */ if( cc < 4 ) goto bad; off = (bp[0] * 256) + bp[1]; n = (bp[2] * 256) + bp[3]; if (cc < 4+n || off+n > scanline) goto bad; _TIFFmemcpy(row+off, bp+4, n); bp += 4+n; cc -= 4+n; break; } default: { uint32 npixels = 0, grey; uint32 imagewidth = tif->tif_dir.td_imagewidth; if( isTiled(tif) ) imagewidth = tif->tif_dir.td_tilewidth; /* * The scanline is composed of a sequence of constant * color ``runs''. We shift into ``run mode'' and * interpret bytes as codes of the form * <color><npixels> until we've filled the scanline. */ op = row; for (;;) { grey = (uint32)((n>>6) & 0x3); n &= 0x3f; /* * Ensure the run does not exceed the scanline * bounds, potentially resulting in a security * issue. */ while (n-- > 0 && npixels < imagewidth) SETPIXEL(op, grey); if (npixels >= imagewidth) break; if (cc == 0) goto bad; n = *bp++, cc--; } break; } } } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld", (long) tif->tif_row); return (0); } Commit Message: * libtiff/tif_next.c: fix potential out-of-bound write in NeXTDecode() triggered by http://lcamtuf.coredump.cx/afl/vulns/libtiff5.tif (bugzilla #2508) CWE ID: CWE-119
NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s) { static const char module[] = "NeXTDecode"; unsigned char *bp, *op; tmsize_t cc; uint8* row; tmsize_t scanline, n; (void) s; /* * Each scanline is assumed to start off as all * white (we assume a PhotometricInterpretation * of ``min-is-black''). */ for (op = (unsigned char*) buf, cc = occ; cc-- > 0;) *op++ = 0xff; bp = (unsigned char *)tif->tif_rawcp; cc = tif->tif_rawcc; scanline = tif->tif_scanlinesize; if (occ % scanline) { TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read"); return (0); } for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) { n = *bp++, cc--; switch (n) { case LITERALROW: /* * The entire scanline is given as literal values. */ if (cc < scanline) goto bad; _TIFFmemcpy(row, bp, scanline); bp += scanline; cc -= scanline; break; case LITERALSPAN: { tmsize_t off; /* * The scanline has a literal span that begins at some * offset. */ if( cc < 4 ) goto bad; off = (bp[0] * 256) + bp[1]; n = (bp[2] * 256) + bp[3]; if (cc < 4+n || off+n > scanline) goto bad; _TIFFmemcpy(row+off, bp+4, n); bp += 4+n; cc -= 4+n; break; } default: { uint32 npixels = 0, grey; uint32 imagewidth = tif->tif_dir.td_imagewidth; if( isTiled(tif) ) imagewidth = tif->tif_dir.td_tilewidth; tmsize_t op_offset = 0; /* * The scanline is composed of a sequence of constant * color ``runs''. We shift into ``run mode'' and * interpret bytes as codes of the form * <color><npixels> until we've filled the scanline. */ op = row; for (;;) { grey = (uint32)((n>>6) & 0x3); n &= 0x3f; /* * Ensure the run does not exceed the scanline * bounds, potentially resulting in a security * issue. */ while (n-- > 0 && npixels < imagewidth && op_offset < scanline) SETPIXEL(op, grey); if (npixels >= imagewidth) break; if (op_offset >= scanline ) { TIFFErrorExt(tif->tif_clientdata, module, "Invalid data for scanline %ld", (long) tif->tif_row); return (0); } if (cc == 0) goto bad; n = *bp++, cc--; } break; } } } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld", (long) tif->tif_row); return (0); }
167,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mdecrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt * , &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mdecrypt_generic(pm->td, data_s, data_size); RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mdecrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt * , &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; if (data_size <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Integer overflow in data size"); RETURN_FALSE; } data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mdecrypt_generic(pm->td, data_s, data_size); RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); }
167,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: atm_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t llchdr; u_int hdrlen = 0; if (caplen < 1 || length < 1) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* Cisco Style NLPID ? */ if (*p == LLC_UI) { if (ndo->ndo_eflag) ND_PRINT((ndo, "CNLPID ")); isoclns_print(ndo, p + 1, length - 1, caplen - 1); return hdrlen; } /* * Must have at least a DSAP, an SSAP, and the first byte of the * control field. */ if (caplen < 3 || length < 3) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* * Extract the presumed LLC header into a variable, for quick * testing. * Then check for a header that's neither a header for a SNAP * packet nor an RFC 2684 routed NLPID-formatted PDU nor * an 802.2-but-no-SNAP IP packet. */ llchdr = EXTRACT_24BITS(p); if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) && llchdr != LLC_UI_HDR(LLCSAP_ISONS) && llchdr != LLC_UI_HDR(LLCSAP_IP)) { /* * XXX - assume 802.6 MAC header from Fore driver. * * Unfortunately, the above list doesn't check for * all known SAPs, doesn't check for headers where * the source and destination SAP aren't the same, * and doesn't check for non-UI frames. It also * runs the risk of an 802.6 MAC header that happens * to begin with one of those values being * incorrectly treated as an 802.2 header. * * So is that Fore driver still around? And, if so, * is it still putting 802.6 MAC headers on ATM * packets? If so, could it be changed to use a * new DLT_IEEE802_6 value if we added it? */ if (caplen < 20 || length < 20) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%08x%08x %08x%08x ", EXTRACT_32BITS(p), EXTRACT_32BITS(p+4), EXTRACT_32BITS(p+8), EXTRACT_32BITS(p+12))); p += 20; length -= 20; caplen -= 20; hdrlen += 20; } hdrlen += atm_llc_print(ndo, p, length, caplen); return (hdrlen); } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
atm_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t llchdr; u_int hdrlen = 0; if (caplen < 1 || length < 1) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* Cisco Style NLPID ? */ if (*p == LLC_UI) { if (ndo->ndo_eflag) ND_PRINT((ndo, "CNLPID ")); isoclns_print(ndo, p + 1, length - 1); return hdrlen; } /* * Must have at least a DSAP, an SSAP, and the first byte of the * control field. */ if (caplen < 3 || length < 3) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* * Extract the presumed LLC header into a variable, for quick * testing. * Then check for a header that's neither a header for a SNAP * packet nor an RFC 2684 routed NLPID-formatted PDU nor * an 802.2-but-no-SNAP IP packet. */ llchdr = EXTRACT_24BITS(p); if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) && llchdr != LLC_UI_HDR(LLCSAP_ISONS) && llchdr != LLC_UI_HDR(LLCSAP_IP)) { /* * XXX - assume 802.6 MAC header from Fore driver. * * Unfortunately, the above list doesn't check for * all known SAPs, doesn't check for headers where * the source and destination SAP aren't the same, * and doesn't check for non-UI frames. It also * runs the risk of an 802.6 MAC header that happens * to begin with one of those values being * incorrectly treated as an 802.2 header. * * So is that Fore driver still around? And, if so, * is it still putting 802.6 MAC headers on ATM * packets? If so, could it be changed to use a * new DLT_IEEE802_6 value if we added it? */ if (caplen < 20 || length < 20) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%08x%08x %08x%08x ", EXTRACT_32BITS(p), EXTRACT_32BITS(p+4), EXTRACT_32BITS(p+8), EXTRACT_32BITS(p+12))); p += 20; length -= 20; caplen -= 20; hdrlen += 20; } hdrlen += atm_llc_print(ndo, p, length, caplen); return (hdrlen); }
167,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_bearer_cap_print(netdissect_options *ndo, const u_char *dat) { const uint32_t *ptr = (const uint32_t *)dat; if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_ANALOG_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_DIGITAL_MASK) { ND_PRINT((ndo, "D")); } } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_bearer_cap_print(netdissect_options *ndo, const u_char *dat) l2tp_bearer_cap_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint32_t *ptr = (const uint32_t *)dat; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_ANALOG_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_BEARER_CAP_DIGITAL_MASK) { ND_PRINT((ndo, "D")); } }
167,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) { { base::AutoLock auto_lock(gpu_info_lock_); if (!gpu_info_.Merge(gpu_info)) return; RunGpuInfoUpdateCallbacks(); content::GetContentClient()->SetGpuInfo(gpu_info_); } UpdateGpuFeatureFlags(); } Commit Message: Fix a lock re-entry bug in GpuDataManager::UpdateGpuInfo. The issue is that the registered callbacks could request GPUInfo, so they could re-enter the lock. Therefore, we should release the lock before we run through callbacks. BUG=84805 TEST=the issue in 84805 is gone. Review URL: http://codereview.chromium.org/7054063 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87898 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) { { base::AutoLock auto_lock(gpu_info_lock_); if (!gpu_info_.Merge(gpu_info)) return; } RunGpuInfoUpdateCallbacks(); { base::AutoLock auto_lock(gpu_info_lock_); content::GetContentClient()->SetGpuInfo(gpu_info_); } UpdateGpuFeatureFlags(); }
170,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */
167,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; return session->internals.handshake_header_buffer.packet_length; } ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; } Commit Message: CWE ID: CWE-189
_gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; if (*recv_type != type) { gnutls_assert (); _gnutls_handshake_log ("HSK[%x]: Handshake type mismatch (under attack?)\n", session); return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET; } return session->internals.handshake_header_buffer.packet_length; } ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; }
165,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PPVarToNPVariant(PP_Var var, NPVariant* result) { switch (var.type) { case PP_VARTYPE_UNDEFINED: VOID_TO_NPVARIANT(*result); break; case PP_VARTYPE_NULL: NULL_TO_NPVARIANT(*result); break; case PP_VARTYPE_BOOL: BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); break; case PP_VARTYPE_INT32: INT32_TO_NPVARIANT(var.value.as_int, *result); break; case PP_VARTYPE_DOUBLE: DOUBLE_TO_NPVARIANT(var.value.as_double, *result); break; case PP_VARTYPE_STRING: { scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); if (!string) { VOID_TO_NPVARIANT(*result); return false; } const std::string& value = string->value(); STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result); break; } case PP_VARTYPE_OBJECT: { scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); if (!object) { VOID_TO_NPVARIANT(*result); return false; } OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), *result); break; } case PP_VARTYPE_ARRAY: case PP_VARTYPE_DICTIONARY: VOID_TO_NPVARIANT(*result); break; } return true; } Commit Message: Fix invalid read in ppapi code BUG=77493 TEST=attached test Review URL: http://codereview.chromium.org/6883059 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@82172 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool PPVarToNPVariant(PP_Var var, NPVariant* result) { switch (var.type) { case PP_VARTYPE_UNDEFINED: VOID_TO_NPVARIANT(*result); break; case PP_VARTYPE_NULL: NULL_TO_NPVARIANT(*result); break; case PP_VARTYPE_BOOL: BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); break; case PP_VARTYPE_INT32: INT32_TO_NPVARIANT(var.value.as_int, *result); break; case PP_VARTYPE_DOUBLE: DOUBLE_TO_NPVARIANT(var.value.as_double, *result); break; case PP_VARTYPE_STRING: { scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); if (!string) { VOID_TO_NPVARIANT(*result); return false; } const std::string& value = string->value(); char* c_string = static_cast<char*>(malloc(value.size())); memcpy(c_string, value.data(), value.size()); STRINGN_TO_NPVARIANT(c_string, value.size(), *result); break; } case PP_VARTYPE_OBJECT: { scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); if (!object) { VOID_TO_NPVARIANT(*result); return false; } OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), *result); break; } case PP_VARTYPE_ARRAY: case PP_VARTYPE_DICTIONARY: VOID_TO_NPVARIANT(*result); break; } return true; }
170,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void * gdImageGifPtr (gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); gdImageGifCtx (im, out); rv = gdDPExtractData (out, size); out->gd_free (out); return rv; } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415
void * gdImageGifPtr (gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); if (!_gdImageGifCtx(im, out)) { rv = gdDPExtractData(out, size); } else { rv = NULL; } out->gd_free (out); return rv; }
169,734
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppShortcutManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSIONS_READY: { OnceOffCreateShortcuts(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: { #if defined(OS_MACOSX) if (!apps::IsAppShimsEnabled()) break; #endif // defined(OS_MACOSX) const extensions::InstalledExtensionInfo* installed_info = content::Details<const extensions::InstalledExtensionInfo>(details) .ptr(); const Extension* extension = installed_info->extension; if (installed_info->is_update) { web_app::UpdateAllShortcuts( base::UTF8ToUTF16(installed_info->old_name), profile_, extension); } else if (ShouldCreateShortcutFor(profile_, extension)) { CreateShortcutsInApplicationsMenu(profile_, extension); } break; } case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: { const Extension* extension = content::Details<const Extension>( details).ptr(); web_app::DeleteAllShortcuts(profile_, extension); break; } default: NOTREACHED(); } } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppShortcutManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSIONS_READY: { OnceOffCreateShortcuts(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: { const extensions::InstalledExtensionInfo* installed_info = content::Details<const extensions::InstalledExtensionInfo>(details) .ptr(); const Extension* extension = installed_info->extension; if (installed_info->is_update) { web_app::UpdateAllShortcuts( base::UTF8ToUTF16(installed_info->old_name), profile_, extension); } else if (ShouldCreateShortcutFor(profile_, extension)) { CreateShortcutsInApplicationsMenu(profile_, extension); } break; } case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: { const Extension* extension = content::Details<const Extension>( details).ptr(); web_app::DeleteAllShortcuts(profile_, extension); break; } default: NOTREACHED(); } }
171,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; if (cnt < 0) { jas_deprecated("negative count for jas_stream_write"); } bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; }
168,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int mk_vhost_fdt_open(int id, unsigned int hash, struct session_request *sr) { int i; int fd; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return open(sr->real_path.data, sr->file_info.flags_read_only); } ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return open(sr->real_path.data, sr->file_info.flags_read_only); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and return the shared FD */ hc->readers++; return hc->fd; } /* * Get here means that no entry exists in the hash table for the * requested file descriptor and hash, we must try to open the file * and register the entry in the table. */ fd = open(sr->real_path.data, sr->file_info.flags_read_only); if (fd == -1) { return -1; } /* If chains are full, just return the new FD, bad luck... */ if (ht->av_slots <= 0) { return fd; } /* Register the new entry in an available slot */ for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) { hc = &ht->chain[i]; if (hc->fd == -1) { hc->fd = fd; hc->hash = hash; hc->readers++; ht->av_slots--; sr->vhost_fdt_id = id; sr->vhost_fdt_hash = hash; return fd; } } return -1; } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <mattd@bugfuzz.com> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <eduardo@monkey.io> CWE ID: CWE-20
static inline int mk_vhost_fdt_open(int id, unsigned int hash, struct session_request *sr) { int i; int fd; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return open(sr->real_path.data, sr->file_info.flags_read_only); } ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return open(sr->real_path.data, sr->file_info.flags_read_only); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and return the shared FD */ hc->readers++; return hc->fd; } /* * Get here means that no entry exists in the hash table for the * requested file descriptor and hash, we must try to open the file * and register the entry in the table. */ fd = open(sr->real_path.data, sr->file_info.flags_read_only); if (fd == -1) { return -1; } /* If chains are full, just return the new FD, bad luck... */ if (ht->av_slots <= 0) { return fd; } /* Register the new entry in an available slot */ for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) { hc = &ht->chain[i]; if (hc->fd == -1) { hc->fd = fd; hc->hash = hash; hc->readers++; ht->av_slots--; sr->vhost_fdt_id = id; sr->vhost_fdt_hash = hash; sr->fd_is_fdt = MK_TRUE; return fd; } } return -1; }
166,279
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <jfilak@redhat.com> CWE ID: CWE-200
char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; }
170,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); } 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
virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); }
171,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VarianceTest<VarianceFunctionType>::OneQuarterTest() { memset(src_, 255, block_size_); const int half = block_size_ / 2; memset(ref_, 255, half); memset(ref_ + half, 0, half); unsigned int sse; unsigned int var; REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void VarianceTest<VarianceFunctionType>::OneQuarterTest() { const int half = block_size_ / 2; if (!use_high_bit_depth_) { memset(src_, 255, block_size_); memset(ref_, 255, half); memset(ref_ + half, 0, half); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(src_), 255 << (bit_depth_ - 8), block_size_); vpx_memset16(CONVERT_TO_SHORTPTR(ref_), 255 << (bit_depth_ - 8), half); vpx_memset16(CONVERT_TO_SHORTPTR(ref_) + half, 0, half); #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse; unsigned int var; ASM_REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); }
174,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */ { const char *p, *q; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); p = val; while (p < endptr) { zval **tmp; q = p; while (*q != PS_DELIMITER) { if (++q >= endptr) goto break_outer_loop; } if (p[0] == PS_UNDEF_MARKER) { p++; has_value = 0; } else { has_value = 1; } namelen = q - p; name = estrndup(p, namelen); q++; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { goto skip; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { var_push_dtor_no_addref(&var_hash, &current); efree(name); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); skip: efree(name); p = q; } break_outer_loop: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */ Commit Message: Fix bug #72681 - consume data even if we're not storing them CWE ID: CWE-74
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */ { const char *p, *q; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; int skip = 0; PHP_VAR_UNSERIALIZE_INIT(var_hash); p = val; while (p < endptr) { zval **tmp; q = p; skip = 0; while (*q != PS_DELIMITER) { if (++q >= endptr) goto break_outer_loop; } if (p[0] == PS_UNDEF_MARKER) { p++; has_value = 0; } else { has_value = 1; } namelen = q - p; name = estrndup(p, namelen); q++; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { skip = 1; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { if (!skip) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } } else { var_push_dtor_no_addref(&var_hash, &current); efree(name); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } if (!skip) { PS_ADD_VARL(name, namelen); } skip: efree(name); p = q; } break_outer_loop: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */
166,959
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: deinterlace_row(png_bytep buffer, png_const_bytep row, unsigned int pixel_size, png_uint_32 w, int pass) { /* The inverse of the above, 'row' is part of row 'y' of the output image, * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute * the pixels of row into buffer and return the number written (to allow * this to be checked). */ png_uint_32 xin, xout, xstep; xout = PNG_PASS_START_COL(pass); xstep = 1U<<PNG_PASS_COL_SHIFT(pass); for (xin=0; xout<w; xout+=xstep) { pixel_copy(buffer, xout, row, xin, pixel_size); ++xin; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
deinterlace_row(png_bytep buffer, png_const_bytep row,
173,607
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ResourceTracker::UnrefResource(PP_Resource res) { DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE)) << res << " is not a PP_Resource."; ResourceMap::iterator i = live_resources_.find(res); if (i != live_resources_.end()) { if (!--i->second.second) { Resource* to_release = i->second.first; PP_Instance instance = to_release->instance()->pp_instance(); to_release->LastPluginRefWasDeleted(false); instance_map_[instance]->resources.erase(res); live_resources_.erase(i); } return true; } else { return false; } } 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
bool ResourceTracker::UnrefResource(PP_Resource res) { DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE)) << res << " is not a PP_Resource."; ResourceMap::iterator i = live_resources_.find(res); if (i != live_resources_.end()) { if (!--i->second.second) { Resource* to_release = i->second.first; PP_Instance instance = to_release->instance()->pp_instance(); to_release->LastPluginRefWasDeleted(); instance_map_[instance]->ref_resources.erase(res); live_resources_.erase(i); } return true; } else { return false; } }
170,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GM2TabStyle::PaintInactiveTabBackground(gfx::Canvas* canvas, const SkPath& clip) const { bool has_custom_image; int fill_id = tab_->controller()->GetBackgroundResourceId(&has_custom_image); if (!has_custom_image) fill_id = 0; PaintTabBackground(canvas, false /* active */, fill_id, 0, tab_->controller()->MaySetClip() ? &clip : nullptr); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
void GM2TabStyle::PaintInactiveTabBackground(gfx::Canvas* canvas, const SkPath& clip) const { bool has_custom_image; int fill_id = tab_->controller()->GetBackgroundResourceId(&has_custom_image); if (!has_custom_image) fill_id = 0; PaintTabBackground(canvas, TAB_INACTIVE, fill_id, 0, tab_->controller()->MaySetClip() ? &clip : nullptr); }
172,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *pool_strdup(const char *s) { char *r = pool_alloc(strlen(s) + 1); strcpy(r, s); return r; } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-119
static char *pool_strdup(const char *s) { size_t len = strlen(s) + 1; char *r = pool_alloc(len); memcpy(r, s, len); return r; }
167,428
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: test_js (void) { GString *result = g_string_new(""); /* simple javascript can be evaluated and returned */ parse_cmd_line("js ('x' + 345).toUpperCase()", result); g_assert_cmpstr("X345", ==, result->str); /* uzbl commands can be run from javascript */ uzbl.net.useragent = "Test useragent"; parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result); g_assert_cmpstr("TEST USERAGENT", ==, result->str); g_string_free(result, TRUE); } Commit Message: disable Uzbl javascript object because of security problem. CWE ID: CWE-264
test_js (void) { GString *result = g_string_new(""); /* simple javascript can be evaluated and returned */ parse_cmd_line("js ('x' + 345).toUpperCase()", result); g_assert_cmpstr("X345", ==, result->str); g_string_free(result, TRUE); }
165,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebView* RenderViewImpl::createView( WebFrame* creator, const WebURLRequest& request, const WebWindowFeatures& features, const WebString& frame_name, WebNavigationPolicy policy) { if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups) return NULL; ViewHostMsg_CreateWindow_Params params; params.opener_id = routing_id_; params.user_gesture = creator->isProcessingUserGesture(); params.window_container_type = WindowFeaturesToContainerType(features); params.session_storage_namespace_id = session_storage_namespace_id_; params.frame_name = frame_name; params.opener_frame_id = creator->identifier(); params.opener_url = creator->document().url(); params.opener_security_origin = creator->document().securityOrigin().toString().utf8(); params.opener_suppressed = creator->willSuppressOpenerInNewFrame(); params.disposition = NavigationPolicyToDisposition(policy); if (!request.isNull()) params.target_url = request.url(); int32 routing_id = MSG_ROUTING_NONE; int32 surface_id = 0; int64 cloned_session_storage_namespace_id; RenderThread::Get()->Send( new ViewHostMsg_CreateWindow(params, &routing_id, &surface_id, &cloned_session_storage_namespace_id)); if (routing_id == MSG_ROUTING_NONE) return NULL; creator->consumeUserGesture(); RenderViewImpl* view = RenderViewImpl::Create( routing_id_, renderer_preferences_, webkit_preferences_, shared_popup_counter_, routing_id, surface_id, cloned_session_storage_namespace_id, frame_name, true, false, 1, screen_info_, accessibility_mode_); view->opened_by_user_gesture_ = params.user_gesture; view->opener_suppressed_ = params.opener_suppressed; view->alternate_error_page_url_ = alternate_error_page_url_; return view->webview(); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
WebView* RenderViewImpl::createView( WebFrame* creator, const WebURLRequest& request, const WebWindowFeatures& features, const WebString& frame_name, WebNavigationPolicy policy) { if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups) return NULL; ViewHostMsg_CreateWindow_Params params; params.opener_id = routing_id_; params.user_gesture = creator->isProcessingUserGesture(); params.window_container_type = WindowFeaturesToContainerType(features); params.session_storage_namespace_id = session_storage_namespace_id_; params.frame_name = frame_name; params.opener_frame_id = creator->identifier(); params.opener_url = creator->document().url(); GURL security_url(creator->document().securityOrigin().toString().utf8()); if (!security_url.is_valid()) security_url = GURL(); params.opener_security_origin = security_url; params.opener_suppressed = creator->willSuppressOpenerInNewFrame(); params.disposition = NavigationPolicyToDisposition(policy); if (!request.isNull()) params.target_url = request.url(); int32 routing_id = MSG_ROUTING_NONE; int32 surface_id = 0; int64 cloned_session_storage_namespace_id; RenderThread::Get()->Send( new ViewHostMsg_CreateWindow(params, &routing_id, &surface_id, &cloned_session_storage_namespace_id)); if (routing_id == MSG_ROUTING_NONE) return NULL; creator->consumeUserGesture(); RenderViewImpl* view = RenderViewImpl::Create( routing_id_, renderer_preferences_, webkit_preferences_, shared_popup_counter_, routing_id, surface_id, cloned_session_storage_namespace_id, frame_name, true, false, 1, screen_info_, accessibility_mode_); view->opened_by_user_gesture_ = params.user_gesture; view->opener_suppressed_ = params.opener_suppressed; view->alternate_error_page_url_ = alternate_error_page_url_; return view->webview(); }
171,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } Commit Message: Security: fix Lua struct package offset handling. After the first fix to the struct package I found another similar problem, which is fixed by this patch. It could be reproduced easily by running the following script: return struct.unpack('f', "xxxxxxxxxxxxx",-3) The above will access bytes before the 'data' pointer. CWE ID: CWE-190
static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; }
169,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: __ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
__ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; }
166,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void close_all_sockets(atransport* t) { asocket* s; /* this is a little gross, but since s->close() *will* modify ** the list out from under you, your options are limited. */ adb_mutex_lock(&socket_list_lock); restart: for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->transport == t || (s->peer && s->peer->transport == t)) { local_socket_close_locked(s); goto restart; } } adb_mutex_unlock(&socket_list_lock); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
void close_all_sockets(atransport* t) { asocket* s; /* this is a little gross, but since s->close() *will* modify ** the list out from under you, your options are limited. */ std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); restart: for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->transport == t || (s->peer && s->peer->transport == t)) { local_socket_close(s); goto restart; } } }
174,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void edge_bulk_in_callback(struct urb *urb) { struct edgeport_port *edge_port = urb->context; struct device *dev = &edge_port->port->dev; unsigned char *data = urb->transfer_buffer; int retval = 0; int port_number; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status); } if (status == -EPIPE) goto exit; if (status) { dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__); return; } port_number = edge_port->port->port_number; if (edge_port->lsr_event) { edge_port->lsr_event = 0; dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n", __func__, port_number, edge_port->lsr_mask, *data); handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data); /* Adjust buffer length/pointer */ --urb->actual_length; ++data; } if (urb->actual_length) { usb_serial_debug_data(dev, __func__, urb->actual_length, data); if (edge_port->close_pending) dev_dbg(dev, "%s - close pending, dropping data on the floor\n", __func__); else edge_tty_recv(edge_port->port, data, urb->actual_length); edge_port->port->icount.rx += urb->actual_length; } exit: /* continue read unless stopped */ spin_lock(&edge_port->ep_lock); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) retval = usb_submit_urb(urb, GFP_ATOMIC); else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED; spin_unlock(&edge_port->ep_lock); if (retval) dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } Commit Message: USB: serial: io_ti: fix information leak in completion handler Add missing sanity check to the bulk-in completion handler to avoid an integer underflow that can be triggered by a malicious device. This avoids leaking 128 kB of memory content from after the URB transfer buffer to user space. Fixes: 8c209e6782ca ("USB: make actual_length in struct urb field u32") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <stable@vger.kernel.org> # 2.6.30 Signed-off-by: Johan Hovold <johan@kernel.org> CWE ID: CWE-191
static void edge_bulk_in_callback(struct urb *urb) { struct edgeport_port *edge_port = urb->context; struct device *dev = &edge_port->port->dev; unsigned char *data = urb->transfer_buffer; int retval = 0; int port_number; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status); } if (status == -EPIPE) goto exit; if (status) { dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__); return; } port_number = edge_port->port->port_number; if (urb->actual_length > 0 && edge_port->lsr_event) { edge_port->lsr_event = 0; dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n", __func__, port_number, edge_port->lsr_mask, *data); handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data); /* Adjust buffer length/pointer */ --urb->actual_length; ++data; } if (urb->actual_length) { usb_serial_debug_data(dev, __func__, urb->actual_length, data); if (edge_port->close_pending) dev_dbg(dev, "%s - close pending, dropping data on the floor\n", __func__); else edge_tty_recv(edge_port->port, data, urb->actual_length); edge_port->port->icount.rx += urb->actual_length; } exit: /* continue read unless stopped */ spin_lock(&edge_port->ep_lock); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) retval = usb_submit_urb(urb, GFP_ATOMIC); else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED; spin_unlock(&edge_port->ep_lock); if (retval) dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); }
168,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cxusb_ctrl_msg(struct dvb_usb_device *d, u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen) { struct cxusb_state *st = d->priv; int ret, wo; if (1 + wlen > MAX_XFER_SIZE) { warn("i2c wr: len=%d is too big!\n", wlen); return -EOPNOTSUPP; } wo = (rbuf == NULL || rlen == 0); /* write-only */ mutex_lock(&d->data_mutex); st->data[0] = cmd; memcpy(&st->data[1], wbuf, wlen); if (wo) ret = dvb_usb_generic_write(d, st->data, 1 + wlen); else ret = dvb_usb_generic_rw(d, st->data, 1 + wlen, rbuf, rlen, 0); mutex_unlock(&d->data_mutex); return ret; } Commit Message: [media] cxusb: Use a dma capable buffer also for reading Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack") added a kmalloc'ed bounce buffer for writes, but missed to do the same for reads. As the read only happens after the write is finished, we can reuse the same buffer. As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling it using the dvb_usb_generic_read wrapper function. Signed-off-by: Stefan Brüns <stefan.bruens@rwth-aachen.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com> CWE ID: CWE-119
static int cxusb_ctrl_msg(struct dvb_usb_device *d, u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen) { struct cxusb_state *st = d->priv; int ret; if (1 + wlen > MAX_XFER_SIZE) { warn("i2c wr: len=%d is too big!\n", wlen); return -EOPNOTSUPP; } if (rlen > MAX_XFER_SIZE) { warn("i2c rd: len=%d is too big!\n", rlen); return -EOPNOTSUPP; } mutex_lock(&d->data_mutex); st->data[0] = cmd; memcpy(&st->data[1], wbuf, wlen); ret = dvb_usb_generic_rw(d, st->data, 1 + wlen, st->data, rlen, 0); if (!ret && rbuf && rlen) memcpy(rbuf, st->data, rlen); mutex_unlock(&d->data_mutex); return ret; }
168,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync( Blob* blob) { loader_->Start(blob->GetBlobDataHandle()); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync( void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync(Blob* blob) { loader_->Start(blob->GetBlobDataHandle()); }
173,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas, bool active, SkColor stroke_color) const { SkPath outer_path = GetPath(TabStyle::PathType::kBorder, canvas->image_scale(), active); gfx::ScopedCanvas scoped_canvas(canvas); float scale = canvas->UndoDeviceScaleFactor(); cc::PaintFlags flags; flags.setAntiAlias(true); flags.setColor(stroke_color); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(GetStrokeThickness(active) * scale); canvas->DrawPath(outer_path, flags); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas, TabState active_state, SkColor stroke_color) const { SkPath outer_path = GetPath(TabStyle::PathType::kBorder, canvas->image_scale(), active_state == TAB_ACTIVE); gfx::ScopedCanvas scoped_canvas(canvas); float scale = canvas->UndoDeviceScaleFactor(); cc::PaintFlags flags; flags.setAntiAlias(true); flags.setColor(stroke_color); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(GetStrokeThickness(active_state == TAB_ACTIVE) * scale); canvas->DrawPath(outer_path, flags); }
172,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *s, *t, c; int i, proto; const void *se; if (length <= 0) return; b = (uint8_t *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = (u_char *)p, t = b, i = length; i > 0; i--) { c = *s++; if (c == 0x7d) { if (i > 1) { i--; c = *s++ ^ 0x20; } else continue; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); } Commit Message: Do bounds checking when unescaping PPP. Clean up a const issue while we're at it. CWE ID: CWE-119
ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *t, c; const u_char *s; int i, proto; const void *se; if (length <= 0) return; b = (u_char *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { c = *s++; if (c == 0x7d) { if (i <= 1 || !ND_TTEST(*s)) break; i--; c = *s++ ^ 0x20; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); }
166,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, *value = NULL, **tmp; if (check_inherited && intern->fptr_offset_has) { zval *offset_tmp = offset; SEPARATE_ARG_IF_REF(offset_tmp); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp); zval_ptr_dtor(&offset_tmp); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); if (check_empty != 1) { return 1; } else if (intern->fptr_offset_get) { value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC); } } else { if (rv) { zval_ptr_dtor(&rv); } return 0; } } if (!value) { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { if (check_empty == 2) { return 1; } } else { return 0; } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { if (check_empty == 2) { return 1; } } else { return 0; } break; default: zend_error(E_WARNING, "Illegal offset type"); return 0; } if (check_empty && check_inherited && intern->fptr_offset_get) { value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC); } else { value = *tmp; } } return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL; } /* }}} */ Commit Message: Fix bug #73029 - Missing type check when unserializing SplArray CWE ID: CWE-20
static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, *value = NULL, **tmp; if (check_inherited && intern->fptr_offset_has) { zval *offset_tmp = offset; SEPARATE_ARG_IF_REF(offset_tmp); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp); zval_ptr_dtor(&offset_tmp); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); if (check_empty != 1) { return 1; } else if (intern->fptr_offset_get) { value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC); } } else { if (rv) { zval_ptr_dtor(&rv); } return 0; } } if (!value) { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { if (check_empty == 2) { return 1; } } else { return 0; } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { if (check_empty == 2) { return 1; } } else { return 0; } break; default: zend_error(E_WARNING, "Illegal offset type"); return 0; } if (check_empty && check_inherited && intern->fptr_offset_get) { value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC); } else { value = *tmp; } } return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL; } /* }}} */
166,932