instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DownloadUrlParameters::DownloadUrlParameters( const GURL& url, int render_process_host_id, int render_view_host_routing_id, int render_frame_host_routing_id, const net::NetworkTrafficAnnotationTag& traffic_annotation) : content_initiated_(false), use_if_range_(true), method_("GET"), post_id_(-1), prefer_cache_(false), referrer_policy_( net::URLRequest:: CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE), render_process_host_id_(render_process_host_id), render_view_host_routing_id_(render_view_host_routing_id), render_frame_host_routing_id_(render_frame_host_routing_id), url_(url), do_not_prompt_for_login_(false), follow_cross_origin_redirects_(true), fetch_error_body_(false), transient_(false), traffic_annotation_(traffic_annotation), download_source_(DownloadSource::UNKNOWN) {} Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
DownloadUrlParameters::DownloadUrlParameters( const GURL& url, int render_process_host_id, int render_view_host_routing_id, int render_frame_host_routing_id, const net::NetworkTrafficAnnotationTag& traffic_annotation) : content_initiated_(false), use_if_range_(true), method_("GET"), post_id_(-1), prefer_cache_(false), referrer_policy_( net::URLRequest:: CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE), render_process_host_id_(render_process_host_id), render_view_host_routing_id_(render_view_host_routing_id), render_frame_host_routing_id_(render_frame_host_routing_id), frame_tree_node_id_(-1), url_(url), do_not_prompt_for_login_(false), follow_cross_origin_redirects_(true), fetch_error_body_(false), transient_(false), traffic_annotation_(traffic_annotation), download_source_(DownloadSource::UNKNOWN) {}
173,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothOptionsHandler::DeviceNotification( const DictionaryValue& device) { web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", device); } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::DeviceNotification( void BluetoothOptionsHandler::SendDeviceNotification( chromeos::BluetoothDevice* device, base::DictionaryValue* params) { // Retrieve properties of the bluetooth device. The properties names are // in title case. Convert to camel case in accordance with our Javascript // naming convention. const DictionaryValue& properties = device->AsDictionary(); base::DictionaryValue js_properties; for (DictionaryValue::key_iterator it = properties.begin_keys(); it != properties.end_keys(); ++it) { base::Value* child = NULL; properties.GetWithoutPathExpansion(*it, &child); if (child) { std::string js_key = *it; js_key[0] = tolower(js_key[0]); js_properties.SetWithoutPathExpansion(js_key, child->DeepCopy()); } } if (params) { js_properties.MergeDictionary(params); } web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", js_properties); }
170,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, long long size_) { const long long stop = start_ + size_; long long pos = start_; m_track = -1; m_pos = -1; m_block = 1; // default while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x77) // CueTrack ID m_track = UnserializeUInt(pReader, pos, size); else if (id == 0x71) // CueClusterPos ID m_pos = UnserializeUInt(pReader, pos, size); else if (id == 0x1378) // CueBlockNumber m_block = UnserializeUInt(pReader, pos, size); pos += size; // consume payload assert(pos <= stop); } assert(m_pos >= 0); assert(m_track > 0); } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, bool CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, long long size_) { const long long stop = start_ + size_; long long pos = start_; m_track = -1; m_pos = -1; m_block = 1; // default while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if ((id < 0) || ((pos + len) > stop)) { return false; } pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); if ((size < 0) || ((pos + len) > stop)) { return false; } pos += len; // consume Size field if ((pos + size) > stop) { return false; } if (id == 0x77) // CueTrack ID m_track = UnserializeUInt(pReader, pos, size); else if (id == 0x71) // CueClusterPos ID m_pos = UnserializeUInt(pReader, pos, size); else if (id == 0x1378) // CueBlockNumber m_block = UnserializeUInt(pReader, pos, size); pos += size; // consume payload } if ((m_pos < 0) || (m_track <= 0)) { return false; } return true; }
173,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov, struct sockaddr_storage *kern_address, int mode) { int tot_len; if (kern_msg->msg_namelen) { if (mode == VERIFY_READ) { int err = move_addr_to_kernel(kern_msg->msg_name, kern_msg->msg_namelen, kern_address); if (err < 0) return err; } kern_msg->msg_name = kern_address; } else kern_msg->msg_name = NULL; tot_len = iov_from_user_compat_to_kern(kern_iov, (struct compat_iovec __user *)kern_msg->msg_iov, kern_msg->msg_iovlen); if (tot_len >= 0) kern_msg->msg_iov = kern_iov; return tot_len; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov, struct sockaddr_storage *kern_address, int mode) { int tot_len; if (kern_msg->msg_namelen) { if (mode == VERIFY_READ) { int err = move_addr_to_kernel(kern_msg->msg_name, kern_msg->msg_namelen, kern_address); if (err < 0) return err; } if (kern_msg->msg_name) kern_msg->msg_name = kern_address; } else kern_msg->msg_name = NULL; tot_len = iov_from_user_compat_to_kern(kern_iov, (struct compat_iovec __user *)kern_msg->msg_iov, kern_msg->msg_iovlen); if (tot_len >= 0) kern_msg->msg_iov = kern_iov; return tot_len; }
166,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_tsquery(char *buf, PushFunction pushval, Datum opaque, bool isplain) { struct TSQueryParserStateData state; int i; TSQuery query; int commonlen; QueryItem *ptr; ListCell *cell; /* init state */ state.buffer = buf; state.buf = buf; state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND; state.count = 0; state.polstr = NIL; /* init value parser's state */ state.valstate = init_tsvector_parser(state.buffer, true, true); /* init list of operand */ state.sumlen = 0; state.lenop = 64; state.curop = state.op = (char *) palloc(state.lenop); *(state.curop) = '\0'; /* parse query & make polish notation (postfix, but in reverse order) */ makepol(&state, pushval, opaque); close_tsvector_parser(state.valstate); if (list_length(state.polstr) == 0) { ereport(NOTICE, (errmsg("text-search query doesn't contain lexemes: \"%s\"", state.buffer))); query = (TSQuery) palloc(HDRSIZETQ); SET_VARSIZE(query, HDRSIZETQ); query->size = 0; return query; } /* Pack the QueryItems in the final TSQuery struct to return to caller */ commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen); query = (TSQuery) palloc0(commonlen); SET_VARSIZE(query, commonlen); query->size = list_length(state.polstr); ptr = GETQUERY(query); /* Copy QueryItems to TSQuery */ i = 0; foreach(cell, state.polstr) { QueryItem *item = (QueryItem *) lfirst(cell); switch (item->type) { case QI_VAL: memcpy(&ptr[i], item, sizeof(QueryOperand)); break; case QI_VALSTOP: ptr[i].type = QI_VALSTOP; break; case QI_OPR: memcpy(&ptr[i], item, sizeof(QueryOperator)); break; default: elog(ERROR, "unrecognized QueryItem type: %d", item->type); } i++; } /* Copy all the operand strings to TSQuery */ memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen); pfree(state.op); /* Set left operand pointers for every operator. */ findoprnd(ptr, query->size); return query; } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
parse_tsquery(char *buf, PushFunction pushval, Datum opaque, bool isplain) { struct TSQueryParserStateData state; int i; TSQuery query; int commonlen; QueryItem *ptr; ListCell *cell; /* init state */ state.buffer = buf; state.buf = buf; state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND; state.count = 0; state.polstr = NIL; /* init value parser's state */ state.valstate = init_tsvector_parser(state.buffer, true, true); /* init list of operand */ state.sumlen = 0; state.lenop = 64; state.curop = state.op = (char *) palloc(state.lenop); *(state.curop) = '\0'; /* parse query & make polish notation (postfix, but in reverse order) */ makepol(&state, pushval, opaque); close_tsvector_parser(state.valstate); if (list_length(state.polstr) == 0) { ereport(NOTICE, (errmsg("text-search query doesn't contain lexemes: \"%s\"", state.buffer))); query = (TSQuery) palloc(HDRSIZETQ); SET_VARSIZE(query, HDRSIZETQ); query->size = 0; return query; } if (TSQUERY_TOO_BIG(list_length(state.polstr), state.sumlen)) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("tsquery is too large"))); commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen); /* Pack the QueryItems in the final TSQuery struct to return to caller */ query = (TSQuery) palloc0(commonlen); SET_VARSIZE(query, commonlen); query->size = list_length(state.polstr); ptr = GETQUERY(query); /* Copy QueryItems to TSQuery */ i = 0; foreach(cell, state.polstr) { QueryItem *item = (QueryItem *) lfirst(cell); switch (item->type) { case QI_VAL: memcpy(&ptr[i], item, sizeof(QueryOperand)); break; case QI_VALSTOP: ptr[i].type = QI_VALSTOP; break; case QI_OPR: memcpy(&ptr[i], item, sizeof(QueryOperator)); break; default: elog(ERROR, "unrecognized QueryItem type: %d", item->type); } i++; } /* Copy all the operand strings to TSQuery */ memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen); pfree(state.op); /* Set left operand pointers for every operator. */ findoprnd(ptr, query->size); return query; }
166,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int CLASS ljpeg_start (struct jhead *jh, int info_only) { int c, tag, len; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; fread (data, 2, 1, ifp); if (data[1] != 0xd8) return 0; do { fread (data, 2, 2, ifp); tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc0: jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: if (info_only) break; for (dp = data; dp < data+len && (c = *dp++) < 4; ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (info_only) return 1; FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } Commit Message: Avoid overflow in ljpeg_start(). CWE ID: CWE-189
int CLASS ljpeg_start (struct jhead *jh, int info_only) { int c, tag; ushort len; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; fread (data, 2, 1, ifp); if (data[1] != 0xd8) return 0; do { fread (data, 2, 2, ifp); tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc0: jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: if (info_only) break; for (dp = data; dp < data+len && (c = *dp++) < 4; ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (info_only) return 1; FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; }
166,622
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr; struct net *net = sock_net(sk); int ret; int chk_addr_ret; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr_len < sizeof(struct sockaddr_l2tpip)) return -EINVAL; if (addr->l2tp_family != AF_INET) return -EINVAL; ret = -EADDRINUSE; read_lock_bh(&l2tp_ip_lock); if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip_lock); lock_sock(sk); if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip)) goto out; chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr); ret = -EADDRNOTAVAIL; if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; if (addr->l2tp_addr.s_addr) inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->inet_saddr = 0; /* Use device */ sk_dst_reset(sk); l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip_lock); sk_add_bind_node(sk, &l2tp_ip_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); ret = 0; sock_reset_flag(sk, SOCK_ZAPPED); out: release_sock(sk); return ret; out_in_use: read_unlock_bh(&l2tp_ip_lock); return ret; } Commit Message: l2tp: fix racy SOCK_ZAPPED flag check in l2tp_ip{,6}_bind() Lock socket before checking the SOCK_ZAPPED flag in l2tp_ip6_bind(). Without lock, a concurrent call could modify the socket flags between the sock_flag(sk, SOCK_ZAPPED) test and the lock_sock() call. This way, a socket could be inserted twice in l2tp_ip6_bind_table. Releasing it would then leave a stale pointer there, generating use-after-free errors when walking through the list or modifying adjacent entries. BUG: KASAN: use-after-free in l2tp_ip6_close+0x22e/0x290 at addr ffff8800081b0ed8 Write of size 8 by task syz-executor/10987 CPU: 0 PID: 10987 Comm: syz-executor Not tainted 4.8.0+ #39 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014 ffff880031d97838 ffffffff829f835b ffff88001b5a1640 ffff8800081b0ec0 ffff8800081b15a0 ffff8800081b6d20 ffff880031d97860 ffffffff8174d3cc ffff880031d978f0 ffff8800081b0e80 ffff88001b5a1640 ffff880031d978e0 Call Trace: [<ffffffff829f835b>] dump_stack+0xb3/0x118 lib/dump_stack.c:15 [<ffffffff8174d3cc>] kasan_object_err+0x1c/0x70 mm/kasan/report.c:156 [< inline >] print_address_description mm/kasan/report.c:194 [<ffffffff8174d666>] kasan_report_error+0x1f6/0x4d0 mm/kasan/report.c:283 [< inline >] kasan_report mm/kasan/report.c:303 [<ffffffff8174db7e>] __asan_report_store8_noabort+0x3e/0x40 mm/kasan/report.c:329 [< inline >] __write_once_size ./include/linux/compiler.h:249 [< inline >] __hlist_del ./include/linux/list.h:622 [< inline >] hlist_del_init ./include/linux/list.h:637 [<ffffffff8579047e>] l2tp_ip6_close+0x22e/0x290 net/l2tp/l2tp_ip6.c:239 [<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415 [<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422 [<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570 [<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017 [<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208 [<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244 [<ffffffff813774f9>] task_work_run+0xf9/0x170 [<ffffffff81324aae>] do_exit+0x85e/0x2a00 [<ffffffff81326dc8>] do_group_exit+0x108/0x330 [<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307 [<ffffffff811b49af>] do_signal+0x7f/0x18f0 [<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156 [< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190 [<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259 [<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6 Object at ffff8800081b0ec0, in cache L2TP/IPv6 size: 1448 Allocated: PID = 10987 [ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20 [ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0 [ 1116.897025] [<ffffffff8174c9ad>] kasan_kmalloc+0xad/0xe0 [ 1116.897025] [<ffffffff8174cee2>] kasan_slab_alloc+0x12/0x20 [ 1116.897025] [< inline >] slab_post_alloc_hook mm/slab.h:417 [ 1116.897025] [< inline >] slab_alloc_node mm/slub.c:2708 [ 1116.897025] [< inline >] slab_alloc mm/slub.c:2716 [ 1116.897025] [<ffffffff817476a8>] kmem_cache_alloc+0xc8/0x2b0 mm/slub.c:2721 [ 1116.897025] [<ffffffff84c4f6a9>] sk_prot_alloc+0x69/0x2b0 net/core/sock.c:1326 [ 1116.897025] [<ffffffff84c58ac8>] sk_alloc+0x38/0xae0 net/core/sock.c:1388 [ 1116.897025] [<ffffffff851ddf67>] inet6_create+0x2d7/0x1000 net/ipv6/af_inet6.c:182 [ 1116.897025] [<ffffffff84c4af7b>] __sock_create+0x37b/0x640 net/socket.c:1153 [ 1116.897025] [< inline >] sock_create net/socket.c:1193 [ 1116.897025] [< inline >] SYSC_socket net/socket.c:1223 [ 1116.897025] [<ffffffff84c4b46f>] SyS_socket+0xef/0x1b0 net/socket.c:1203 [ 1116.897025] [<ffffffff85e4d685>] entry_SYSCALL_64_fastpath+0x23/0xc6 Freed: PID = 10987 [ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20 [ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0 [ 1116.897025] [<ffffffff8174cf61>] kasan_slab_free+0x71/0xb0 [ 1116.897025] [< inline >] slab_free_hook mm/slub.c:1352 [ 1116.897025] [< inline >] slab_free_freelist_hook mm/slub.c:1374 [ 1116.897025] [< inline >] slab_free mm/slub.c:2951 [ 1116.897025] [<ffffffff81748b28>] kmem_cache_free+0xc8/0x330 mm/slub.c:2973 [ 1116.897025] [< inline >] sk_prot_free net/core/sock.c:1369 [ 1116.897025] [<ffffffff84c541eb>] __sk_destruct+0x32b/0x4f0 net/core/sock.c:1444 [ 1116.897025] [<ffffffff84c5aca4>] sk_destruct+0x44/0x80 net/core/sock.c:1452 [ 1116.897025] [<ffffffff84c5ad33>] __sk_free+0x53/0x220 net/core/sock.c:1460 [ 1116.897025] [<ffffffff84c5af23>] sk_free+0x23/0x30 net/core/sock.c:1471 [ 1116.897025] [<ffffffff84c5cb6c>] sk_common_release+0x28c/0x3e0 ./include/net/sock.h:1589 [ 1116.897025] [<ffffffff8579044e>] l2tp_ip6_close+0x1fe/0x290 net/l2tp/l2tp_ip6.c:243 [ 1116.897025] [<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415 [ 1116.897025] [<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422 [ 1116.897025] [<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570 [ 1116.897025] [<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017 [ 1116.897025] [<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208 [ 1116.897025] [<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244 [ 1116.897025] [<ffffffff813774f9>] task_work_run+0xf9/0x170 [ 1116.897025] [<ffffffff81324aae>] do_exit+0x85e/0x2a00 [ 1116.897025] [<ffffffff81326dc8>] do_group_exit+0x108/0x330 [ 1116.897025] [<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307 [ 1116.897025] [<ffffffff811b49af>] do_signal+0x7f/0x18f0 [ 1116.897025] [<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156 [ 1116.897025] [< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190 [ 1116.897025] [<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259 [ 1116.897025] [<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6 Memory state around the buggy address: ffff8800081b0d80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ffff8800081b0e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc >ffff8800081b0e80: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb ^ ffff8800081b0f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8800081b0f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== The same issue exists with l2tp_ip_bind() and l2tp_ip_bind_table. Fixes: c51ce49735c1 ("l2tp: fix oops in L2TP IP sockets for connect() AF_UNSPEC case") Reported-by: Baozeng Ding <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Baozeng Ding <[email protected]> Signed-off-by: Guillaume Nault <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr; struct net *net = sock_net(sk); int ret; int chk_addr_ret; if (addr_len < sizeof(struct sockaddr_l2tpip)) return -EINVAL; if (addr->l2tp_family != AF_INET) return -EINVAL; ret = -EADDRINUSE; read_lock_bh(&l2tp_ip_lock); if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip_lock); lock_sock(sk); if (!sock_flag(sk, SOCK_ZAPPED)) goto out; if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip)) goto out; chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr); ret = -EADDRNOTAVAIL; if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; if (addr->l2tp_addr.s_addr) inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->inet_saddr = 0; /* Use device */ sk_dst_reset(sk); l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip_lock); sk_add_bind_node(sk, &l2tp_ip_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); ret = 0; sock_reset_flag(sk, SOCK_ZAPPED); out: release_sock(sk); return ret; out_in_use: read_unlock_bh(&l2tp_ip_lock); return ret; }
168,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: handle_associated_event(struct cpu_hw_events *cpuc, int idx, struct perf_sample_data *data, struct pt_regs *regs) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc = &event->hw; mipspmu_event_update(event, hwc, idx); data->period = event->hw.last_period; if (!mipspmu_event_set_period(event, hwc, idx)) return; if (perf_event_overflow(event, 0, data, regs)) mipspmu->disable_event(idx); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
handle_associated_event(struct cpu_hw_events *cpuc, int idx, struct perf_sample_data *data, struct pt_regs *regs) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc = &event->hw; mipspmu_event_update(event, hwc, idx); data->period = event->hw.last_period; if (!mipspmu_event_set_period(event, hwc, idx)) return; if (perf_event_overflow(event, data, regs)) mipspmu->disable_event(idx); }
165,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void WriteProfile(j_compress_ptr jpeg_info,Image *image) { const char *name; const StringInfo *profile; MagickBooleanType iptc; register ssize_t i; size_t length, tag_length; StringInfo *custom_profile; /* Save image profile as a APP marker. */ iptc=MagickFalse; custom_profile=AcquireStringInfo(65535L); ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { register unsigned char *p; profile=GetImageProfile(image,name); p=GetStringInfoDatum(custom_profile); if (LocaleCompare(name,"EXIF") == 0) for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65533L) { length=MagickMin(GetStringInfoLength(profile)-i,65533L); jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile)+i, (unsigned int) length); } if (LocaleCompare(name,"ICC") == 0) { register unsigned char *p; tag_length=strlen(ICC_PROFILE); p=GetStringInfoDatum(custom_profile); (void) CopyMagickMemory(p,ICC_PROFILE,tag_length); p[tag_length]='\0'; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L) { length=MagickMin(GetStringInfoLength(profile)-i,65519L); p[12]=(unsigned char) ((i/65519L)+1); p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1); (void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i, length); jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum( custom_profile),(unsigned int) (length+tag_length+3)); } } if (((LocaleCompare(name,"IPTC") == 0) || (LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse)) { size_t roundup; iptc=MagickTrue; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L) { length=MagickMin(GetStringInfoLength(profile)-i,65500L); roundup=(size_t) (length & 0x01); if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0) { (void) memcpy(p,"Photoshop 3.0 ",14); tag_length=14; } else { (void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24); tag_length=26; p[24]=(unsigned char) (length >> 8); p[25]=(unsigned char) (length & 0xff); } p[13]=0x00; (void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length); if (roundup != 0) p[length+tag_length]='\0'; jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum( custom_profile),(unsigned int) (length+tag_length+roundup)); } } if (LocaleCompare(name,"XMP") == 0) { StringInfo *xmp_profile; /* Add namespace to XMP profile. */ xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ "); if (xmp_profile != (StringInfo *) NULL) { if (profile != (StringInfo *) NULL) ConcatenateStringInfo(xmp_profile,profile); GetStringInfoDatum(xmp_profile)[28]='\0'; for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L) { length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L); jpeg_write_marker(jpeg_info,XML_MARKER, GetStringInfoDatum(xmp_profile)+i,(unsigned int) length); } xmp_profile=DestroyStringInfo(xmp_profile); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), "%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile)); name=GetNextImageProfile(image); } custom_profile=DestroyStringInfo(custom_profile); } Commit Message: Changed the JPEG writer to raise a warning when the exif profile exceeds 65533 bytes and truncate it. CWE ID: CWE-119
static void WriteProfile(j_compress_ptr jpeg_info,Image *image) { const char *name; const StringInfo *profile; MagickBooleanType iptc; register ssize_t i; size_t length, tag_length; StringInfo *custom_profile; /* Save image profile as a APP marker. */ iptc=MagickFalse; custom_profile=AcquireStringInfo(65535L); ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { register unsigned char *p; profile=GetImageProfile(image,name); p=GetStringInfoDatum(custom_profile); if (LocaleCompare(name,"EXIF") == 0) { length=GetStringInfoLength(profile); if (length > 65533L) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderWarning,"ExifProfileSizeExceedsLimit",image->filename); length=65533L; } jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile), (unsigned int) length); } if (LocaleCompare(name,"ICC") == 0) { register unsigned char *p; tag_length=strlen(ICC_PROFILE); p=GetStringInfoDatum(custom_profile); (void) CopyMagickMemory(p,ICC_PROFILE,tag_length); p[tag_length]='\0'; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L) { length=MagickMin(GetStringInfoLength(profile)-i,65519L); p[12]=(unsigned char) ((i/65519L)+1); p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1); (void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i, length); jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum( custom_profile),(unsigned int) (length+tag_length+3)); } } if (((LocaleCompare(name,"IPTC") == 0) || (LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse)) { size_t roundup; iptc=MagickTrue; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L) { length=MagickMin(GetStringInfoLength(profile)-i,65500L); roundup=(size_t) (length & 0x01); if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0) { (void) memcpy(p,"Photoshop 3.0 ",14); tag_length=14; } else { (void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24); tag_length=26; p[24]=(unsigned char) (length >> 8); p[25]=(unsigned char) (length & 0xff); } p[13]=0x00; (void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length); if (roundup != 0) p[length+tag_length]='\0'; jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum( custom_profile),(unsigned int) (length+tag_length+roundup)); } } if (LocaleCompare(name,"XMP") == 0) { StringInfo *xmp_profile; /* Add namespace to XMP profile. */ xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ "); if (xmp_profile != (StringInfo *) NULL) { if (profile != (StringInfo *) NULL) ConcatenateStringInfo(xmp_profile,profile); GetStringInfoDatum(xmp_profile)[28]='\0'; for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L) { length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L); jpeg_write_marker(jpeg_info,XML_MARKER, GetStringInfoDatum(xmp_profile)+i,(unsigned int) length); } xmp_profile=DestroyStringInfo(xmp_profile); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), "%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile)); name=GetNextImageProfile(image); } custom_profile=DestroyStringInfo(custom_profile); }
168,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId(); if (view_) view_->DidNavigate(); viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId(); if (old_surface_id == new_surface_id) return; } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <[email protected]> Reviewed-by: ccameron <[email protected]> Commit-Queue: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#586913} CWE ID: CWE-20
void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; if (view_) view_->DidNavigate(); } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); }
172,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DownloadCoreServiceImpl::GetDownloadManagerDelegate() { DownloadManager* manager = BrowserContext::GetDownloadManager(profile_); if (download_manager_created_) { DCHECK(static_cast<DownloadManagerDelegate*>(manager_delegate_.get()) == manager->GetDelegate()); return manager_delegate_.get(); } download_manager_created_ = true; if (!manager_delegate_.get()) manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_)); manager_delegate_->SetDownloadManager(manager); #if BUILDFLAG(ENABLE_EXTENSIONS) extension_event_router_.reset( new extensions::ExtensionDownloadsEventRouter(profile_, manager)); #endif if (!profile_->IsOffTheRecord()) { history::HistoryService* history = HistoryServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); history->GetNextDownloadId( manager_delegate_->GetDownloadIdReceiverCallback()); download_history_.reset(new DownloadHistory( manager, std::unique_ptr<DownloadHistory::HistoryAdapter>( new DownloadHistory::HistoryAdapter(history)))); } download_ui_.reset(new DownloadUIController( manager, std::unique_ptr<DownloadUIController::Delegate>())); g_browser_process->download_status_updater()->AddManager(manager); return manager_delegate_.get(); } Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate. DownloadManager has public SetDelegate method and tests and or other subsystems can install their own implementations of the delegate. Bug: 805905 Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8 TBR: tests updated to follow the API change. Reviewed-on: https://chromium-review.googlesource.com/894702 Reviewed-by: David Vallet <[email protected]> Reviewed-by: Min Qin <[email protected]> Cr-Commit-Position: refs/heads/master@{#533515} CWE ID: CWE-125
DownloadCoreServiceImpl::GetDownloadManagerDelegate() { DownloadManager* manager = BrowserContext::GetDownloadManager(profile_); if (download_manager_created_) return manager_delegate_.get(); download_manager_created_ = true; if (!manager_delegate_.get()) manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_)); manager_delegate_->SetDownloadManager(manager); #if BUILDFLAG(ENABLE_EXTENSIONS) extension_event_router_.reset( new extensions::ExtensionDownloadsEventRouter(profile_, manager)); #endif if (!profile_->IsOffTheRecord()) { history::HistoryService* history = HistoryServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); history->GetNextDownloadId( manager_delegate_->GetDownloadIdReceiverCallback()); download_history_.reset(new DownloadHistory( manager, std::unique_ptr<DownloadHistory::HistoryAdapter>( new DownloadHistory::HistoryAdapter(history)))); } download_ui_.reset(new DownloadUIController( manager, std::unique_ptr<DownloadUIController::Delegate>())); DCHECK(g_browser_process->download_status_updater()); g_browser_process->download_status_updater()->AddManager(manager); return manager_delegate_.get(); }
173,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: sfnt_init_face( FT_Stream stream, TT_Face face, FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Memory memory = face->root.memory; FT_Library library = face->root.driver->root.library; SFNT_Service sfnt; FT_Int face_index; /* for now, parameters are unused */ FT_UNUSED( num_params ); FT_UNUSED( params ); sfnt = (SFNT_Service)face->sfnt; if ( !sfnt ) { sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" ); if ( !sfnt ) { FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" )); return FT_THROW( Missing_Module ); } face->sfnt = sfnt; face->goto_table = sfnt->goto_table; } FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !face->mm ) { /* we want the MM interface from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->mm = ft_module_get_service( tt_module, FT_SERVICE_ID_MULTI_MASTERS, 0 ); } if ( !face->var ) { /* we want the metrics variations interface */ /* from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->var = ft_module_get_service( tt_module, FT_SERVICE_ID_METRICS_VARIATIONS, 0 ); } #endif FT_TRACE2(( "SFNT driver\n" )); error = sfnt_open_font( stream, face ); if ( error ) return error; /* Stream may have changed in sfnt_open_font. */ stream = face->root.stream; FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* value -(N+1) requests information on index N */ if ( face_instance_index < 0 ) face_index--; if ( face_index >= face->ttc_header.count ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else face_index = 0; } if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) ) return error; /* check whether we have a valid TrueType file */ error = sfnt->load_font_dir( face, stream ); if ( error ) return error; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_ULong fvar_len; FT_ULong version; FT_ULong offset; FT_UShort num_axes; FT_UShort axis_size; FT_UShort num_instances; FT_UShort instance_size; FT_Int instance_index; FT_Byte* default_values = NULL; FT_Byte* instance_values = NULL; face->is_default_instance = 1; instance_index = FT_ABS( face_instance_index ) >> 16; /* test whether current face is a GX font with named instances */ if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) || fvar_len < 20 || FT_READ_ULONG( version ) || FT_READ_USHORT( offset ) || FT_STREAM_SKIP( 2 ) /* reserved */ || FT_READ_USHORT( num_axes ) || FT_READ_USHORT( axis_size ) || FT_READ_USHORT( num_instances ) || FT_READ_USHORT( instance_size ) ) { version = 0; offset = 0; num_axes = 0; axis_size = 0; num_instances = 0; instance_size = 0; } /* check that the data is bound by the table length */ if ( version != 0x00010000UL || axis_size != 20 || num_axes == 0 || /* `num_axes' limit implied by 16-bit `instance_size' */ num_axes > 0x3FFE || !( instance_size == 4 + 4 * num_axes || instance_size == 6 + 4 * num_axes ) || /* `num_instances' limit implied by limited range of name IDs */ num_instances > 0x7EFF || offset + axis_size * num_axes + instance_size * num_instances > fvar_len ) num_instances = 0; else face->variation_support |= TT_FACE_FLAG_VAR_FVAR; /* * As documented in the OpenType specification, an entry for the * default instance may be omitted in the named instance table. In * particular this means that even if there is no named instance * table in the font we actually do have a named instance, namely the * default instance. * * For consistency, we always want the default instance in our list * of named instances. If it is missing, we try to synthesize it * later on. Here, we have to adjust `num_instances' accordingly. */ if ( !( FT_ALLOC( default_values, num_axes * 2 ) || FT_ALLOC( instance_values, num_axes * 2 ) ) ) { /* the current stream position is 16 bytes after the table start */ FT_ULong array_start = FT_STREAM_POS() - 16 + offset; FT_ULong default_value_offset, instance_offset; FT_Byte* p; FT_UInt i; default_value_offset = array_start + 8; p = default_values; for ( i = 0; i < num_axes; i++ ) { (void)FT_STREAM_READ_AT( default_value_offset, p, 2 ); default_value_offset += axis_size; p += 2; } instance_offset = array_start + axis_size * num_axes + 4; for ( i = 0; i < num_instances; i++ ) { (void)FT_STREAM_READ_AT( instance_offset, instance_values, num_axes * 2 ); if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) ) break; instance_offset += instance_size; } if ( i == num_instances ) { /* no default instance in named instance table; */ /* we thus have to synthesize it */ num_instances++; } } FT_FREE( default_values ); FT_FREE( instance_values ); /* we don't support Multiple Master CFFs yet */ if ( face->goto_table( face, TTAG_glyf, stream, 0 ) && !face->goto_table( face, TTAG_CFF, stream, 0 ) ) num_instances = 0; if ( instance_index > num_instances ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else num_instances = 0; } face->root.style_flags = (FT_Long)num_instances << 16; } #endif face->root.num_faces = face->ttc_header.count; face->root.face_index = face_instance_index; return error; } Commit Message: CWE ID: CWE-787
sfnt_init_face( FT_Stream stream, TT_Face face, FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Memory memory = face->root.memory; FT_Library library = face->root.driver->root.library; SFNT_Service sfnt; FT_Int face_index; /* for now, parameters are unused */ FT_UNUSED( num_params ); FT_UNUSED( params ); sfnt = (SFNT_Service)face->sfnt; if ( !sfnt ) { sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" ); if ( !sfnt ) { FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" )); return FT_THROW( Missing_Module ); } face->sfnt = sfnt; face->goto_table = sfnt->goto_table; } FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !face->mm ) { /* we want the MM interface from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->mm = ft_module_get_service( tt_module, FT_SERVICE_ID_MULTI_MASTERS, 0 ); } if ( !face->var ) { /* we want the metrics variations interface */ /* from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->var = ft_module_get_service( tt_module, FT_SERVICE_ID_METRICS_VARIATIONS, 0 ); } #endif FT_TRACE2(( "SFNT driver\n" )); error = sfnt_open_font( stream, face ); if ( error ) return error; /* Stream may have changed in sfnt_open_font. */ stream = face->root.stream; FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* value -(N+1) requests information on index N */ if ( face_instance_index < 0 ) face_index--; if ( face_index >= face->ttc_header.count ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else face_index = 0; } if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) ) return error; /* check whether we have a valid TrueType file */ error = sfnt->load_font_dir( face, stream ); if ( error ) return error; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_ULong fvar_len; FT_ULong version; FT_ULong offset; FT_UShort num_axes; FT_UShort axis_size; FT_UShort num_instances; FT_UShort instance_size; FT_Int instance_index; FT_Byte* default_values = NULL; FT_Byte* instance_values = NULL; face->is_default_instance = 1; instance_index = FT_ABS( face_instance_index ) >> 16; /* test whether current face is a GX font with named instances */ if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) || fvar_len < 20 || FT_READ_ULONG( version ) || FT_READ_USHORT( offset ) || FT_STREAM_SKIP( 2 ) /* reserved */ || FT_READ_USHORT( num_axes ) || FT_READ_USHORT( axis_size ) || FT_READ_USHORT( num_instances ) || FT_READ_USHORT( instance_size ) ) { version = 0; offset = 0; num_axes = 0; axis_size = 0; num_instances = 0; instance_size = 0; } /* check that the data is bound by the table length */ if ( version != 0x00010000UL || axis_size != 20 || num_axes == 0 || /* `num_axes' limit implied by 16-bit `instance_size' */ num_axes > 0x3FFE || !( instance_size == 4 + 4 * num_axes || instance_size == 6 + 4 * num_axes ) || /* `num_instances' limit implied by limited range of name IDs */ num_instances > 0x7EFF || offset + axis_size * num_axes + instance_size * num_instances > fvar_len ) num_instances = 0; else face->variation_support |= TT_FACE_FLAG_VAR_FVAR; /* * As documented in the OpenType specification, an entry for the * default instance may be omitted in the named instance table. In * particular this means that even if there is no named instance * table in the font we actually do have a named instance, namely the * default instance. * * For consistency, we always want the default instance in our list * of named instances. If it is missing, we try to synthesize it * later on. Here, we have to adjust `num_instances' accordingly. */ if ( !( FT_ALLOC( default_values, num_axes * 2 ) || FT_ALLOC( instance_values, num_axes * 2 ) ) ) { /* the current stream position is 16 bytes after the table start */ FT_ULong array_start = FT_STREAM_POS() - 16 + offset; FT_ULong default_value_offset, instance_offset; FT_Byte* p; FT_UInt i; default_value_offset = array_start + 8; p = default_values; for ( i = 0; i < num_axes; i++ ) { (void)FT_STREAM_READ_AT( default_value_offset, p, 2 ); default_value_offset += axis_size; p += 2; } instance_offset = array_start + axis_size * num_axes + 4; for ( i = 0; i < num_instances; i++ ) { (void)FT_STREAM_READ_AT( instance_offset, instance_values, num_axes * 2 ); if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) ) break; instance_offset += instance_size; } if ( i == num_instances ) { /* no default instance in named instance table; */ /* we thus have to synthesize it */ num_instances++; } } FT_FREE( default_values ); FT_FREE( instance_values ); /* we don't support Multiple Master CFFs yet; */ /* note that `glyf' or `CFF2' have precedence */ if ( face->goto_table( face, TTAG_glyf, stream, 0 ) && face->goto_table( face, TTAG_CFF2, stream, 0 ) && !face->goto_table( face, TTAG_CFF, stream, 0 ) ) num_instances = 0; if ( instance_index > num_instances ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else num_instances = 0; } face->root.style_flags = (FT_Long)num_instances << 16; } #endif face->root.num_faces = face->ttc_header.count; face->root.face_index = face_instance_index; return error; }
164,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint32_t readU32(const uint8_t* data, size_t offset) { return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]; } Commit Message: Avoid integer overflows in parsing fonts A malformed TTF can cause size calculations to overflow. This patch checks the maximum reasonable value so that the total size fits in 32 bits. It also adds some explicit casting to avoid possible technical undefined behavior when parsing sized unsigned values. Bug: 25645298 Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616 (cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274) CWE ID: CWE-19
static uint32_t readU32(const uint8_t* data, size_t offset) { return ((uint32_t)data[offset]) << 24 | ((uint32_t)data[offset + 1]) << 16 | ((uint32_t)data[offset + 2]) << 8 | ((uint32_t)data[offset + 3]); }
173,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_LINEARSIZE); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image, (unsigned int) (Max(1,(image->columns+3)/4) * 8)); else (void) WriteBlobLSBLong(image, (unsigned int) (Max(1,(image->columns+3)/4) * 16)); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) ResetMagickMemory(software,0,sizeof(software)); (void) strcpy(software,"IMAGEMAGICK"); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) // bitcount / masks (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) // ddscaps2 + reserved region (void) WriteBlobLSBLong(image,0x00); } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_LINEARSIZE); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8)); else (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16)); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) ResetMagickMemory(software,0,sizeof(software)); (void) strcpy(software,"IMAGEMAGICK"); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) // bitcount / masks (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) // ddscaps2 + reserved region (void) WriteBlobLSBLong(image,0x00); }
168,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { vpx_codec_err_t res = VPX_CODEC_OK; if(data + data_sz <= data) { res = VPX_CODEC_INVALID_PARAM; } else { /* Parse uncompresssed part of key frame header. * 3 bytes:- including version, frame type and an offset * 3 bytes:- sync code (0x9d, 0x01, 0x2a) * 4 bytes:- including image width and height in the lowest 14 bits * of each 2-byte value. */ uint8_t clear_buffer[10]; const uint8_t *clear = data; if (decrypt_cb) { int n = MIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, n); clear = clear_buffer; } si->is_kf = 0; if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */ { si->is_kf = 1; /* vet via sync code */ if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a) return VPX_CODEC_UNSUP_BITSTREAM; si->w = (clear[6] | (clear[7] << 8)) & 0x3fff; si->h = (clear[8] | (clear[9] << 8)) & 0x3fff; /*printf("w=%d, h=%d\n", si->w, si->h);*/ if (!(si->h | si->w)) res = VPX_CODEC_UNSUP_BITSTREAM; } else { res = VPX_CODEC_UNSUP_BITSTREAM; } } return res; } Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream Description from upstream: vp8: fix decoder crash with invalid leading keyframes decoding the same invalid keyframe twice would result in a crash as the second time through the decoder would be assumed to have been initialized as there was no resolution change. in this case the resolution was itself invalid (0x6), but vp8_peek_si() was only failing in the case of 0x0. invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by duplicating the first keyframe and additionally adds a valid one to ensure decoding can resume without error. Bug: 30593765 Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507 (cherry picked from commit fc0466b695dce03e10390101844caa374848d903) (cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136) CWE ID: CWE-20
static vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { vpx_codec_err_t res = VPX_CODEC_OK; if(data + data_sz <= data) { res = VPX_CODEC_INVALID_PARAM; } else { /* Parse uncompresssed part of key frame header. * 3 bytes:- including version, frame type and an offset * 3 bytes:- sync code (0x9d, 0x01, 0x2a) * 4 bytes:- including image width and height in the lowest 14 bits * of each 2-byte value. */ uint8_t clear_buffer[10]; const uint8_t *clear = data; if (decrypt_cb) { int n = MIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, n); clear = clear_buffer; } si->is_kf = 0; if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */ { si->is_kf = 1; /* vet via sync code */ if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a) return VPX_CODEC_UNSUP_BITSTREAM; si->w = (clear[6] | (clear[7] << 8)) & 0x3fff; si->h = (clear[8] | (clear[9] << 8)) & 0x3fff; /*printf("w=%d, h=%d\n", si->w, si->h);*/ if (!(si->h && si->w)) res = VPX_CODEC_CORRUPT_FRAME; } else { res = VPX_CODEC_UNSUP_BITSTREAM; } } return res; }
173,383
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserPpapiHostImpl::DeleteInstance(PP_Instance instance) { auto it = instance_map_.find(instance); DCHECK(it != instance_map_.end()); for (auto& observer : it->second->observer_list) observer.OnHostDestroyed(); instance_map_.erase(it); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void BrowserPpapiHostImpl::DeleteInstance(PP_Instance instance) { // NOTE: 'instance' may be coming from a compromised renderer process. We // take care here to make sure an attacker can't cause a UAF by deleting a // non-existent plugin instance. // See http://crbug.com/733548. auto it = instance_map_.find(instance); if (it != instance_map_.end()) { // We need to tell the observers for that instance that we are destroyed // because we won't have the opportunity to once we remove them from the // |instance_map_|. If the instance was deleted, observers for those // instances should never call back into the host anyway, so it is safe to // tell them that the host is destroyed. for (auto& observer : it->second->observer_list) observer.OnHostDestroyed(); instance_map_.erase(it); } else { NOTREACHED(); } }
172,310
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool RunLoop::BeforeRun() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); #if DCHECK_IS_ON() DCHECK(!run_called_); run_called_ = true; #endif // DCHECK_IS_ON() if (quit_called_) return false; auto& active_run_loops_ = delegate_->active_run_loops_; active_run_loops_.push(this); const bool is_nested = active_run_loops_.size() > 1; if (is_nested) { CHECK(delegate_->allow_nesting_); for (auto& observer : delegate_->nesting_observers_) observer.OnBeginNestedRunLoop(); } running_ = true; return true; } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
bool RunLoop::BeforeRun() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); #if DCHECK_IS_ON() DCHECK(!run_called_); run_called_ = true; #endif // DCHECK_IS_ON() if (quit_called_) return false; auto& active_run_loops_ = delegate_->active_run_loops_; active_run_loops_.push(this); const bool is_nested = active_run_loops_.size() > 1; if (is_nested) { CHECK(delegate_->allow_nesting_); for (auto& observer : delegate_->nesting_observers_) observer.OnBeginNestedRunLoop(); if (type_ == Type::kNestableTasksAllowed) delegate_->EnsureWorkScheduled(); } running_ = true; return true; }
171,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } Commit Message: issue #27, do not overwrite stack on corrupt RF64 file CWE ID: CWE-119
int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
169,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock *sctp_v6_create_accept_sk(struct sock *sk, struct sctp_association *asoc, bool kern) { struct sock *newsk; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct sctp6_sock *newsctp6sk; struct ipv6_txoptions *opt; newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern); if (!newsk) goto out; sock_init_data(NULL, newsk); sctp_copy_sock(newsk, sk, asoc); sock_reset_flag(sk, SOCK_ZAPPED); newsctp6sk = (struct sctp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newsctp6sk->inet6; sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); rcu_read_lock(); opt = rcu_dereference(np->opt); if (opt) opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); rcu_read_unlock(); /* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname() * and getpeername(). */ sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk); newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr; sk_refcnt_debug_inc(newsk); if (newsk->sk_prot->init(newsk)) { sk_common_release(newsk); newsk = NULL; } out: return newsk; } Commit Message: sctp: do not inherit ipv6_{mc|ac|fl}_list from parent SCTP needs fixes similar to 83eaddab4378 ("ipv6/dccp: do not inherit ipv6_mc_list from parent"), otherwise bad things can happen. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static struct sock *sctp_v6_create_accept_sk(struct sock *sk, struct sctp_association *asoc, bool kern) { struct sock *newsk; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct sctp6_sock *newsctp6sk; struct ipv6_txoptions *opt; newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern); if (!newsk) goto out; sock_init_data(NULL, newsk); sctp_copy_sock(newsk, sk, asoc); sock_reset_flag(sk, SOCK_ZAPPED); newsctp6sk = (struct sctp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newsctp6sk->inet6; sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; rcu_read_lock(); opt = rcu_dereference(np->opt); if (opt) opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); rcu_read_unlock(); /* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname() * and getpeername(). */ sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk); newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr; sk_refcnt_debug_inc(newsk); if (newsk->sk_prot->init(newsk)) { sk_common_release(newsk); newsk = NULL; } out: return newsk; }
168,129
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType TIFFWritePhotoshopLayers(Image* image, const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception) { BlobInfo *blob; CustomStreamInfo *custom_stream; Image *base_image, *next; ImageInfo *clone_info; MagickBooleanType status; PhotoshopProfile profile; PSDInfo info; StringInfo *layers; base_image=CloneImage(image,0,0,MagickFalse,exception); if (base_image == (Image *) NULL) return(MagickTrue); clone_info=CloneImageInfo(image_info); if (clone_info == (ImageInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); profile.offset=0; profile.quantum=MagickMinBlobExtent; layers=AcquireStringInfo(profile.quantum); if (layers == (StringInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } profile.data=layers; profile.extent=layers->length; custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } blob=CloneBlobInfo((BlobInfo *) NULL); if (blob == (BlobInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); custom_stream=DestroyCustomStreamInfo(custom_stream); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } DestroyBlob(base_image); base_image->blob=blob; next=base_image; while (next != (Image *) NULL) next=SyncNextImageInList(next); AttachCustomStream(base_image->blob,custom_stream); InitPSDInfo(image,&info); base_image->endian=endian; WriteBlobString(base_image,"Adobe Photoshop Document Data Block"); WriteBlobByte(base_image,0); WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" : "8BIMLayr"); status=WritePSDLayers(base_image,clone_info,&info,exception); if (status != MagickFalse) { SetStringInfoLength(layers,(size_t) profile.offset); status=SetImageProfile(image,"tiff:37724",layers,exception); } next=base_image; while (next != (Image *) NULL) { CloseBlob(next); next=next->next; } layers=DestroyStringInfo(layers); clone_info=DestroyImageInfo(clone_info); custom_stream=DestroyCustomStreamInfo(custom_stream); return(status); } Commit Message: Fixed possible memory leak reported in #1206 CWE ID: CWE-772
static MagickBooleanType TIFFWritePhotoshopLayers(Image* image, const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception) { BlobInfo *blob; CustomStreamInfo *custom_stream; Image *base_image, *next; ImageInfo *clone_info; MagickBooleanType status; PhotoshopProfile profile; PSDInfo info; StringInfo *layers; base_image=CloneImage(image,0,0,MagickFalse,exception); if (base_image == (Image *) NULL) return(MagickTrue); clone_info=CloneImageInfo(image_info); if (clone_info == (ImageInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); profile.offset=0; profile.quantum=MagickMinBlobExtent; layers=AcquireStringInfo(profile.quantum); if (layers == (StringInfo *) NULL) { base_image=DestroyImage(base_image); clone_info=DestroyImageInfo(clone_info); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } profile.data=layers; profile.extent=layers->length; custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) { base_image=DestroyImage(base_image); clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } blob=CloneBlobInfo((BlobInfo *) NULL); if (blob == (BlobInfo *) NULL) { base_image=DestroyImage(base_image); clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); custom_stream=DestroyCustomStreamInfo(custom_stream); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } DestroyBlob(base_image); base_image->blob=blob; next=base_image; while (next != (Image *) NULL) next=SyncNextImageInList(next); AttachCustomStream(base_image->blob,custom_stream); InitPSDInfo(image,&info); base_image->endian=endian; WriteBlobString(base_image,"Adobe Photoshop Document Data Block"); WriteBlobByte(base_image,0); WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" : "8BIMLayr"); status=WritePSDLayers(base_image,clone_info,&info,exception); if (status != MagickFalse) { SetStringInfoLength(layers,(size_t) profile.offset); status=SetImageProfile(image,"tiff:37724",layers,exception); } next=base_image; while (next != (Image *) NULL) { CloseBlob(next); next=next->next; } layers=DestroyStringInfo(layers); clone_info=DestroyImageInfo(clone_info); custom_stream=DestroyCustomStreamInfo(custom_stream); return(status); }
169,043
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t x, y; unsigned short color; if (dds_info->pixelformat.rgb_bitcount == 8) (void) SetImageType(image,GrayscaleType); else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask( dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000)) ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 8) SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image))); else if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); SetPixelRed(q,ScaleCharToQuantum((unsigned char) (((color >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 5) >> 10)/63.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (dds_info->pixelformat.rgb_bitcount == 32) (void) ReadBlobByte(image); } SetPixelAlpha(q,QuantumRange); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } SkipRGBMipmaps(image, dds_info, 3); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t x, y; unsigned short color; if (dds_info->pixelformat.rgb_bitcount == 8) (void) SetImageType(image,GrayscaleType); else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask( dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000)) ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 8) SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image))); else if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); SetPixelRed(q,ScaleCharToQuantum((unsigned char) (((color >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 5) >> 10)/63.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (dds_info->pixelformat.rgb_bitcount == 32) (void) ReadBlobByte(image); } SetPixelAlpha(q,QuantumRange); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } return(SkipRGBMipmaps(image,dds_info,3,exception)); }
168,902
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: StyleResolver::StyleResolver(Document& document) : m_document(document) , m_fontSelector(CSSFontSelector::create(&document)) , m_viewportStyleResolver(ViewportStyleResolver::create(&document)) , m_styleResourceLoader(document.fetcher()) , m_styleResolverStatsSequence(0) , m_accessCount(0) { Element* root = document.documentElement(); m_fontSelector->registerForInvalidationCallbacks(this); CSSDefaultStyleSheets::initDefaultStyle(root); FrameView* view = document.view(); if (view) m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType())); else m_medium = adoptPtr(new MediaQueryEvaluator("all")); if (root) m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules); if (m_rootDefaultStyle && view) m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get())); m_styleTree.clear(); initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors()); #if ENABLE(SVG_FONTS) if (document.svgExtensions()) { const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements(); HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end(); for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it) fontSelector()->addFontFaceRule((*it)->fontFaceRule()); } #endif document.styleEngine()->appendActiveAuthorStyleSheets(this); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
StyleResolver::StyleResolver(Document& document) : m_document(document) , m_fontSelector(CSSFontSelector::create(&document)) , m_viewportStyleResolver(ViewportStyleResolver::create(&document)) , m_styleResourceLoader(document.fetcher()) , m_styleResolverStatsSequence(0) , m_accessCount(0) { m_fontSelector->registerForInvalidationCallbacks(this); // FIXME: Why do this here instead of as part of resolving style on the root? CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary(); // Construct document root element default style. This is needed // This is here instead of constructor because when constructor is run, // Document doesn't have documentElement. // NOTE: This assumes that element that gets passed to the styleForElement call // is always from the document that owns the StyleResolver. FrameView* view = document.view(); if (view) m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType())); else m_medium = adoptPtr(new MediaQueryEvaluator("all")); Element* root = document.documentElement(); if (root) m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules); if (m_rootDefaultStyle && view) m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get())); m_styleTree.clear(); initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors()); #if ENABLE(SVG_FONTS) if (document.svgExtensions()) { const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements(); HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end(); for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it) fontSelector()->addFontFaceRule((*it)->fontFaceRule()); } #endif document.styleEngine()->appendActiveAuthorStyleSheets(this); }
171,584
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = calloc(1, sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = malloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = malloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = safe_calloc(sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = safe_calloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = safe_calloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; }
169,573
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_inquire_sec_context_by_oid( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; ret = gss_inquire_sec_context_by_oid(minor_status, context_handle, desired_object, data_set); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_inquire_sec_context_by_oid( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; /* There are no SPNEGO-specific OIDs for this function. */ if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_UNAVAILABLE); ret = gss_inquire_sec_context_by_oid(minor_status, sc->ctx_handle, desired_object, data_set); return (ret); }
166,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int send_event (int fd, uint16_t type, uint16_t code, int32_t value) { struct uinput_event event; BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__, type, code, value); memset(&event, 0, sizeof(event)); event.type = type; event.code = code; event.value = value; return write(fd, &event, sizeof(event)); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int send_event (int fd, uint16_t type, uint16_t code, int32_t value) { struct uinput_event event; BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__, type, code, value); memset(&event, 0, sizeof(event)); event.type = type; event.code = code; event.value = value; return TEMP_FAILURE_RETRY(write(fd, &event, sizeof(event))); }
173,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebGL2RenderingContextBase::bindSampler(GLuint unit, WebGLSampler* sampler) { if (isContextLost()) return; bool deleted; if (!CheckObjectToBeBound("bindSampler", sampler, deleted)) return; if (deleted) { SynthesizeGLError(GL_INVALID_OPERATION, "bindSampler", "attempted to bind a deleted sampler"); return; } if (unit >= sampler_units_.size()) { SynthesizeGLError(GL_INVALID_VALUE, "bindSampler", "texture unit out of range"); return; } sampler_units_[unit] = sampler; ContextGL()->BindSampler(unit, ObjectOrZero(sampler)); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#565016} CWE ID: CWE-119
void WebGL2RenderingContextBase::bindSampler(GLuint unit, WebGLSampler* sampler) { bool deleted; if (!CheckObjectToBeBound("bindSampler", sampler, deleted)) return; if (deleted) { SynthesizeGLError(GL_INVALID_OPERATION, "bindSampler", "attempted to bind a deleted sampler"); return; } if (unit >= sampler_units_.size()) { SynthesizeGLError(GL_INVALID_VALUE, "bindSampler", "texture unit out of range"); return; } sampler_units_[unit] = sampler; ContextGL()->BindSampler(unit, ObjectOrZero(sampler)); }
173,122
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kill_something_info(int sig, struct siginfo *info, pid_t pid) { int ret; if (pid > 0) { rcu_read_lock(); ret = kill_pid_info(sig, info, find_vpid(pid)); rcu_read_unlock(); return ret; } read_lock(&tasklist_lock); if (pid != -1) { ret = __kill_pgrp_info(sig, info, pid ? find_vpid(-pid) : task_pgrp(current)); } else { int retval = 0, count = 0; struct task_struct * p; for_each_process(p) { if (task_pid_vnr(p) > 1 && !same_thread_group(p, current)) { int err = group_send_sig_info(sig, info, p); ++count; if (err != -EPERM) retval = err; } } ret = count ? retval : -ESRCH; } read_unlock(&tasklist_lock); return ret; } Commit Message: kernel/signal.c: avoid undefined behaviour in kill_something_info When running kill(72057458746458112, 0) in userspace I hit the following issue. UBSAN: Undefined behaviour in kernel/signal.c:1462:11 negation of -2147483648 cannot be represented in type 'int': CPU: 226 PID: 9849 Comm: test Tainted: G B ---- ------- 3.10.0-327.53.58.70.x86_64_ubsan+ #116 Hardware name: Huawei Technologies Co., Ltd. RH8100 V3/BC61PBIA, BIOS BLHSV028 11/11/2014 Call Trace: dump_stack+0x19/0x1b ubsan_epilogue+0xd/0x50 __ubsan_handle_negate_overflow+0x109/0x14e SYSC_kill+0x43e/0x4d0 SyS_kill+0xe/0x10 system_call_fastpath+0x16/0x1b Add code to avoid the UBSAN detection. [[email protected]: tweak comment] Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: zhongjiang <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: Michal Hocko <[email protected]> Cc: Vlastimil Babka <[email protected]> Cc: Xishi Qiu <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119
static int kill_something_info(int sig, struct siginfo *info, pid_t pid) { int ret; if (pid > 0) { rcu_read_lock(); ret = kill_pid_info(sig, info, find_vpid(pid)); rcu_read_unlock(); return ret; } /* -INT_MIN is undefined. Exclude this case to avoid a UBSAN warning */ if (pid == INT_MIN) return -ESRCH; read_lock(&tasklist_lock); if (pid != -1) { ret = __kill_pgrp_info(sig, info, pid ? find_vpid(-pid) : task_pgrp(current)); } else { int retval = 0, count = 0; struct task_struct * p; for_each_process(p) { if (task_pid_vnr(p) > 1 && !same_thread_group(p, current)) { int err = group_send_sig_info(sig, info, p); ++count; if (err != -EPERM) retval = err; } } ret = count ? retval : -ESRCH; } read_unlock(&tasklist_lock); return ret; }
169,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while ((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while (((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) && (ctxt->instate != XML_PARSER_EOF)) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if (ctxt->instate == XML_PARSER_EOF) goto error; if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); error: if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); }
171,270
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; }
167,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int GetFreeFrameBuffer(size_t min_size, vpx_codec_frame_buffer_t *fb) { EXPECT_TRUE(fb != NULL); const int idx = FindFreeBufferIndex(); if (idx == num_buffers_) return -1; if (ext_fb_list_[idx].size < min_size) { delete [] ext_fb_list_[idx].data; ext_fb_list_[idx].data = new uint8_t[min_size]; ext_fb_list_[idx].size = min_size; } SetFrameBuffer(idx, fb); return 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int GetFreeFrameBuffer(size_t min_size, vpx_codec_frame_buffer_t *fb) { EXPECT_TRUE(fb != NULL); const int idx = FindFreeBufferIndex(); if (idx == num_buffers_) return -1; if (ext_fb_list_[idx].size < min_size) { delete [] ext_fb_list_[idx].data; ext_fb_list_[idx].data = new uint8_t[min_size]; memset(ext_fb_list_[idx].data, 0, min_size); ext_fb_list_[idx].size = min_size; } SetFrameBuffer(idx, fb); return 0; }
174,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd3_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); if (!IS_POSIXACL(inode) || !inode->i_op->set_acl) { error = -EOPNOTSUPP; goto out_errno; } error = fh_want_write(fh); if (error) goto out_errno; error = inode->i_op->set_acl(inode, argp->acl_access, ACL_TYPE_ACCESS); if (error) goto out_drop_write; error = inode->i_op->set_acl(inode, argp->acl_default, ACL_TYPE_DEFAULT); out_drop_write: fh_drop_write(fh); out_errno: nfserr = nfserrno(error); out: /* argp->acl_{access,default} may have been allocated in nfs3svc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); RETURN_STATUS(nfserr); } Commit Message: nfsd: check permissions when setting ACLs Use set_posix_acl, which includes proper permission checks, instead of calling ->set_acl directly. Without this anyone may be able to grant themselves permissions to a file by setting the ACL. Lock the inode to make the new checks atomic with respect to set_acl. (Also, nfsd was the only caller of set_acl not locking the inode, so I suspect this may fix other races.) This also simplifies the code, and ensures our ACLs are checked by posix_acl_valid. The permission checks and the inode locking were lost with commit 4ac7249e, which changed nfsd to use the set_acl inode operation directly instead of going through xattr handlers. Reported-by: David Sinquin <[email protected]> [[email protected]: use set_posix_acl] Fixes: 4ac7249e Cc: Christoph Hellwig <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-284
static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd3_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); error = fh_want_write(fh); if (error) goto out_errno; fh_lock(fh); error = set_posix_acl(inode, ACL_TYPE_ACCESS, argp->acl_access); if (error) goto out_drop_lock; error = set_posix_acl(inode, ACL_TYPE_DEFAULT, argp->acl_default); out_drop_lock: fh_unlock(fh); fh_drop_write(fh); out_errno: nfserr = nfserrno(error); out: /* argp->acl_{access,default} may have been allocated in nfs3svc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); RETURN_STATUS(nfserr); }
167,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_get_algo_key_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); RETURN_LONG(mcrypt_module_get_algo_key_size(module, dir)); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_get_algo_key_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); RETURN_LONG(mcrypt_module_get_algo_key_size(module, dir)); }
167,100
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t len; uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->iov.iov_len / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { len = r->sector_count * 512; if (len > SCSI_DMA_BUF_SIZE) { len = SCSI_DMA_BUF_SIZE; } r->iov.iov_len = len; DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, len); scsi_req_data(&r->req, len); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->qiov.size / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { scsi_init_iovec(r); DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size); scsi_req_data(&r->req, r->qiov.size); } }
169,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int MDC2_Update(MDC2_CTX *c, const unsigned char *in, size_t len) { size_t i, j; i = c->num; if (i != 0) { if (i + len < MDC2_BLOCK) { /* partial block */ memcpy(&(c->data[i]), in, len); c->num += (int)len; return 1; } else { /* filled one */ j = MDC2_BLOCK - i; memcpy(&(c->data[i]), in, j); len -= j; in += j; c->num = 0; mdc2_body(c, &(c->data[0]), MDC2_BLOCK); } } i = len & ~((size_t)MDC2_BLOCK - 1); if (i > 0) mdc2_body(c, in, i); j = len - i; if (j > 0) { memcpy(&(c->data[0]), &(in[i]), j); c->num = (int)j; } return 1; } Commit Message: CWE ID: CWE-787
int MDC2_Update(MDC2_CTX *c, const unsigned char *in, size_t len) { size_t i, j; i = c->num; if (i != 0) { if (len < MDC2_BLOCK - i) { /* partial block */ memcpy(&(c->data[i]), in, len); c->num += (int)len; return 1; } else { /* filled one */ j = MDC2_BLOCK - i; memcpy(&(c->data[i]), in, j); len -= j; in += j; c->num = 0; mdc2_body(c, &(c->data[0]), MDC2_BLOCK); } } i = len & ~((size_t)MDC2_BLOCK - 1); if (i > 0) mdc2_body(c, in, i); j = len - i; if (j > 0) { memcpy(&(c->data[0]), &(in[i]), j); c->num = (int)j; } return 1; }
164,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; char* tag_value = NULL; char* empty_result = ""; int result = 0; char* msg = NULL; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name ,&loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Call ICU get */ tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0); /* No value found */ if( result == -1 ) { if( tag_value){ efree( tag_value); } RETURN_STRING( empty_result , TRUE); } /* value found */ if( tag_value){ RETURN_STRING( tag_value , FALSE); } /* Error encountered while fetching the value */ if( result ==0) { spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_NULL(); } } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; char* tag_value = NULL; char* empty_result = ""; int result = 0; char* msg = NULL; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name ,&loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Call ICU get */ tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0); /* No value found */ if( result == -1 ) { if( tag_value){ efree( tag_value); } RETURN_STRING( empty_result , TRUE); } /* value found */ if( tag_value){ RETURN_STRING( tag_value , FALSE); } /* Error encountered while fetching the value */ if( result ==0) { spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_NULL(); } }
167,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; /* The remaining bits are in the top of the byte, the mask is the bits to * retain. */ mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth, int littleendian) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; if (littleendian) mask = 0xff << (bitWidth & 7); else mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } }
173,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */ { xml_parser *parser; int auto_detect = 0; char *encoding_param = NULL; int encoding_param_len = 0; char *ns_param = NULL; int ns_param_len = 0; XML_Char *encoding; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) { RETURN_FALSE; } if (encoding_param != NULL) { /* The supported encoding types are hardcoded here because * we are limited to the encodings supported by expat/xmltok. */ if (encoding_param_len == 0) { encoding = XML(default_encoding); auto_detect = 1; } else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) { encoding = "ISO-8859-1"; } else if (strcasecmp(encoding_param, "UTF-8") == 0) { encoding = "UTF-8"; } else if (strcasecmp(encoding_param, "US-ASCII") == 0) { encoding = "US-ASCII"; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param); RETURN_FALSE; } } else { encoding = XML(default_encoding); } if (ns_support && ns_param == NULL){ ns_param = ":"; } parser = ecalloc(1, sizeof(xml_parser)); parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding), &php_xml_mem_hdlrs, ns_param); parser->target_encoding = encoding; parser->case_folding = 1; parser->object = NULL; parser->isparsing = 0; XML_SetUserData(parser->parser, parser); ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser); parser->index = Z_LVAL_P(return_value); } /* }}} */ Commit Message: CWE ID: CWE-119
static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */ { xml_parser *parser; int auto_detect = 0; char *encoding_param = NULL; int encoding_param_len = 0; char *ns_param = NULL; int ns_param_len = 0; XML_Char *encoding; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) { RETURN_FALSE; } if (encoding_param != NULL) { /* The supported encoding types are hardcoded here because * we are limited to the encodings supported by expat/xmltok. */ if (encoding_param_len == 0) { encoding = XML(default_encoding); auto_detect = 1; } else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) { encoding = "ISO-8859-1"; } else if (strcasecmp(encoding_param, "UTF-8") == 0) { encoding = "UTF-8"; } else if (strcasecmp(encoding_param, "US-ASCII") == 0) { encoding = "US-ASCII"; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param); RETURN_FALSE; } } else { encoding = XML(default_encoding); } if (ns_support && ns_param == NULL){ ns_param = ":"; } parser = ecalloc(1, sizeof(xml_parser)); parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding), &php_xml_mem_hdlrs, ns_param); parser->target_encoding = encoding; parser->case_folding = 1; parser->object = NULL; parser->isparsing = 0; XML_SetUserData(parser->parser, parser); ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser); parser->index = Z_LVAL_P(return_value); } /* }}} */
165,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool OMXNodeInstance::handleMessage(omx_message &msg) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (msg.type == omx_message::FILL_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.extended_buffer_data.buffer); { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( FBD, WITH_STATS(FULL_BUFFER( msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd))); unbumpDebugLevel_l(kPortIndexOutput); } BufferMeta *buffer_meta = static_cast<BufferMeta *>(buffer->pAppPrivate); if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset || buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) { CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter, FULL_BUFFER(NULL, buffer, msg.fenceFd)); } buffer_meta->CopyFromOMX(buffer); if (bufferSource != NULL) { bufferSource->codecBufferFilled(buffer); msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp; } } else if (msg.type == omx_message::EMPTY_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.buffer_data.buffer); { Mutex::Autolock _l(mDebugLock); mInputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd))); } if (bufferSource != NULL) { bufferSource->codecBufferEmptied(buffer, msg.fenceFd); return true; } } return false; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
bool OMXNodeInstance::handleMessage(omx_message &msg) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (msg.type == omx_message::FILL_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.extended_buffer_data.buffer, kPortIndexOutput); if (buffer == NULL) { return false; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( FBD, WITH_STATS(FULL_BUFFER( msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd))); unbumpDebugLevel_l(kPortIndexOutput); } BufferMeta *buffer_meta = static_cast<BufferMeta *>(buffer->pAppPrivate); if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset || buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) { CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter, FULL_BUFFER(NULL, buffer, msg.fenceFd)); } buffer_meta->CopyFromOMX(buffer); if (bufferSource != NULL) { bufferSource->codecBufferFilled(buffer); msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp; } } else if (msg.type == omx_message::EMPTY_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.buffer_data.buffer, kPortIndexInput); if (buffer == NULL) { return false; } { Mutex::Autolock _l(mDebugLock); mInputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd))); } if (bufferSource != NULL) { bufferSource->codecBufferEmptied(buffer, msg.fenceFd); return true; } } return false; }
173,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SharedMemoryHandleProvider::InitFromMojoHandle( mojo::ScopedSharedBufferHandle buffer_handle) { #if DCHECK_IS_ON() DCHECK_EQ(map_ref_count_, 0); #endif DCHECK(!shared_memory_); base::SharedMemoryHandle memory_handle; const MojoResult result = mojo::UnwrapSharedMemoryHandle(std::move(buffer_handle), &memory_handle, &mapped_size_, &read_only_flag_); if (result != MOJO_RESULT_OK) return false; shared_memory_.emplace(memory_handle, read_only_flag_); return true; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
bool SharedMemoryHandleProvider::InitFromMojoHandle( mojo::ScopedSharedBufferHandle buffer_handle) { #if DCHECK_IS_ON() DCHECK_EQ(map_ref_count_, 0); #endif DCHECK(!shared_memory_); base::SharedMemoryHandle memory_handle; mojo::UnwrappedSharedMemoryHandleProtection protection; const MojoResult result = mojo::UnwrapSharedMemoryHandle( std::move(buffer_handle), &memory_handle, &mapped_size_, &protection); if (result != MOJO_RESULT_OK) return false; read_only_flag_ = protection == mojo::UnwrappedSharedMemoryHandleProtection::kReadOnly; shared_memory_.emplace(memory_handle, read_only_flag_); return true; }
172,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation( const NavigationRequest& request) { DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme)) << "Don't call this method for JavaScript URLs as those create a " "temporary NavigationRequest and we don't want to reset an ongoing " "navigation's speculative RFH."; RenderFrameHostImpl* navigation_rfh = nullptr; SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigationRequest(request); bool use_current_rfh = current_site_instance == dest_site_instance; bool notify_webui_of_rf_creation = false; if (use_current_rfh) { if (speculative_render_frame_host_) { if (speculative_render_frame_host_->navigation_handle()) { frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded( speculative_render_frame_host_->navigation_handle() ->pending_nav_entry_id()); } DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost()); } if (frame_tree_node_->IsMainFrame()) { UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url, request.bindings()); } navigation_rfh = render_frame_host_.get(); DCHECK(!speculative_render_frame_host_); } else { if (!speculative_render_frame_host_ || speculative_render_frame_host_->GetSiteInstance() != dest_site_instance.get()) { CleanUpNavigation(); bool success = CreateSpeculativeRenderFrameHost(current_site_instance, dest_site_instance.get()); DCHECK(success); } DCHECK(speculative_render_frame_host_); if (frame_tree_node_->IsMainFrame()) { bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI( request.common_params().url, request.bindings()); speculative_render_frame_host_->CommitPendingWebUI(); DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui()); notify_webui_of_rf_creation = changed_web_ui && speculative_render_frame_host_->web_ui(); } navigation_rfh = speculative_render_frame_host_.get(); if (!render_frame_host_->IsRenderFrameLive()) { if (GetRenderFrameProxyHost(dest_site_instance.get())) { navigation_rfh->Send( new FrameMsg_SwapIn(navigation_rfh->GetRoutingID())); } CommitPending(); if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) { render_frame_host_->web_ui()->RenderFrameCreated( render_frame_host_.get()); notify_webui_of_rf_creation = false; } } } DCHECK(navigation_rfh && (navigation_rfh == render_frame_host_.get() || navigation_rfh == speculative_render_frame_host_.get())); if (!navigation_rfh->IsRenderFrameLive()) { if (!ReinitializeRenderFrame(navigation_rfh)) return nullptr; notify_webui_of_rf_creation = true; if (navigation_rfh == render_frame_host_.get()) { EnsureRenderFrameHostVisibilityConsistent(); EnsureRenderFrameHostPageFocusConsistent(); delegate_->NotifyMainFrameSwappedFromRenderManager( nullptr, render_frame_host_->render_view_host()); } } if (notify_webui_of_rf_creation && GetNavigatingWebUI() && frame_tree_node_->IsMainFrame()) { GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh); } return navigation_rfh; } Commit Message: Fix issue with pending NavigationEntry being discarded incorrectly This CL fixes an issue where we would attempt to discard a pending NavigationEntry when a cross-process navigation to this NavigationEntry is interrupted by another navigation to the same NavigationEntry. BUG=760342,797656,796135 Change-Id: I204deff1efd4d572dd2e0b20e492592d48d787d9 Reviewed-on: https://chromium-review.googlesource.com/850877 Reviewed-by: Charlie Reis <[email protected]> Commit-Queue: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#528611} CWE ID: CWE-20
RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation( const NavigationRequest& request) { DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme)) << "Don't call this method for JavaScript URLs as those create a " "temporary NavigationRequest and we don't want to reset an ongoing " "navigation's speculative RFH."; RenderFrameHostImpl* navigation_rfh = nullptr; SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigationRequest(request); bool use_current_rfh = current_site_instance == dest_site_instance; bool notify_webui_of_rf_creation = false; if (use_current_rfh) { if (speculative_render_frame_host_) { // NavigationEntry stopped if needed. This is the case if the new // navigation was started from BeginNavigation. If the navigation was // started through the NavigationController, the NavigationController has // already updated its state properly, and doesn't need to be notified. if (speculative_render_frame_host_->navigation_handle() && request.from_begin_navigation()) { frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded( speculative_render_frame_host_->navigation_handle() ->pending_nav_entry_id()); } DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost()); } if (frame_tree_node_->IsMainFrame()) { UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url, request.bindings()); } navigation_rfh = render_frame_host_.get(); DCHECK(!speculative_render_frame_host_); } else { if (!speculative_render_frame_host_ || speculative_render_frame_host_->GetSiteInstance() != dest_site_instance.get()) { CleanUpNavigation(); bool success = CreateSpeculativeRenderFrameHost(current_site_instance, dest_site_instance.get()); DCHECK(success); } DCHECK(speculative_render_frame_host_); if (frame_tree_node_->IsMainFrame()) { bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI( request.common_params().url, request.bindings()); speculative_render_frame_host_->CommitPendingWebUI(); DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui()); notify_webui_of_rf_creation = changed_web_ui && speculative_render_frame_host_->web_ui(); } navigation_rfh = speculative_render_frame_host_.get(); if (!render_frame_host_->IsRenderFrameLive()) { if (GetRenderFrameProxyHost(dest_site_instance.get())) { navigation_rfh->Send( new FrameMsg_SwapIn(navigation_rfh->GetRoutingID())); } CommitPending(); if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) { render_frame_host_->web_ui()->RenderFrameCreated( render_frame_host_.get()); notify_webui_of_rf_creation = false; } } } DCHECK(navigation_rfh && (navigation_rfh == render_frame_host_.get() || navigation_rfh == speculative_render_frame_host_.get())); if (!navigation_rfh->IsRenderFrameLive()) { if (!ReinitializeRenderFrame(navigation_rfh)) return nullptr; notify_webui_of_rf_creation = true; if (navigation_rfh == render_frame_host_.get()) { EnsureRenderFrameHostVisibilityConsistent(); EnsureRenderFrameHostPageFocusConsistent(); delegate_->NotifyMainFrameSwappedFromRenderManager( nullptr, render_frame_host_->render_view_host()); } } if (notify_webui_of_rf_creation && GetNavigatingWebUI() && frame_tree_node_->IsMainFrame()) { GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh); } return navigation_rfh; }
172,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val - 1); } Commit Message: CWE ID: CWE-20
void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); }
165,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); }
167,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } Commit Message: CWE ID: CWE-310
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
164,791
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_exit_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); perf_event_exit_cpu_context(cpu); mutex_lock(&swhash->hlist_mutex); swhash->online = false; swevent_hlist_release(swhash); mutex_unlock(&swhash->hlist_mutex); } Commit Message: perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <[email protected]> Tested-by: Sasha Levin <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-416
static void perf_event_exit_cpu(int cpu) { perf_event_exit_cpu_context(cpu); }
167,460
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb) { spin_unlock(&hb->lock); drop_futex_key_refs(&q->key); } Commit Message: futex: Fix errors in nested key ref-counting futex_wait() is leaking key references due to futex_wait_setup() acquiring an additional reference via the queue_lock() routine. The nested key ref-counting has been masking bugs and complicating code analysis. queue_lock() is only called with a previously ref-counted key, so remove the additional ref-counting from the queue_(un)lock() functions. Also futex_wait_requeue_pi() drops one key reference too many in unqueue_me_pi(). Remove the key reference handling from unqueue_me_pi(). This was paired with a queue_lock() in futex_lock_pi(), so the count remains unchanged. Document remaining nested key ref-counting sites. Signed-off-by: Darren Hart <[email protected]> Reported-and-tested-by: Matthieu Fertré<[email protected]> Reported-by: Louis Rilling<[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Eric Dumazet <[email protected]> Cc: John Kacur <[email protected]> Cc: Rusty Russell <[email protected]> LKML-Reference: <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: [email protected] CWE ID: CWE-119
queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb) { spin_unlock(&hb->lock); }
166,452
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintRenderFrameHelper::PreviewPageRendered(int page_number, PdfMetafileSkia* metafile) { DCHECK_GE(page_number, FIRST_PAGE_INDEX); if (!print_preview_context_.IsModifiable() || !print_preview_context_.generate_draft_pages()) { DCHECK(!metafile); return true; } if (!metafile) { NOTREACHED(); print_preview_context_.set_error( PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE); return false; } PrintHostMsg_DidPreviewPage_Params preview_page_params; if (!CopyMetafileDataToSharedMem(*metafile, &preview_page_params.metafile_data_handle)) { LOG(ERROR) << "CopyMetafileDataToSharedMem failed"; print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED); return false; } preview_page_params.data_size = metafile->GetDataSize(); preview_page_params.page_number = page_number; preview_page_params.preview_request_id = print_pages_params_->params.preview_request_id; Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params)); return true; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
bool PrintRenderFrameHelper::PreviewPageRendered(int page_number, PdfMetafileSkia* metafile) { DCHECK_GE(page_number, FIRST_PAGE_INDEX); if (!print_preview_context_.IsModifiable() || !print_preview_context_.generate_draft_pages()) { DCHECK(!metafile); return true; } if (!metafile) { NOTREACHED(); print_preview_context_.set_error( PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE); return false; } PrintHostMsg_DidPreviewPage_Params preview_page_params; if (!CopyMetafileDataToReadOnlySharedMem( *metafile, &preview_page_params.metafile_data_handle)) { LOG(ERROR) << "CopyMetafileDataToReadOnlySharedMem failed"; print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED); return false; } preview_page_params.data_size = metafile->GetDataSize(); preview_page_params.page_number = page_number; preview_page_params.preview_request_id = print_pages_params_->params.preview_request_id; Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params)); return true; }
172,853
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct rds_connection *__rds_conn_create(struct net *net, __be32 laddr, __be32 faddr, struct rds_transport *trans, gfp_t gfp, int is_outgoing) { struct rds_connection *conn, *parent = NULL; struct hlist_head *head = rds_conn_bucket(laddr, faddr); struct rds_transport *loop_trans; unsigned long flags; int ret; struct rds_transport *otrans = trans; if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP) goto new_conn; rcu_read_lock(); conn = rds_conn_lookup(net, head, laddr, faddr, trans); if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport && laddr == faddr && !is_outgoing) { /* This is a looped back IB connection, and we're * called by the code handling the incoming connect. * We need a second connection object into which we * can stick the other QP. */ parent = conn; conn = parent->c_passive; } rcu_read_unlock(); if (conn) goto out; new_conn: conn = kmem_cache_zalloc(rds_conn_slab, gfp); if (!conn) { conn = ERR_PTR(-ENOMEM); goto out; } INIT_HLIST_NODE(&conn->c_hash_node); conn->c_laddr = laddr; conn->c_faddr = faddr; spin_lock_init(&conn->c_lock); conn->c_next_tx_seq = 1; rds_conn_net_set(conn, net); init_waitqueue_head(&conn->c_waitq); INIT_LIST_HEAD(&conn->c_send_queue); INIT_LIST_HEAD(&conn->c_retrans); ret = rds_cong_get_maps(conn); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } /* * This is where a connection becomes loopback. If *any* RDS sockets * can bind to the destination address then we'd rather the messages * flow through loopback rather than either transport. */ loop_trans = rds_trans_get_preferred(net, faddr); if (loop_trans) { rds_trans_put(loop_trans); conn->c_loopback = 1; if (is_outgoing && trans->t_prefer_loopback) { /* "outgoing" connection - and the transport * says it wants the connection handled by the * loopback transport. This is what TCP does. */ trans = &rds_loop_transport; } } conn->c_trans = trans; ret = trans->conn_alloc(conn, gfp); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } atomic_set(&conn->c_state, RDS_CONN_DOWN); conn->c_send_gen = 0; conn->c_reconnect_jiffies = 0; INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker); INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker); INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker); INIT_WORK(&conn->c_down_w, rds_shutdown_worker); mutex_init(&conn->c_cm_lock); conn->c_flags = 0; rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n", conn, &laddr, &faddr, trans->t_name ? trans->t_name : "[unknown]", is_outgoing ? "(outgoing)" : ""); /* * Since we ran without holding the conn lock, someone could * have created the same conn (either normal or passive) in the * interim. We check while holding the lock. If we won, we complete * init and return our conn. If we lost, we rollback and return the * other one. */ spin_lock_irqsave(&rds_conn_lock, flags); if (parent) { /* Creating passive conn */ if (parent->c_passive) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = parent->c_passive; } else { parent->c_passive = conn; rds_cong_add_conn(conn); rds_conn_count++; } } else { /* Creating normal conn */ struct rds_connection *found; if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP) found = NULL; else found = rds_conn_lookup(net, head, laddr, faddr, trans); if (found) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = found; } else { if ((is_outgoing && otrans->t_type == RDS_TRANS_TCP) || (otrans->t_type != RDS_TRANS_TCP)) { /* Only the active side should be added to * reconnect list for TCP. */ hlist_add_head_rcu(&conn->c_hash_node, head); } rds_cong_add_conn(conn); rds_conn_count++; } } spin_unlock_irqrestore(&rds_conn_lock, flags); out: return conn; } Commit Message: RDS: verify the underlying transport exists before creating a connection There was no verification that an underlying transport exists when creating a connection, this would cause dereferencing a NULL ptr. It might happen on sockets that weren't properly bound before attempting to send a message, which will cause a NULL ptr deref: [135546.047719] kasan: GPF could be caused by NULL-ptr deref or user memory accessgeneral protection fault: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC KASAN [135546.051270] Modules linked in: [135546.051781] CPU: 4 PID: 15650 Comm: trinity-c4 Not tainted 4.2.0-next-20150902-sasha-00041-gbaa1222-dirty #2527 [135546.053217] task: ffff8800835bc000 ti: ffff8800bc708000 task.ti: ffff8800bc708000 [135546.054291] RIP: __rds_conn_create (net/rds/connection.c:194) [135546.055666] RSP: 0018:ffff8800bc70fab0 EFLAGS: 00010202 [135546.056457] RAX: dffffc0000000000 RBX: 0000000000000f2c RCX: ffff8800835bc000 [135546.057494] RDX: 0000000000000007 RSI: ffff8800835bccd8 RDI: 0000000000000038 [135546.058530] RBP: ffff8800bc70fb18 R08: 0000000000000001 R09: 0000000000000000 [135546.059556] R10: ffffed014d7a3a23 R11: ffffed014d7a3a21 R12: 0000000000000000 [135546.060614] R13: 0000000000000001 R14: ffff8801ec3d0000 R15: 0000000000000000 [135546.061668] FS: 00007faad4ffb700(0000) GS:ffff880252000000(0000) knlGS:0000000000000000 [135546.062836] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b [135546.063682] CR2: 000000000000846a CR3: 000000009d137000 CR4: 00000000000006a0 [135546.064723] Stack: [135546.065048] ffffffffafe2055c ffffffffafe23fc1 ffffed00493097bf ffff8801ec3d0008 [135546.066247] 0000000000000000 00000000000000d0 0000000000000000 ac194a24c0586342 [135546.067438] 1ffff100178e1f78 ffff880320581b00 ffff8800bc70fdd0 ffff880320581b00 [135546.068629] Call Trace: [135546.069028] ? __rds_conn_create (include/linux/rcupdate.h:856 net/rds/connection.c:134) [135546.069989] ? rds_message_copy_from_user (net/rds/message.c:298) [135546.071021] rds_conn_create_outgoing (net/rds/connection.c:278) [135546.071981] rds_sendmsg (net/rds/send.c:1058) [135546.072858] ? perf_trace_lock (include/trace/events/lock.h:38) [135546.073744] ? lockdep_init (kernel/locking/lockdep.c:3298) [135546.074577] ? rds_send_drop_to (net/rds/send.c:976) [135546.075508] ? __might_fault (./arch/x86/include/asm/current.h:14 mm/memory.c:3795) [135546.076349] ? __might_fault (mm/memory.c:3795) [135546.077179] ? rds_send_drop_to (net/rds/send.c:976) [135546.078114] sock_sendmsg (net/socket.c:611 net/socket.c:620) [135546.078856] SYSC_sendto (net/socket.c:1657) [135546.079596] ? SYSC_connect (net/socket.c:1628) [135546.080510] ? trace_dump_stack (kernel/trace/trace.c:1926) [135546.081397] ? ring_buffer_unlock_commit (kernel/trace/ring_buffer.c:2479 kernel/trace/ring_buffer.c:2558 kernel/trace/ring_buffer.c:2674) [135546.082390] ? trace_buffer_unlock_commit (kernel/trace/trace.c:1749) [135546.083410] ? trace_event_raw_event_sys_enter (include/trace/events/syscalls.h:16) [135546.084481] ? do_audit_syscall_entry (include/trace/events/syscalls.h:16) [135546.085438] ? trace_buffer_unlock_commit (kernel/trace/trace.c:1749) [135546.085515] rds_ib_laddr_check(): addr 36.74.25.172 ret -99 node type -1 Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: Sasha Levin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static struct rds_connection *__rds_conn_create(struct net *net, __be32 laddr, __be32 faddr, struct rds_transport *trans, gfp_t gfp, int is_outgoing) { struct rds_connection *conn, *parent = NULL; struct hlist_head *head = rds_conn_bucket(laddr, faddr); struct rds_transport *loop_trans; unsigned long flags; int ret; struct rds_transport *otrans = trans; if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP) goto new_conn; rcu_read_lock(); conn = rds_conn_lookup(net, head, laddr, faddr, trans); if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport && laddr == faddr && !is_outgoing) { /* This is a looped back IB connection, and we're * called by the code handling the incoming connect. * We need a second connection object into which we * can stick the other QP. */ parent = conn; conn = parent->c_passive; } rcu_read_unlock(); if (conn) goto out; new_conn: conn = kmem_cache_zalloc(rds_conn_slab, gfp); if (!conn) { conn = ERR_PTR(-ENOMEM); goto out; } INIT_HLIST_NODE(&conn->c_hash_node); conn->c_laddr = laddr; conn->c_faddr = faddr; spin_lock_init(&conn->c_lock); conn->c_next_tx_seq = 1; rds_conn_net_set(conn, net); init_waitqueue_head(&conn->c_waitq); INIT_LIST_HEAD(&conn->c_send_queue); INIT_LIST_HEAD(&conn->c_retrans); ret = rds_cong_get_maps(conn); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } /* * This is where a connection becomes loopback. If *any* RDS sockets * can bind to the destination address then we'd rather the messages * flow through loopback rather than either transport. */ loop_trans = rds_trans_get_preferred(net, faddr); if (loop_trans) { rds_trans_put(loop_trans); conn->c_loopback = 1; if (is_outgoing && trans->t_prefer_loopback) { /* "outgoing" connection - and the transport * says it wants the connection handled by the * loopback transport. This is what TCP does. */ trans = &rds_loop_transport; } } if (trans == NULL) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(-ENODEV); goto out; } conn->c_trans = trans; ret = trans->conn_alloc(conn, gfp); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } atomic_set(&conn->c_state, RDS_CONN_DOWN); conn->c_send_gen = 0; conn->c_reconnect_jiffies = 0; INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker); INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker); INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker); INIT_WORK(&conn->c_down_w, rds_shutdown_worker); mutex_init(&conn->c_cm_lock); conn->c_flags = 0; rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n", conn, &laddr, &faddr, trans->t_name ? trans->t_name : "[unknown]", is_outgoing ? "(outgoing)" : ""); /* * Since we ran without holding the conn lock, someone could * have created the same conn (either normal or passive) in the * interim. We check while holding the lock. If we won, we complete * init and return our conn. If we lost, we rollback and return the * other one. */ spin_lock_irqsave(&rds_conn_lock, flags); if (parent) { /* Creating passive conn */ if (parent->c_passive) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = parent->c_passive; } else { parent->c_passive = conn; rds_cong_add_conn(conn); rds_conn_count++; } } else { /* Creating normal conn */ struct rds_connection *found; if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP) found = NULL; else found = rds_conn_lookup(net, head, laddr, faddr, trans); if (found) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = found; } else { if ((is_outgoing && otrans->t_type == RDS_TRANS_TCP) || (otrans->t_type != RDS_TRANS_TCP)) { /* Only the active side should be added to * reconnect list for TCP. */ hlist_add_head_rcu(&conn->c_hash_node, head); } rds_cong_add_conn(conn); rds_conn_count++; } } spin_unlock_irqrestore(&rds_conn_lock, flags); out: return conn; }
166,583
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector, grub_off_t offset, grub_size_t size, void *buf) { char *tmp_buf; unsigned real_offset; /* First of all, check if the region is within the disk. */ if (grub_disk_adjust_range (disk, &sector, &offset, size) != GRUB_ERR_NONE) { grub_error_push (); grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n", (unsigned long long) sector, grub_errmsg); grub_error_pop (); return grub_errno; } real_offset = offset; /* Allocate a temporary buffer. */ tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS); if (! tmp_buf) return grub_errno; /* Until SIZE is zero... */ while (size) { char *data; grub_disk_addr_t start_sector; grub_size_t len; grub_size_t pos; /* For reading bulk data. */ start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1); pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS; len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS) - pos - real_offset); if (len > size) len = size; /* Fetch the cache. */ data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector); if (data) { /* Just copy it! */ if (buf) grub_memcpy (buf, data + pos + real_offset, len); grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector); } else { /* Otherwise read data from the disk actually. */ if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors || (disk->dev->read) (disk, start_sector, GRUB_DISK_CACHE_SIZE, tmp_buf) != GRUB_ERR_NONE) { /* Uggh... Failed. Instead, just read necessary data. */ unsigned num; char *p; grub_errno = GRUB_ERR_NONE; num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1) >> GRUB_DISK_SECTOR_BITS); p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS); if (!p) goto finish; tmp_buf = p; if ((disk->dev->read) (disk, sector, num, tmp_buf)) { grub_error_push (); grub_dprintf ("disk", "%s read failed\n", disk->name); grub_error_pop (); goto finish; } if (buf) grub_memcpy (buf, tmp_buf + real_offset, size); /* Call the read hook, if any. */ if (disk->read_hook) while (size) { grub_size_t to_read; to_read = size; if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE) to_read = GRUB_DISK_SECTOR_SIZE - real_offset; (disk->read_hook) (sector, real_offset, to_read, disk->closure); if (grub_errno != GRUB_ERR_NONE) goto finish; sector++; size -= to_read; real_offset = 0; } /* This must be the end. */ goto finish; } /* Copy it and store it in the disk cache. */ if (buf) grub_memcpy (buf, tmp_buf + pos + real_offset, len); grub_disk_cache_store (disk->dev->id, disk->id, start_sector, tmp_buf); } /* Call the read hook, if any. */ if (disk->read_hook) { grub_disk_addr_t s = sector; grub_size_t l = len; while (l) { (disk->read_hook) (s, real_offset, ((l > GRUB_DISK_SECTOR_SIZE) ? GRUB_DISK_SECTOR_SIZE : l), disk->closure); if (l < GRUB_DISK_SECTOR_SIZE - real_offset) break; s++; l -= GRUB_DISK_SECTOR_SIZE - real_offset; real_offset = 0; } } sector = start_sector + GRUB_DISK_CACHE_SIZE; if (buf) buf = (char *) buf + len; size -= len; real_offset = 0; } finish: grub_free (tmp_buf); return grub_errno; } Commit Message: Fix r2_hbo_grub_memmove ext2 crash CWE ID: CWE-119
grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector, grub_off_t offset, grub_size_t size, void *buf) { char *tmp_buf; unsigned real_offset; /* First of all, check if the region is within the disk. */ if (grub_disk_adjust_range (disk, &sector, &offset, size) != GRUB_ERR_NONE) { grub_error_push (); grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n", (unsigned long long) sector, grub_errmsg); grub_error_pop (); return grub_errno; } real_offset = offset; /* Allocate a temporary buffer. */ tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS); if (! tmp_buf) return grub_errno; /* Until SIZE is zero... */ while (size) { char *data; grub_disk_addr_t start_sector; grub_size_t len; grub_size_t pos; /* For reading bulk data. */ start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1); pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS; len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS) - pos - real_offset); if (len > size) len = size; /* Fetch the cache. */ data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector); if (data) { /* Just copy it! */ if (buf) { if (pos + real_offset + len >= size) { // prevent read overflow grub_errno = GRUB_ERR_BAD_FS; return grub_errno; } grub_memcpy (buf, data + pos + real_offset, len); } grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector); } else { /* Otherwise read data from the disk actually. */ if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors || (disk->dev->read) (disk, start_sector, GRUB_DISK_CACHE_SIZE, tmp_buf) != GRUB_ERR_NONE) { /* Uggh... Failed. Instead, just read necessary data. */ unsigned num; char *p; grub_errno = GRUB_ERR_NONE; num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1) >> GRUB_DISK_SECTOR_BITS); p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS); if (!p) goto finish; tmp_buf = p; if ((disk->dev->read) (disk, sector, num, tmp_buf)) { grub_error_push (); grub_dprintf ("disk", "%s read failed\n", disk->name); grub_error_pop (); goto finish; } if (buf) grub_memcpy (buf, tmp_buf + real_offset, size); /* Call the read hook, if any. */ if (disk->read_hook) while (size) { grub_size_t to_read; to_read = size; if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE) to_read = GRUB_DISK_SECTOR_SIZE - real_offset; (disk->read_hook) (sector, real_offset, to_read, disk->closure); if (grub_errno != GRUB_ERR_NONE) goto finish; sector++; size -= to_read; real_offset = 0; } /* This must be the end. */ goto finish; } /* Copy it and store it in the disk cache. */ if (buf) grub_memcpy (buf, tmp_buf + pos + real_offset, len); grub_disk_cache_store (disk->dev->id, disk->id, start_sector, tmp_buf); } /* Call the read hook, if any. */ if (disk->read_hook) { grub_disk_addr_t s = sector; grub_size_t l = len; while (l) { (disk->read_hook) (s, real_offset, ((l > GRUB_DISK_SECTOR_SIZE) ? GRUB_DISK_SECTOR_SIZE : l), disk->closure); if (l < GRUB_DISK_SECTOR_SIZE - real_offset) break; s++; l -= GRUB_DISK_SECTOR_SIZE - real_offset; real_offset = 0; } } sector = start_sector + GRUB_DISK_CACHE_SIZE; if (buf) buf = (char *) buf + len; size -= len; real_offset = 0; } finish: grub_free (tmp_buf); return grub_errno; }
168,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; } Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read. As reported here: https://jira.mongodb.org/browse/CDRIVER-2819, a heap overread occurs due a failure to correctly verify data bounds. In the original check, len - o returns the data left including the sizeof(l) we just read. Instead, the comparison should check against the data left NOT including the binary int32, i.e. just subtype (byte*) instead of int32 subtype (byte*). Added in test for corrupted BSON example. CWE ID: CWE-125
_bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o - 4)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; }
169,032
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadMTVImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent]; Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; unsigned char *pixels; unsigned long columns, rows; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MTV image. */ (void) ReadBlobString(image,buffer); count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows); if (count <= 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=columns; image->rows=rows; image->depth=8; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Convert MTV raster image to pixel packets. */ pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns, 3UL*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { count=(ssize_t) ReadBlob(image,(size_t) (3*image->columns),pixels); if (count != (ssize_t) (3*image->columns)) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *buffer='\0'; (void) ReadBlobString(image,buffer); count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows); if (count > 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (count > 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadMTVImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent]; Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; unsigned char *pixels; unsigned long columns, rows; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MTV image. */ (void) ReadBlobString(image,buffer); count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows); if (count <= 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=columns; image->rows=rows; image->depth=8; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert MTV raster image to pixel packets. */ pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns, 3UL*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { count=(ssize_t) ReadBlob(image,(size_t) (3*image->columns),pixels); if (count != (ssize_t) (3*image->columns)) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *buffer='\0'; (void) ReadBlobString(image,buffer); count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows); if (count > 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (count > 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,584
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMP3::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSamplingRate; return OMX_ErrorNone; } case OMX_IndexParamAudioMp3: { OMX_AUDIO_PARAM_MP3TYPE *mp3Params = (OMX_AUDIO_PARAM_MP3TYPE *)params; if (mp3Params->nPortIndex > 1) { return OMX_ErrorUndefined; } mp3Params->nChannels = mNumChannels; mp3Params->nBitRate = 0 /* unknown */; mp3Params->nSampleRate = mSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftMP3::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSamplingRate; return OMX_ErrorNone; } case OMX_IndexParamAudioMp3: { OMX_AUDIO_PARAM_MP3TYPE *mp3Params = (OMX_AUDIO_PARAM_MP3TYPE *)params; if (!isValidOMXParam(mp3Params)) { return OMX_ErrorBadParameter; } if (mp3Params->nPortIndex > 1) { return OMX_ErrorUndefined; } mp3Params->nChannels = mNumChannels; mp3Params->nBitRate = 0 /* unknown */; mp3Params->nSampleRate = mSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int atusb_get_and_show_build(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; char build[ATUSB_BUILD_SIZE + 1]; int ret; ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_BUILD, ATUSB_REQ_FROM_DEV, 0, 0, build, ATUSB_BUILD_SIZE, 1000); if (ret >= 0) { build[ret] = 0; dev_info(&usb_dev->dev, "Firmware: build %s\n", build); } return ret; } Commit Message: ieee802154: atusb: do not use the stack for buffers to make them DMA able From 4.9 we should really avoid using the stack here as this will not be DMA able on various platforms. This changes the buffers already being present in time of 4.9 being released. This should go into stable as well. Reported-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Stefan Schmidt <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-119
static int atusb_get_and_show_build(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; char *build; int ret; build = kmalloc(ATUSB_BUILD_SIZE + 1, GFP_KERNEL); if (!build) return -ENOMEM; ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_BUILD, ATUSB_REQ_FROM_DEV, 0, 0, build, ATUSB_BUILD_SIZE, 1000); if (ret >= 0) { build[ret] = 0; dev_info(&usb_dev->dev, "Firmware: build %s\n", build); } kfree(build); return ret; }
168,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::string16 GetRelyingPartyIdString( AuthenticatorRequestDialogModel* dialog_model) { static constexpr char kRpIdUrlPrefix[] = "https://"; static constexpr int kDialogWidth = 300; const auto& rp_id = dialog_model->relying_party_id(); DCHECK(!rp_id.empty()); GURL rp_id_url(kRpIdUrlPrefix + rp_id); auto max_static_string_length = gfx::GetStringWidthF( l10n_util::GetStringUTF16(IDS_WEBAUTHN_GENERIC_TITLE), gfx::FontList(), gfx::Typesetter::DEFAULT); return url_formatter::ElideHost(rp_id_url, gfx::FontList(), kDialogWidth - max_static_string_length); } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} CWE ID: CWE-119
base::string16 GetRelyingPartyIdString( AuthenticatorRequestDialogModel* dialog_model) { static constexpr char kRpIdUrlPrefix[] = "https://"; static constexpr int kDialogWidth = 300; const auto& rp_id = dialog_model->relying_party_id(); DCHECK(!rp_id.empty()); GURL rp_id_url(kRpIdUrlPrefix + rp_id); return url_formatter::ElideHost(rp_id_url, gfx::FontList(), kDialogWidth); }
172,561
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; } Commit Message: l2tp: fix info leak via getsockname() The L2TP code for IPv6 fails to initialize the l2tp_unused member of struct sockaddr_l2tpip6 and that for leaks two bytes kernel stack via the getsockname() syscall. Initialize l2tp_unused with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: James Chapman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_unused = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; }
166,183
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() { if (texture_holder_->IsSkiaTextureHolder()) return; texture_holder_ = std::make_unique<SkiaTextureHolder>(std::move(texture_holder_)); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (texture_holder_->IsSkiaTextureHolder()) return; texture_holder_ = std::make_unique<SkiaTextureHolder>(std::move(texture_holder_)); }
172,592
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PopupContainer::refresh(const IntRect& targetControlRect) { IntPoint location = m_frameView->contentsToWindow(targetControlRect.location()); location.move(0, targetControlRect.height()); listBox()->setBaseWidth(max(m_originalFrameRect.width() - kBorderSize * 2, 0)); listBox()->updateFromElement(); IntSize originalSize = size(); IntRect widgetRect = layoutAndCalculateWidgetRect(targetControlRect.height(), location); if (originalSize != widgetRect.size()) { ChromeClientChromium* chromeClient = chromeClientChromium(); if (chromeClient) { IntPoint widgetLocation = chromeClient->screenToRootView(widgetRect.location()); widgetRect.setLocation(widgetLocation); setFrameRect(widgetRect); } } invalidate(); } Commit Message: [REGRESSION] Refreshed autofill popup renders garbage https://bugs.webkit.org/show_bug.cgi?id=83255 http://code.google.com/p/chromium/issues/detail?id=118374 The code used to update only the PopupContainer coordinates as if they were the coordinates relative to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer, so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's location should be (0, 0) (and their sizes should always be equal). Reviewed by Kent Tamura. No new tests, as the popup appearance is not testable in WebKit. * platform/chromium/PopupContainer.cpp: (WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed. (WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect() for passing into chromeClient. (WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container. (WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly. * platform/chromium/PopupContainer.h: (PopupContainer): git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void PopupContainer::refresh(const IntRect& targetControlRect) { listBox()->setBaseWidth(max(m_originalFrameRect.width() - kBorderSize * 2, 0)); listBox()->updateFromElement(); IntPoint locationInWindow = m_frameView->contentsToWindow(targetControlRect.location()); locationInWindow.move(0, targetControlRect.height()); IntRect widgetRectInScreen = layoutAndCalculateWidgetRect(targetControlRect.height(), locationInWindow); // Reset the size (which can be set to the PopupListBox size in layoutAndGetRTLOffset(), exceeding the available widget rectangle.) if (size() != widgetRectInScreen.size()) resize(widgetRectInScreen.size()); ChromeClientChromium* chromeClient = chromeClientChromium(); if (chromeClient) { // Update the WebWidget location (which is relative to the screen origin). if (widgetRectInScreen != chromeClient->windowRect()) chromeClient->setWindowRect(widgetRectInScreen); } invalidate(); }
171,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next) { File* file = V8File::toNative(value.As<v8::Object>()); if (!file) return 0; if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.add(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(blobIndex >= 0); m_writer.writeFileIndex(blobIndex); } else { m_writer.writeFile(*file); } return 0; } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 [email protected] Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next) { File* file = V8File::toNative(value.As<v8::Object>()); if (!file) return 0; if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.set(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(blobIndex >= 0); m_writer.writeFileIndex(blobIndex); } else { m_writer.writeFile(*file); } return 0; }
171,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; mutex_lock(&tu->tread_sem); if (tu->timeri) { /* too late */ mutex_unlock(&tu->tread_sem); return -EBUSY; } if (get_user(xarg, p)) { mutex_unlock(&tu->tread_sem); return -EFAULT; } tu->tread = xarg ? 1 : 0; mutex_unlock(&tu->tread_sem); return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; } Commit Message: ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; if (tu->timeri) /* too late */ return -EBUSY; if (get_user(xarg, p)) return -EFAULT; tu->tread = xarg ? 1 : 0; return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; }
167,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long AudioTrack::GetBitDepth() const { return m_bitDepth; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long AudioTrack::GetBitDepth() const
174,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/663 https://github.com/ImageMagick/ImageMagick/issues/655 CWE ID: CWE-119
MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); }
167,964
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebGL2RenderingContextBase::deleteVertexArray( WebGLVertexArrayObject* vertex_array) { if (isContextLost() || !vertex_array) return; if (!vertex_array->IsDefaultObject() && vertex_array == bound_vertex_array_object_) SetBoundVertexArrayObject(nullptr); vertex_array->DeleteObject(ContextGL()); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#565016} CWE ID: CWE-119
void WebGL2RenderingContextBase::deleteVertexArray( WebGLVertexArrayObject* vertex_array) { if (isContextLost() || !vertex_array || !ValidateWebGLObject("deleteVertexArray", vertex_array)) return; if (!vertex_array->IsDefaultObject() && vertex_array == bound_vertex_array_object_) SetBoundVertexArrayObject(nullptr); vertex_array->DeleteObject(ContextGL()); }
173,124
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; size_t newsize; switch(option) { case PHP_STREAM_OPTION_TRUNCATE_API: switch (value) { case PHP_STREAM_TRUNCATE_SUPPORTED: return PHP_STREAM_OPTION_RETURN_OK; case PHP_STREAM_TRUNCATE_SET_SIZE: if (ms->mode & TEMP_STREAM_READONLY) { return PHP_STREAM_OPTION_RETURN_ERR; } newsize = *(size_t*)ptrparam; if (newsize <= ms->fsize) { if (newsize < ms->fpos) { ms->fpos = newsize; } } else { ms->data = erealloc(ms->data, newsize); memset(ms->data+ms->fsize, 0, newsize - ms->fsize); ms->fsize = newsize; } ms->fsize = newsize; return PHP_STREAM_OPTION_RETURN_OK; } default: return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */ Commit Message: CWE ID: CWE-20
static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; size_t newsize; switch(option) { case PHP_STREAM_OPTION_TRUNCATE_API: switch (value) { case PHP_STREAM_TRUNCATE_SUPPORTED: return PHP_STREAM_OPTION_RETURN_OK; case PHP_STREAM_TRUNCATE_SET_SIZE: if (ms->mode & TEMP_STREAM_READONLY) { return PHP_STREAM_OPTION_RETURN_ERR; } newsize = *(size_t*)ptrparam; if (newsize <= ms->fsize) { if (newsize < ms->fpos) { ms->fpos = newsize; } } else { ms->data = erealloc(ms->data, newsize); memset(ms->data+ms->fsize, 0, newsize - ms->fsize); ms->fsize = newsize; } ms->fsize = newsize; return PHP_STREAM_OPTION_RETURN_OK; } default: return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */
165,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void unix_release_sock(struct sock *sk, int embrion) { struct unix_sock *u = unix_sk(sk); struct path path; struct sock *skpair; struct sk_buff *skb; int state; unix_remove_socket(sk); /* Clear state */ unix_state_lock(sk); sock_orphan(sk); sk->sk_shutdown = SHUTDOWN_MASK; path = u->path; u->path.dentry = NULL; u->path.mnt = NULL; state = sk->sk_state; sk->sk_state = TCP_CLOSE; unix_state_unlock(sk); wake_up_interruptible_all(&u->peer_wait); skpair = unix_peer(sk); if (skpair != NULL) { if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) { unix_state_lock(skpair); /* No more writes */ skpair->sk_shutdown = SHUTDOWN_MASK; if (!skb_queue_empty(&sk->sk_receive_queue) || embrion) skpair->sk_err = ECONNRESET; unix_state_unlock(skpair); skpair->sk_state_change(skpair); sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP); } sock_put(skpair); /* It may now die */ unix_peer(sk) = NULL; } /* Try to flush out this socket. Throw out buffers at least */ while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { if (state == TCP_LISTEN) unix_release_sock(skb->sk, 1); /* passed fds are erased in the kfree_skb hook */ UNIXCB(skb).consumed = skb->len; kfree_skb(skb); } if (path.dentry) path_put(&path); sock_put(sk); /* ---- Socket is dead now and most probably destroyed ---- */ /* * Fixme: BSD difference: In BSD all sockets connected to us get * ECONNRESET and we die on the spot. In Linux we behave * like files and pipes do and wait for the last * dereference. * * Can't we simply set sock->err? * * What the above comment does talk about? --ANK(980817) */ if (unix_tot_inflight) unix_gc(); /* Garbage collect fds */ } Commit Message: unix: avoid use-after-free in ep_remove_wait_queue Rainer Weikusat <[email protected]> writes: An AF_UNIX datagram socket being the client in an n:1 association with some server socket is only allowed to send messages to the server if the receive queue of this socket contains at most sk_max_ack_backlog datagrams. This implies that prospective writers might be forced to go to sleep despite none of the message presently enqueued on the server receive queue were sent by them. In order to ensure that these will be woken up once space becomes again available, the present unix_dgram_poll routine does a second sock_poll_wait call with the peer_wait wait queue of the server socket as queue argument (unix_dgram_recvmsg does a wake up on this queue after a datagram was received). This is inherently problematic because the server socket is only guaranteed to remain alive for as long as the client still holds a reference to it. In case the connection is dissolved via connect or by the dead peer detection logic in unix_dgram_sendmsg, the server socket may be freed despite "the polling mechanism" (in particular, epoll) still has a pointer to the corresponding peer_wait queue. There's no way to forcibly deregister a wait queue with epoll. Based on an idea by Jason Baron, the patch below changes the code such that a wait_queue_t belonging to the client socket is enqueued on the peer_wait queue of the server whenever the peer receive queue full condition is detected by either a sendmsg or a poll. A wake up on the peer queue is then relayed to the ordinary wait queue of the client socket via wake function. The connection to the peer wait queue is again dissolved if either a wake up is about to be relayed or the client socket reconnects or a dead peer is detected or the client socket is itself closed. This enables removing the second sock_poll_wait from unix_dgram_poll, thus avoiding the use-after-free, while still ensuring that no blocked writer sleeps forever. Signed-off-by: Rainer Weikusat <[email protected]> Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets") Reviewed-by: Jason Baron <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static void unix_release_sock(struct sock *sk, int embrion) { struct unix_sock *u = unix_sk(sk); struct path path; struct sock *skpair; struct sk_buff *skb; int state; unix_remove_socket(sk); /* Clear state */ unix_state_lock(sk); sock_orphan(sk); sk->sk_shutdown = SHUTDOWN_MASK; path = u->path; u->path.dentry = NULL; u->path.mnt = NULL; state = sk->sk_state; sk->sk_state = TCP_CLOSE; unix_state_unlock(sk); wake_up_interruptible_all(&u->peer_wait); skpair = unix_peer(sk); if (skpair != NULL) { if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) { unix_state_lock(skpair); /* No more writes */ skpair->sk_shutdown = SHUTDOWN_MASK; if (!skb_queue_empty(&sk->sk_receive_queue) || embrion) skpair->sk_err = ECONNRESET; unix_state_unlock(skpair); skpair->sk_state_change(skpair); sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP); } unix_dgram_peer_wake_disconnect(sk, skpair); sock_put(skpair); /* It may now die */ unix_peer(sk) = NULL; } /* Try to flush out this socket. Throw out buffers at least */ while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { if (state == TCP_LISTEN) unix_release_sock(skb->sk, 1); /* passed fds are erased in the kfree_skb hook */ UNIXCB(skb).consumed = skb->len; kfree_skb(skb); } if (path.dentry) path_put(&path); sock_put(sk); /* ---- Socket is dead now and most probably destroyed ---- */ /* * Fixme: BSD difference: In BSD all sockets connected to us get * ECONNRESET and we die on the spot. In Linux we behave * like files and pipes do and wait for the last * dereference. * * Can't we simply set sock->err? * * What the above comment does talk about? --ANK(980817) */ if (unix_tot_inflight) unix_gc(); /* Garbage collect fds */ }
166,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen, int prediction_resistance, const unsigned char *adin, size_t adinlen) { int reseed_required = 0; if (drbg->state != DRBG_READY) { rand_drbg_restart(drbg, NULL, 0, 0); if (drbg->state == DRBG_ERROR) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE); return 0; } if (drbg->state == DRBG_UNINITIALISED) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED); return 0; } } if (outlen > drbg->max_request) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG); return 0; } if (adinlen > drbg->max_adinlen) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG); return 0; return 0; } if (drbg->fork_count != rand_fork_count) { drbg->fork_count = rand_fork_count; reseed_required = 1; } } Commit Message: CWE ID: CWE-330
int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen, int prediction_resistance, const unsigned char *adin, size_t adinlen) { int fork_id; int reseed_required = 0; if (drbg->state != DRBG_READY) { rand_drbg_restart(drbg, NULL, 0, 0); if (drbg->state == DRBG_ERROR) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE); return 0; } if (drbg->state == DRBG_UNINITIALISED) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED); return 0; } } if (outlen > drbg->max_request) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG); return 0; } if (adinlen > drbg->max_adinlen) { RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG); return 0; return 0; } fork_id = openssl_get_fork_id(); if (drbg->fork_id != fork_id) { drbg->fork_id = fork_id; reseed_required = 1; } }
165,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderBox::styleDidChange(diff, oldStyle); RenderStyle* newStyle = style(); if (!isAnonymousBlock()) { for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) { RenderBoxModelObject* nextCont = currCont->continuation(); currCont->setContinuation(0); currCont->setStyle(newStyle); currCont->setContinuation(nextCont); } } if (FastTextAutosizer* textAutosizer = document().fastTextAutosizer()) textAutosizer->record(this); propagateStyleToAnonymousChildren(true); invalidateLineHeight(); m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle); Vector<ImageResource*> images; appendImagesFromStyle(images, *newStyle); if (images.isEmpty()) ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this); else ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderBox::styleDidChange(diff, oldStyle); RenderStyle* newStyle = style(); if (!isAnonymousBlock()) { for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) { RenderBoxModelObject* nextCont = currCont->continuation(); currCont->setContinuation(0); currCont->setStyle(newStyle); currCont->setContinuation(nextCont); } } if (FastTextAutosizer* textAutosizer = document().fastTextAutosizer()) textAutosizer->record(this); propagateStyleToAnonymousChildren(true); invalidateLineHeight(); m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff.needsFullLayout() && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle); Vector<ImageResource*> images; appendImagesFromStyle(images, *newStyle); if (images.isEmpty()) ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this); else ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this); }
171,460
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScopedRequest(PepperDeviceEnumerationHostHelper* owner, const Delegate::EnumerateDevicesCallback& callback) : owner_(owner), callback_(callback), requested_(false), request_id_(0), sync_call_(false) { if (!owner_->document_url_.is_valid()) return; requested_ = true; sync_call_ = true; request_id_ = owner_->delegate_->EnumerateDevices( owner_->device_type_, owner_->document_url_, base::Bind(&ScopedRequest::EnumerateDevicesCallbackBody, AsWeakPtr())); sync_call_ = false; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
ScopedRequest(PepperDeviceEnumerationHostHelper* owner, const Delegate::EnumerateDevicesCallback& callback) : owner_(owner), callback_(callback), requested_(false), request_id_(0), sync_call_(false) { if (!owner_->document_url_.is_valid()) return; requested_ = true; sync_call_ = true; DCHECK(owner_->delegate_); request_id_ = owner_->delegate_->EnumerateDevices( owner_->device_type_, owner_->document_url_, base::Bind(&ScopedRequest::EnumerateDevicesCallbackBody, AsWeakPtr())); sync_call_ = false; }
171,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else tty_encode_baud_rate(tty, baud, baud); edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); } Commit Message: USB: serial: io_ti: fix div-by-zero in set_termios Fix a division-by-zero in set_termios when debugging is enabled and a high-enough speed has been requested so that the divisor value becomes zero. Instead of just fixing the offending debug statement, cap the baud rate at the base as a zero divisor value also appears to crash the firmware. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <[email protected]> # 2.6.12 Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-369
static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else { /* Avoid a zero divisor. */ baud = min(baud, 461550); tty_encode_baud_rate(tty, baud, baud); } edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); }
169,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __kprobes perf_event_nmi_handler(struct notifier_block *self, unsigned long cmd, void *__args) { struct die_args *args = __args; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int i; if (!atomic_read(&active_events)) return NOTIFY_DONE; switch (cmd) { case DIE_NMI: break; default: return NOTIFY_DONE; } regs = args->regs; perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); /* If the PMU has the TOE IRQ enable bits, we need to do a * dummy write to the %pcr to clear the overflow bits and thus * the interrupt. * * Do this before we peek at the counters to determine * overflow so we don't lose any events. */ if (sparc_pmu->irq_bit) pcr_ops->write(cpuc->pcr); for (i = 0; i < cpuc->n_events; i++) { struct perf_event *event = cpuc->event[i]; int idx = cpuc->current_idx[i]; struct hw_perf_event *hwc; u64 val; hwc = &event->hw; val = sparc_perf_event_update(event, hwc, idx); if (val & (1ULL << 31)) continue; data.period = event->hw.last_period; if (!sparc_perf_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, 1, &data, regs)) sparc_pmu_stop(event, 0); } return NOTIFY_STOP; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static int __kprobes perf_event_nmi_handler(struct notifier_block *self, unsigned long cmd, void *__args) { struct die_args *args = __args; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int i; if (!atomic_read(&active_events)) return NOTIFY_DONE; switch (cmd) { case DIE_NMI: break; default: return NOTIFY_DONE; } regs = args->regs; perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); /* If the PMU has the TOE IRQ enable bits, we need to do a * dummy write to the %pcr to clear the overflow bits and thus * the interrupt. * * Do this before we peek at the counters to determine * overflow so we don't lose any events. */ if (sparc_pmu->irq_bit) pcr_ops->write(cpuc->pcr); for (i = 0; i < cpuc->n_events; i++) { struct perf_event *event = cpuc->event[i]; int idx = cpuc->current_idx[i]; struct hw_perf_event *hwc; u64 val; hwc = &event->hw; val = sparc_perf_event_update(event, hwc, idx); if (val & (1ULL << 31)) continue; data.period = event->hw.last_period; if (!sparc_perf_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, &data, regs)) sparc_pmu_stop(event, 0); } return NOTIFY_STOP; }
165,804
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); }
166,985
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GeometryMapper::SourceToDestinationProjectionInternal( const TransformPaintPropertyNode* source, const TransformPaintPropertyNode* destination, bool& success) { DCHECK(source && destination); DEFINE_STATIC_LOCAL(TransformationMatrix, identity, (TransformationMatrix())); DEFINE_STATIC_LOCAL(TransformationMatrix, temp, (TransformationMatrix())); if (source == destination) { success = true; return identity; } const GeometryMapperTransformCache& source_cache = source->GetTransformCache(); const GeometryMapperTransformCache& destination_cache = destination->GetTransformCache(); if (source_cache.plane_root() == destination_cache.plane_root()) { success = true; if (source == destination_cache.plane_root()) return destination_cache.from_plane_root(); if (destination == source_cache.plane_root()) return source_cache.to_plane_root(); temp = destination_cache.from_plane_root(); temp.Multiply(source_cache.to_plane_root()); return temp; } if (!destination_cache.projection_from_screen_is_valid()) { success = false; return identity; } const auto* root = TransformPaintPropertyNode::Root(); success = true; if (source == root) return destination_cache.projection_from_screen(); if (destination == root) { temp = source_cache.to_screen(); } else { temp = destination_cache.projection_from_screen(); temp.Multiply(source_cache.to_screen()); } temp.FlattenTo2d(); return temp; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
GeometryMapper::SourceToDestinationProjectionInternal( const TransformPaintPropertyNode* source, const TransformPaintPropertyNode* destination, bool& success) { DCHECK(source && destination); DEFINE_STATIC_LOCAL(TransformationMatrix, identity, (TransformationMatrix())); DEFINE_STATIC_LOCAL(TransformationMatrix, temp, (TransformationMatrix())); if (source == destination) { success = true; return identity; } const GeometryMapperTransformCache& source_cache = source->GetTransformCache(); const GeometryMapperTransformCache& destination_cache = destination->GetTransformCache(); if (source_cache.plane_root() == destination_cache.plane_root()) { success = true; if (source == destination_cache.plane_root()) return destination_cache.from_plane_root(); if (destination == source_cache.plane_root()) return source_cache.to_plane_root(); temp = destination_cache.from_plane_root(); temp.Multiply(source_cache.to_plane_root()); return temp; } if (!destination_cache.projection_from_screen_is_valid()) { success = false; return identity; } const auto* root = &TransformPaintPropertyNode::Root(); success = true; if (source == root) return destination_cache.projection_from_screen(); if (destination == root) { temp = source_cache.to_screen(); } else { temp = destination_cache.projection_from_screen(); temp.Multiply(source_cache.to_screen()); } temp.FlattenTo2d(); return temp; }
171,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb) { struct ipcm_cookie ipc; struct rtable *rt = skb_rtable(skb); struct net *net = dev_net(rt->dst.dev); struct sock *sk; struct inet_sock *inet; __be32 daddr; if (ip_options_echo(&icmp_param->replyopts, skb)) return; sk = icmp_xmit_lock(net); if (sk == NULL) return; inet = inet_sk(sk); icmp_param->data.icmph.checksum = 0; inet->tos = ip_hdr(skb)->tos; daddr = ipc.addr = rt->rt_src; ipc.opt = NULL; ipc.tx_flags = 0; if (icmp_param->replyopts.optlen) { ipc.opt = &icmp_param->replyopts; if (ipc.opt->srr) daddr = icmp_param->replyopts.faddr; } { struct flowi4 fl4 = { .daddr = daddr, .saddr = rt->rt_spec_dst, .flowi4_tos = RT_TOS(ip_hdr(skb)->tos), .flowi4_proto = IPPROTO_ICMP, }; security_skb_classify_flow(skb, flowi4_to_flowi(&fl4)); rt = ip_route_output_key(net, &fl4); if (IS_ERR(rt)) goto out_unlock; } if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type, icmp_param->data.icmph.code)) icmp_push_reply(icmp_param, &ipc, &rt); ip_rt_put(rt); out_unlock: icmp_xmit_unlock(sk); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb) { struct ipcm_cookie ipc; struct rtable *rt = skb_rtable(skb); struct net *net = dev_net(rt->dst.dev); struct sock *sk; struct inet_sock *inet; __be32 daddr; if (ip_options_echo(&icmp_param->replyopts.opt.opt, skb)) return; sk = icmp_xmit_lock(net); if (sk == NULL) return; inet = inet_sk(sk); icmp_param->data.icmph.checksum = 0; inet->tos = ip_hdr(skb)->tos; daddr = ipc.addr = rt->rt_src; ipc.opt = NULL; ipc.tx_flags = 0; if (icmp_param->replyopts.opt.opt.optlen) { ipc.opt = &icmp_param->replyopts.opt; if (ipc.opt->opt.srr) daddr = icmp_param->replyopts.opt.opt.faddr; } { struct flowi4 fl4 = { .daddr = daddr, .saddr = rt->rt_spec_dst, .flowi4_tos = RT_TOS(ip_hdr(skb)->tos), .flowi4_proto = IPPROTO_ICMP, }; security_skb_classify_flow(skb, flowi4_to_flowi(&fl4)); rt = ip_route_output_key(net, &fl4); if (IS_ERR(rt)) goto out_unlock; } if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type, icmp_param->data.icmph.code)) icmp_push_reply(icmp_param, &ipc, &rt); ip_rt_put(rt); out_unlock: icmp_xmit_unlock(sk); }
165,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y]); } } } Commit Message: Fix seven bugs discovered and fixed by ForAllSecure: CVE-2019-13217: heap buffer overflow in start_decoder() CVE-2019-13218: stack buffer overflow in compute_codewords() CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest() CVE-2019-13220: out-of-range read in draw_line() CVE-2019-13221: issue with large 1D codebooks in lookup1_values() CVE-2019-13222: unchecked NULL returned by get_window() CVE-2019-13223: division by zero in predict_point() CWE ID: CWE-20
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y&255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y&255]); } } }
169,614
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAACEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAACEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_encoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)params); } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (avcType->nPortIndex != 1) { return OMX_ErrorUndefined; } mEntropyMode = 0; if (OMX_TRUE == avcType->bEntropyCodingCABAC) mEntropyMode = 1; if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) && avcType->nPFrames) { mBframes = avcType->nBFrames / avcType->nPFrames; } mIInterval = avcType->nPFrames + avcType->nBFrames; if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode) mDisableDeblkLevel = 4; if (avcType->nRefFrames != 1 || avcType->bUseHadamard != OMX_TRUE || avcType->nRefIdx10ActiveMinus1 != 0 || avcType->nRefIdx11ActiveMinus1 != 0 || avcType->bWeightedPPrediction != OMX_FALSE || avcType->bconstIpred != OMX_FALSE || avcType->bDirect8x8Inference != OMX_FALSE || avcType->bDirectSpatialTemporal != OMX_FALSE || avcType->nCabacInitIdc != 0) { return OMX_ErrorUndefined; } if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *)params; if (!isValidOMXParam(bitRate)) { return OMX_ErrorBadParameter; } return internalSetBitrateParams(bitRate); } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (!isValidOMXParam(avcType)) { return OMX_ErrorBadParameter; } if (avcType->nPortIndex != 1) { return OMX_ErrorUndefined; } mEntropyMode = 0; if (OMX_TRUE == avcType->bEntropyCodingCABAC) mEntropyMode = 1; if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) && avcType->nPFrames) { mBframes = avcType->nBFrames / avcType->nPFrames; } mIInterval = avcType->nPFrames + avcType->nBFrames; if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode) mDisableDeblkLevel = 4; if (avcType->nRefFrames != 1 || avcType->bUseHadamard != OMX_TRUE || avcType->nRefIdx10ActiveMinus1 != 0 || avcType->nRefIdx11ActiveMinus1 != 0 || avcType->bWeightedPPrediction != OMX_FALSE || avcType->bconstIpred != OMX_FALSE || avcType->bDirect8x8Inference != OMX_FALSE || avcType->bDirectSpatialTemporal != OMX_FALSE || avcType->nCabacInitIdc != 0) { return OMX_ErrorUndefined; } if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } }
174,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_hrtimer_start(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_cancel(&stime->hrt); hrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution), HRTIMER_MODE_REL); atomic_set(&stime->running, 1); return 0; } Commit Message: ALSA: hrtimer: Fix stall by hrtimer_cancel() hrtimer_cancel() waits for the completion from the callback, thus it must not be called inside the callback itself. This was already a problem in the past with ALSA hrtimer driver, and the early commit [fcfdebe70759: ALSA: hrtimer - Fix lock-up] tried to address it. However, the previous fix is still insufficient: it may still cause a lockup when the ALSA timer instance reprograms itself in its callback. Then it invokes the start function even in snd_timer_interrupt() that is called in hrtimer callback itself, results in a CPU stall. This is no hypothetical problem but actually triggered by syzkaller fuzzer. This patch tries to fix the issue again. Now we call hrtimer_try_to_cancel() at both start and stop functions so that it won't fall into a deadlock, yet giving some chance to cancel the queue if the functions have been called outside the callback. The proper hrtimer_cancel() is called in anyway at closing, so this should be enough. Reported-and-tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20
static int snd_hrtimer_start(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_try_to_cancel(&stime->hrt); hrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution), HRTIMER_MODE_REL); atomic_set(&stime->running, 1); return 0; }
167,398
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Block::GetTimeCode(const Cluster* pCluster) const { if (pCluster == 0) return m_timecode; const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; //unscaled timecode units } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Block::GetTimeCode(const Cluster* pCluster) const const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; // unscaled timecode units }
174,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static RAND_DRBG *rand_drbg_new(int secure, int type, unsigned int flags, RAND_DRBG *parent) { RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg)); if (drbg == NULL) { RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE); return NULL; } drbg->secure = secure && CRYPTO_secure_allocated(drbg); drbg->fork_count = rand_fork_count; drbg->parent = parent; if (parent == NULL) { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; #ifndef RAND_DRBG_GET_RANDOM_NONCE drbg->get_nonce = rand_drbg_get_nonce; drbg->cleanup_nonce = rand_drbg_cleanup_nonce; #endif drbg->reseed_interval = master_reseed_interval; drbg->reseed_time_interval = master_reseed_time_interval; } else { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; /* * Do not provide nonce callbacks, the child DRBGs will * obtain their nonce using random bits from the parent. */ drbg->reseed_interval = slave_reseed_interval; drbg->reseed_time_interval = slave_reseed_time_interval; } if (RAND_DRBG_set(drbg, type, flags) == 0) goto err; if (parent != NULL) { rand_drbg_lock(parent); if (drbg->strength > parent->strength) { /* * We currently don't support the algorithm from NIST SP 800-90C * 10.1.2 to use a weaker DRBG as source */ rand_drbg_unlock(parent); RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK); goto err; } rand_drbg_unlock(parent); } return drbg; err: RAND_DRBG_free(drbg); return NULL; } Commit Message: CWE ID: CWE-330
static RAND_DRBG *rand_drbg_new(int secure, int type, unsigned int flags, RAND_DRBG *parent) { RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg)); if (drbg == NULL) { RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE); return NULL; } drbg->secure = secure && CRYPTO_secure_allocated(drbg); drbg->fork_id = openssl_get_fork_id(); drbg->parent = parent; if (parent == NULL) { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; #ifndef RAND_DRBG_GET_RANDOM_NONCE drbg->get_nonce = rand_drbg_get_nonce; drbg->cleanup_nonce = rand_drbg_cleanup_nonce; #endif drbg->reseed_interval = master_reseed_interval; drbg->reseed_time_interval = master_reseed_time_interval; } else { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; /* * Do not provide nonce callbacks, the child DRBGs will * obtain their nonce using random bits from the parent. */ drbg->reseed_interval = slave_reseed_interval; drbg->reseed_time_interval = slave_reseed_time_interval; } if (RAND_DRBG_set(drbg, type, flags) == 0) goto err; if (parent != NULL) { rand_drbg_lock(parent); if (drbg->strength > parent->strength) { /* * We currently don't support the algorithm from NIST SP 800-90C * 10.1.2 to use a weaker DRBG as source */ rand_drbg_unlock(parent); RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK); goto err; } rand_drbg_unlock(parent); } return drbg; err: RAND_DRBG_free(drbg); return NULL; }
165,144
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error) { *arg0 = 42; *arg1 = g_strdup ("42"); *arg2 = -67; *arg3 = 2; *arg4 = 26; *arg5 = "hello world"; /* Annotation specifies as const */ return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error)
165,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_wrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_assoc_buffer, gss_buffer_t input_payload_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; ret = gss_wrap_aead(minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_wrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_assoc_buffer, gss_buffer_t input_payload_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_wrap_aead(minor_status, sc->ctx_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); return (ret); }
166,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) { int i = 0; int j = comp->nbStep - 1; while (j > i) { register xmlChar *tmp; register xsltOp op; register xmlXPathCompExprPtr expr; register int t; tmp = comp->steps[i].value; comp->steps[i].value = comp->steps[j].value; comp->steps[j].value = tmp; tmp = comp->steps[i].value2; comp->steps[i].value2 = comp->steps[j].value2; comp->steps[j].value2 = tmp; tmp = comp->steps[i].value3; comp->steps[i].value3 = comp->steps[j].value3; comp->steps[j].value3 = tmp; op = comp->steps[i].op; comp->steps[i].op = comp->steps[j].op; comp->steps[j].op = op; expr = comp->steps[i].comp; comp->steps[i].comp = comp->steps[j].comp; comp->steps[j].comp = expr; t = comp->steps[i].previousExtra; comp->steps[i].previousExtra = comp->steps[j].previousExtra; comp->steps[j].previousExtra = t; t = comp->steps[i].indexExtra; comp->steps[i].indexExtra = comp->steps[j].indexExtra; comp->steps[j].indexExtra = t; t = comp->steps[i].lenExtra; comp->steps[i].lenExtra = comp->steps[j].lenExtra; comp->steps[j].lenExtra = t; j--; i++; } xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0); /* * detect consecutive XSLT_OP_PREDICATE indicating a direct * matching should be done. */ for (i = 0;i < comp->nbStep - 1;i++) { if ((comp->steps[i].op == XSLT_OP_PREDICATE) && (comp->steps[i + 1].op == XSLT_OP_PREDICATE)) { comp->direct = 1; if (comp->pattern[0] != '/') { xmlChar *query; query = xmlStrdup((const xmlChar *)"//"); query = xmlStrcat(query, comp->pattern); xmlFree((xmlChar *) comp->pattern); comp->pattern = query; } break; } } } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) { int i = 0; int j = comp->nbStep - 1; while (j > i) { register xmlChar *tmp; register xsltOp op; register xmlXPathCompExprPtr expr; register int t; tmp = comp->steps[i].value; comp->steps[i].value = comp->steps[j].value; comp->steps[j].value = tmp; tmp = comp->steps[i].value2; comp->steps[i].value2 = comp->steps[j].value2; comp->steps[j].value2 = tmp; tmp = comp->steps[i].value3; comp->steps[i].value3 = comp->steps[j].value3; comp->steps[j].value3 = tmp; op = comp->steps[i].op; comp->steps[i].op = comp->steps[j].op; comp->steps[j].op = op; expr = comp->steps[i].comp; comp->steps[i].comp = comp->steps[j].comp; comp->steps[j].comp = expr; t = comp->steps[i].previousExtra; comp->steps[i].previousExtra = comp->steps[j].previousExtra; comp->steps[j].previousExtra = t; t = comp->steps[i].indexExtra; comp->steps[i].indexExtra = comp->steps[j].indexExtra; comp->steps[j].indexExtra = t; t = comp->steps[i].lenExtra; comp->steps[i].lenExtra = comp->steps[j].lenExtra; comp->steps[j].lenExtra = t; j--; i++; } xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0); /* * Detect consecutive XSLT_OP_PREDICATE and predicates on ops which * haven't been optimized yet indicating a direct matching should be done. */ for (i = 0;i < comp->nbStep - 1;i++) { xsltOp op = comp->steps[i].op; if ((op != XSLT_OP_ELEM) && (op != XSLT_OP_ALL) && (comp->steps[i + 1].op == XSLT_OP_PREDICATE)) { comp->direct = 1; if (comp->pattern[0] != '/') { xmlChar *query; query = xmlStrdup((const xmlChar *)"//"); query = xmlStrcat(query, comp->pattern); xmlFree((xmlChar *) comp->pattern); comp->pattern = query; } break; } } }
173,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); dev->priv_flags &= ~IFF_TX_SKB_SHARING; if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; }
165,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnDrm::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case INIT_CHECK: { CHECK_INTERFACE(IDrm, data, reply); reply->writeInt32(initCheck()); return OK; } case IS_CRYPTO_SUPPORTED: { CHECK_INTERFACE(IDrm, data, reply); uint8_t uuid[16]; data.read(uuid, sizeof(uuid)); String8 mimeType = data.readString8(); reply->writeInt32(isCryptoSchemeSupported(uuid, mimeType)); return OK; } case CREATE_PLUGIN: { CHECK_INTERFACE(IDrm, data, reply); uint8_t uuid[16]; data.read(uuid, sizeof(uuid)); reply->writeInt32(createPlugin(uuid)); return OK; } case DESTROY_PLUGIN: { CHECK_INTERFACE(IDrm, data, reply); reply->writeInt32(destroyPlugin()); return OK; } case OPEN_SESSION: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; status_t result = openSession(sessionId); writeVector(reply, sessionId); reply->writeInt32(result); return OK; } case CLOSE_SESSION: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); reply->writeInt32(closeSession(sessionId)); return OK; } case GET_KEY_REQUEST: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, initData; readVector(data, sessionId); readVector(data, initData); String8 mimeType = data.readString8(); DrmPlugin::KeyType keyType = (DrmPlugin::KeyType)data.readInt32(); KeyedVector<String8, String8> optionalParameters; uint32_t count = data.readInt32(); for (size_t i = 0; i < count; ++i) { String8 key, value; key = data.readString8(); value = data.readString8(); optionalParameters.add(key, value); } Vector<uint8_t> request; String8 defaultUrl; DrmPlugin::KeyRequestType keyRequestType; status_t result = getKeyRequest(sessionId, initData, mimeType, keyType, optionalParameters, request, defaultUrl, &keyRequestType); writeVector(reply, request); reply->writeString8(defaultUrl); reply->writeInt32(static_cast<int32_t>(keyRequestType)); reply->writeInt32(result); return OK; } case PROVIDE_KEY_RESPONSE: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, response, keySetId; readVector(data, sessionId); readVector(data, response); uint32_t result = provideKeyResponse(sessionId, response, keySetId); writeVector(reply, keySetId); reply->writeInt32(result); return OK; } case REMOVE_KEYS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> keySetId; readVector(data, keySetId); reply->writeInt32(removeKeys(keySetId)); return OK; } case RESTORE_KEYS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keySetId; readVector(data, sessionId); readVector(data, keySetId); reply->writeInt32(restoreKeys(sessionId, keySetId)); return OK; } case QUERY_KEY_STATUS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); KeyedVector<String8, String8> infoMap; status_t result = queryKeyStatus(sessionId, infoMap); size_t count = infoMap.size(); reply->writeInt32(count); for (size_t i = 0; i < count; ++i) { reply->writeString8(infoMap.keyAt(i)); reply->writeString8(infoMap.valueAt(i)); } reply->writeInt32(result); return OK; } case GET_PROVISION_REQUEST: { CHECK_INTERFACE(IDrm, data, reply); String8 certType = data.readString8(); String8 certAuthority = data.readString8(); Vector<uint8_t> request; String8 defaultUrl; status_t result = getProvisionRequest(certType, certAuthority, request, defaultUrl); writeVector(reply, request); reply->writeString8(defaultUrl); reply->writeInt32(result); return OK; } case PROVIDE_PROVISION_RESPONSE: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> response; Vector<uint8_t> certificate; Vector<uint8_t> wrappedKey; readVector(data, response); status_t result = provideProvisionResponse(response, certificate, wrappedKey); writeVector(reply, certificate); writeVector(reply, wrappedKey); reply->writeInt32(result); return OK; } case UNPROVISION_DEVICE: { CHECK_INTERFACE(IDrm, data, reply); status_t result = unprovisionDevice(); reply->writeInt32(result); return OK; } case GET_SECURE_STOPS: { CHECK_INTERFACE(IDrm, data, reply); List<Vector<uint8_t> > secureStops; status_t result = getSecureStops(secureStops); size_t count = secureStops.size(); reply->writeInt32(count); List<Vector<uint8_t> >::iterator iter = secureStops.begin(); while(iter != secureStops.end()) { size_t size = iter->size(); reply->writeInt32(size); reply->write(iter->array(), iter->size()); iter++; } reply->writeInt32(result); return OK; } case GET_SECURE_STOP: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> ssid, secureStop; readVector(data, ssid); status_t result = getSecureStop(ssid, secureStop); writeVector(reply, secureStop); reply->writeInt32(result); return OK; } case RELEASE_SECURE_STOPS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> ssRelease; readVector(data, ssRelease); reply->writeInt32(releaseSecureStops(ssRelease)); return OK; } case RELEASE_ALL_SECURE_STOPS: { CHECK_INTERFACE(IDrm, data, reply); reply->writeInt32(releaseAllSecureStops()); return OK; } case GET_PROPERTY_STRING: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); String8 value; status_t result = getPropertyString(name, value); reply->writeString8(value); reply->writeInt32(result); return OK; } case GET_PROPERTY_BYTE_ARRAY: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); Vector<uint8_t> value; status_t result = getPropertyByteArray(name, value); writeVector(reply, value); reply->writeInt32(result); return OK; } case SET_PROPERTY_STRING: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); String8 value = data.readString8(); reply->writeInt32(setPropertyString(name, value)); return OK; } case SET_PROPERTY_BYTE_ARRAY: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); Vector<uint8_t> value; readVector(data, value); reply->writeInt32(setPropertyByteArray(name, value)); return OK; } case SET_CIPHER_ALGORITHM: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); String8 algorithm = data.readString8(); reply->writeInt32(setCipherAlgorithm(sessionId, algorithm)); return OK; } case SET_MAC_ALGORITHM: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); String8 algorithm = data.readString8(); reply->writeInt32(setMacAlgorithm(sessionId, algorithm)); return OK; } case ENCRYPT: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, input, iv, output; readVector(data, sessionId); readVector(data, keyId); readVector(data, input); readVector(data, iv); uint32_t result = encrypt(sessionId, keyId, input, iv, output); writeVector(reply, output); reply->writeInt32(result); return OK; } case DECRYPT: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, input, iv, output; readVector(data, sessionId); readVector(data, keyId); readVector(data, input); readVector(data, iv); uint32_t result = decrypt(sessionId, keyId, input, iv, output); writeVector(reply, output); reply->writeInt32(result); return OK; } case SIGN: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, message, signature; readVector(data, sessionId); readVector(data, keyId); readVector(data, message); uint32_t result = sign(sessionId, keyId, message, signature); writeVector(reply, signature); reply->writeInt32(result); return OK; } case VERIFY: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, message, signature; readVector(data, sessionId); readVector(data, keyId); readVector(data, message); readVector(data, signature); bool match; uint32_t result = verify(sessionId, keyId, message, signature, match); reply->writeInt32(match); reply->writeInt32(result); return OK; } case SIGN_RSA: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, message, wrappedKey, signature; readVector(data, sessionId); String8 algorithm = data.readString8(); readVector(data, message); readVector(data, wrappedKey); uint32_t result = signRSA(sessionId, algorithm, message, wrappedKey, signature); writeVector(reply, signature); reply->writeInt32(result); return OK; } case SET_LISTENER: { CHECK_INTERFACE(IDrm, data, reply); sp<IDrmClient> listener = interface_cast<IDrmClient>(data.readStrongBinder()); reply->writeInt32(setListener(listener)); return NO_ERROR; } break; default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: Fix info leak vulnerability of IDrm bug: 26323455 Change-Id: I25bb30d3666ab38d5150496375ed2f55ecb23ba8 CWE ID: CWE-264
status_t BnDrm::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case INIT_CHECK: { CHECK_INTERFACE(IDrm, data, reply); reply->writeInt32(initCheck()); return OK; } case IS_CRYPTO_SUPPORTED: { CHECK_INTERFACE(IDrm, data, reply); uint8_t uuid[16]; data.read(uuid, sizeof(uuid)); String8 mimeType = data.readString8(); reply->writeInt32(isCryptoSchemeSupported(uuid, mimeType)); return OK; } case CREATE_PLUGIN: { CHECK_INTERFACE(IDrm, data, reply); uint8_t uuid[16]; data.read(uuid, sizeof(uuid)); reply->writeInt32(createPlugin(uuid)); return OK; } case DESTROY_PLUGIN: { CHECK_INTERFACE(IDrm, data, reply); reply->writeInt32(destroyPlugin()); return OK; } case OPEN_SESSION: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; status_t result = openSession(sessionId); writeVector(reply, sessionId); reply->writeInt32(result); return OK; } case CLOSE_SESSION: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); reply->writeInt32(closeSession(sessionId)); return OK; } case GET_KEY_REQUEST: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, initData; readVector(data, sessionId); readVector(data, initData); String8 mimeType = data.readString8(); DrmPlugin::KeyType keyType = (DrmPlugin::KeyType)data.readInt32(); KeyedVector<String8, String8> optionalParameters; uint32_t count = data.readInt32(); for (size_t i = 0; i < count; ++i) { String8 key, value; key = data.readString8(); value = data.readString8(); optionalParameters.add(key, value); } Vector<uint8_t> request; String8 defaultUrl; DrmPlugin::KeyRequestType keyRequestType = DrmPlugin::kKeyRequestType_Unknown; status_t result = getKeyRequest(sessionId, initData, mimeType, keyType, optionalParameters, request, defaultUrl, &keyRequestType); writeVector(reply, request); reply->writeString8(defaultUrl); reply->writeInt32(static_cast<int32_t>(keyRequestType)); reply->writeInt32(result); return OK; } case PROVIDE_KEY_RESPONSE: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, response, keySetId; readVector(data, sessionId); readVector(data, response); uint32_t result = provideKeyResponse(sessionId, response, keySetId); writeVector(reply, keySetId); reply->writeInt32(result); return OK; } case REMOVE_KEYS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> keySetId; readVector(data, keySetId); reply->writeInt32(removeKeys(keySetId)); return OK; } case RESTORE_KEYS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keySetId; readVector(data, sessionId); readVector(data, keySetId); reply->writeInt32(restoreKeys(sessionId, keySetId)); return OK; } case QUERY_KEY_STATUS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); KeyedVector<String8, String8> infoMap; status_t result = queryKeyStatus(sessionId, infoMap); size_t count = infoMap.size(); reply->writeInt32(count); for (size_t i = 0; i < count; ++i) { reply->writeString8(infoMap.keyAt(i)); reply->writeString8(infoMap.valueAt(i)); } reply->writeInt32(result); return OK; } case GET_PROVISION_REQUEST: { CHECK_INTERFACE(IDrm, data, reply); String8 certType = data.readString8(); String8 certAuthority = data.readString8(); Vector<uint8_t> request; String8 defaultUrl; status_t result = getProvisionRequest(certType, certAuthority, request, defaultUrl); writeVector(reply, request); reply->writeString8(defaultUrl); reply->writeInt32(result); return OK; } case PROVIDE_PROVISION_RESPONSE: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> response; Vector<uint8_t> certificate; Vector<uint8_t> wrappedKey; readVector(data, response); status_t result = provideProvisionResponse(response, certificate, wrappedKey); writeVector(reply, certificate); writeVector(reply, wrappedKey); reply->writeInt32(result); return OK; } case UNPROVISION_DEVICE: { CHECK_INTERFACE(IDrm, data, reply); status_t result = unprovisionDevice(); reply->writeInt32(result); return OK; } case GET_SECURE_STOPS: { CHECK_INTERFACE(IDrm, data, reply); List<Vector<uint8_t> > secureStops; status_t result = getSecureStops(secureStops); size_t count = secureStops.size(); reply->writeInt32(count); List<Vector<uint8_t> >::iterator iter = secureStops.begin(); while(iter != secureStops.end()) { size_t size = iter->size(); reply->writeInt32(size); reply->write(iter->array(), iter->size()); iter++; } reply->writeInt32(result); return OK; } case GET_SECURE_STOP: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> ssid, secureStop; readVector(data, ssid); status_t result = getSecureStop(ssid, secureStop); writeVector(reply, secureStop); reply->writeInt32(result); return OK; } case RELEASE_SECURE_STOPS: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> ssRelease; readVector(data, ssRelease); reply->writeInt32(releaseSecureStops(ssRelease)); return OK; } case RELEASE_ALL_SECURE_STOPS: { CHECK_INTERFACE(IDrm, data, reply); reply->writeInt32(releaseAllSecureStops()); return OK; } case GET_PROPERTY_STRING: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); String8 value; status_t result = getPropertyString(name, value); reply->writeString8(value); reply->writeInt32(result); return OK; } case GET_PROPERTY_BYTE_ARRAY: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); Vector<uint8_t> value; status_t result = getPropertyByteArray(name, value); writeVector(reply, value); reply->writeInt32(result); return OK; } case SET_PROPERTY_STRING: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); String8 value = data.readString8(); reply->writeInt32(setPropertyString(name, value)); return OK; } case SET_PROPERTY_BYTE_ARRAY: { CHECK_INTERFACE(IDrm, data, reply); String8 name = data.readString8(); Vector<uint8_t> value; readVector(data, value); reply->writeInt32(setPropertyByteArray(name, value)); return OK; } case SET_CIPHER_ALGORITHM: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); String8 algorithm = data.readString8(); reply->writeInt32(setCipherAlgorithm(sessionId, algorithm)); return OK; } case SET_MAC_ALGORITHM: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId; readVector(data, sessionId); String8 algorithm = data.readString8(); reply->writeInt32(setMacAlgorithm(sessionId, algorithm)); return OK; } case ENCRYPT: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, input, iv, output; readVector(data, sessionId); readVector(data, keyId); readVector(data, input); readVector(data, iv); uint32_t result = encrypt(sessionId, keyId, input, iv, output); writeVector(reply, output); reply->writeInt32(result); return OK; } case DECRYPT: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, input, iv, output; readVector(data, sessionId); readVector(data, keyId); readVector(data, input); readVector(data, iv); uint32_t result = decrypt(sessionId, keyId, input, iv, output); writeVector(reply, output); reply->writeInt32(result); return OK; } case SIGN: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, message, signature; readVector(data, sessionId); readVector(data, keyId); readVector(data, message); uint32_t result = sign(sessionId, keyId, message, signature); writeVector(reply, signature); reply->writeInt32(result); return OK; } case VERIFY: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, keyId, message, signature; readVector(data, sessionId); readVector(data, keyId); readVector(data, message); readVector(data, signature); bool match; uint32_t result = verify(sessionId, keyId, message, signature, match); reply->writeInt32(match); reply->writeInt32(result); return OK; } case SIGN_RSA: { CHECK_INTERFACE(IDrm, data, reply); Vector<uint8_t> sessionId, message, wrappedKey, signature; readVector(data, sessionId); String8 algorithm = data.readString8(); readVector(data, message); readVector(data, wrappedKey); uint32_t result = signRSA(sessionId, algorithm, message, wrappedKey, signature); writeVector(reply, signature); reply->writeInt32(result); return OK; } case SET_LISTENER: { CHECK_INTERFACE(IDrm, data, reply); sp<IDrmClient> listener = interface_cast<IDrmClient>(data.readStrongBinder()); reply->writeInt32(setListener(listener)); return NO_ERROR; } break; default: return BBinder::onTransact(code, data, reply, flags); } }
173,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void lxc_execute_bind_init(struct lxc_conf *conf) { int ret; char path[PATH_MAX], destpath[PATH_MAX], *p; /* If init exists in the container, don't bind mount a static one */ p = choose_init(conf->rootfs.mount); if (p) { free(p); return; } ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long searching for lxc.init.static"); return; } if (!file_exists(path)) { INFO("%s does not exist on host", path); return; } ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long for container's lxc.init.static"); return; } if (!file_exists(destpath)) { FILE * pathfile = fopen(destpath, "wb"); if (!pathfile) { SYSERROR("Failed to create mount target '%s'", destpath); return; } fclose(pathfile); } ret = mount(path, destpath, "none", MS_BIND, NULL); if (ret < 0) SYSERROR("Failed to bind lxc.init.static into container"); INFO("lxc.init.static bound into container at %s", path); } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59
void lxc_execute_bind_init(struct lxc_conf *conf) { int ret; char path[PATH_MAX], destpath[PATH_MAX], *p; /* If init exists in the container, don't bind mount a static one */ p = choose_init(conf->rootfs.mount); if (p) { free(p); return; } ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long searching for lxc.init.static"); return; } if (!file_exists(path)) { INFO("%s does not exist on host", path); return; } ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long for container's lxc.init.static"); return; } if (!file_exists(destpath)) { FILE * pathfile = fopen(destpath, "wb"); if (!pathfile) { SYSERROR("Failed to create mount target '%s'", destpath); return; } fclose(pathfile); } ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount); if (ret < 0) SYSERROR("Failed to bind lxc.init.static into container"); INFO("lxc.init.static bound into container at %s", path); }
166,712
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNConversionResult IDNToUnicodeWithAdjustmentsImpl( base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments, bool enable_spoof_checks) { if (adjustments) adjustments->clear(); base::string16 input16; input16.reserve(host.length()); input16.insert(input16.end(), host.begin(), host.end()); bool is_tld_ascii = true; size_t last_dot = host.rfind('.'); if (last_dot != base::StringPiece::npos && host.substr(last_dot).starts_with(".xn--")) { is_tld_ascii = false; } IDNConversionResult result; base::string16 out16; for (size_t component_start = 0, component_end; component_start < input16.length(); component_start = component_end + 1) { component_end = input16.find('.', component_start); if (component_end == base::string16::npos) component_end = input16.length(); // For getting the last component. size_t component_length = component_end - component_start; size_t new_component_start = out16.length(); bool converted_idn = false; if (component_end > component_start) { bool has_idn_component = false; converted_idn = IDNToUnicodeOneComponent( input16.data() + component_start, component_length, is_tld_ascii, enable_spoof_checks, &out16, &has_idn_component); result.has_idn_component |= has_idn_component; } size_t new_component_length = out16.length() - new_component_start; if (converted_idn && adjustments) { adjustments->push_back(base::OffsetAdjuster::Adjustment( component_start, component_length, new_component_length)); } if (component_end < input16.length()) out16.push_back('.'); } result.result = out16; if (result.has_idn_component) { result.matching_top_domain = g_idn_spoof_checker.Get().GetSimilarTopDomain(out16); if (enable_spoof_checks && !result.matching_top_domain.domain.empty()) { if (adjustments) adjustments->clear(); result.result = input16; } } return result; } Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains This character (þ) can be confused with both b and p when used in a domain name. IDN spoof checker doesn't have a good way of flagging a character as confusable with multiple characters, so it can't catch spoofs containing this character. As a practical fix, this CL restricts this character to domains under Iceland's ccTLD (.is). With this change, a domain name containing "þ" with a non-.is TLD will be displayed in punycode in the UI. This change affects less than 10 real world domains with limited popularity. Bug: 798892, 843352, 904327, 1017707 Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992 Commit-Queue: Mustafa Emre Acer <[email protected]> Reviewed-by: Christopher Thompson <[email protected]> Cr-Commit-Position: refs/heads/master@{#709309} CWE ID:
IDNConversionResult IDNToUnicodeWithAdjustmentsImpl( base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments, bool enable_spoof_checks) { if (adjustments) adjustments->clear(); base::string16 input16; input16.reserve(host.length()); input16.insert(input16.end(), host.begin(), host.end()); base::StringPiece top_level_domain; size_t last_dot = host.rfind('.'); if (last_dot != base::StringPiece::npos) { top_level_domain = host.substr(last_dot); } IDNConversionResult result; base::string16 out16; for (size_t component_start = 0, component_end; component_start < input16.length(); component_start = component_end + 1) { component_end = input16.find('.', component_start); if (component_end == base::string16::npos) component_end = input16.length(); // For getting the last component. size_t component_length = component_end - component_start; size_t new_component_start = out16.length(); bool converted_idn = false; if (component_end > component_start) { bool has_idn_component = false; converted_idn = IDNToUnicodeOneComponent( input16.data() + component_start, component_length, top_level_domain, enable_spoof_checks, &out16, &has_idn_component); result.has_idn_component |= has_idn_component; } size_t new_component_length = out16.length() - new_component_start; if (converted_idn && adjustments) { adjustments->push_back(base::OffsetAdjuster::Adjustment( component_start, component_length, new_component_length)); } if (component_end < input16.length()) out16.push_back('.'); } result.result = out16; if (result.has_idn_component) { result.matching_top_domain = g_idn_spoof_checker.Get().GetSimilarTopDomain(out16); if (enable_spoof_checks && !result.matching_top_domain.domain.empty()) { if (adjustments) adjustments->clear(); result.result = input16; } } return result; }
172,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \ { \ if (data != (unsigned char *) NULL) \ data=(unsigned char *) RelinquishMagickMemory(data); \ if (stream_info != (DCMStreamInfo *) NULL) \ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \ ThrowReaderException((exception),(message)); \ } char explicit_vr[MaxTextExtent], implicit_vr[MaxTextExtent], magick[MaxTextExtent], photometric[MaxTextExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, sequence, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ data=(unsigned char *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent); info.polarity=MagickFalse; info.scale=(Quantum *) NULL; info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.significant_bits=0; info.rescale=MagickFalse; info.rescale_intercept=0.0; info.rescale_slope=1.0; info.window_center=0.0; info.window_width=0.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; sequence=MagickFalse; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"UL",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"FL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MaxTextExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MaxTextExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype); if (count < 1) ThrowDCMException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if (info.depth > 32) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if (info.depth > 32) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data, (char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data, (char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data, (char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MaxTextExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s", filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s", filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property)); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); info.scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); break; } image->colorspace=RGBColorspace; if ((image->colormap == (PixelPacket *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors) == MagickFalse) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(Quantum) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(Quantum) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(Quantum) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(Quantum) index; image->colormap[i].green=(Quantum) index; image->colormap[i].blue=(Quantum) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,stream_info->offsets[0]+ stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register PixelPacket *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 1: { SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 2: { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 3: { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } default: break; } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) info.window_width=0; } option=GetImageOption(image_info,"dcm:window"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,"dcm:rescale"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,stream_info->offsets[0]+ stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse,exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/551 CWE ID: CWE-772
static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \ { \ if (data != (unsigned char *) NULL) \ data=(unsigned char *) RelinquishMagickMemory(data); \ if (stream_info != (DCMStreamInfo *) NULL) \ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \ ThrowReaderException((exception),(message)); \ } char explicit_vr[MaxTextExtent], implicit_vr[MaxTextExtent], magick[MaxTextExtent], photometric[MaxTextExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, sequence, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ data=(unsigned char *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent); info.polarity=MagickFalse; info.scale=(Quantum *) NULL; info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.significant_bits=0; info.rescale=MagickFalse; info.rescale_intercept=0.0; info.rescale_slope=1.0; info.window_center=0.0; info.window_width=0.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; sequence=MagickFalse; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"UL",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"FL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > GetBlobSize(image)) ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MaxTextExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MaxTextExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype); if (count < 1) ThrowDCMException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if (info.depth > 32) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if (info.depth > 32) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data, (char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data, (char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data, (char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MaxTextExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s", filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s", filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property)); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); info.scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); break; } image->colorspace=RGBColorspace; if ((image->colormap == (PixelPacket *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors) == MagickFalse) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(Quantum) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(Quantum) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(Quantum) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(Quantum) index; image->colormap[i].green=(Quantum) index; image->colormap[i].blue=(Quantum) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,stream_info->offsets[0]+ stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register PixelPacket *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 1: { SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 2: { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 3: { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } default: break; } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) info.window_width=0; } option=GetImageOption(image_info,"dcm:window"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,"dcm:rescale"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,stream_info->offsets[0]+ stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse,exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
167,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int queued = 0; int res; tp->rx_opt.saw_tstamp = 0; switch (sk->sk_state) { case TCP_CLOSE: goto discard; case TCP_LISTEN: if (th->ack) return 1; if (th->rst) goto discard; if (th->syn) { if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) return 1; /* Now we have several options: In theory there is * nothing else in the frame. KA9Q has an option to * send data with the syn, BSD accepts data with the * syn up to the [to be] advertised window and * Solaris 2.1 gives you a protocol error. For now * we just ignore it, that fits the spec precisely * and avoids incompatibilities. It would be nice in * future to drop through and process the data. * * Now that TTCP is starting to be used we ought to * queue this data. * But, this leaves one open to an easy denial of * service attack, and SYN cookies can't defend * against this problem. So, we drop the data * in the interest of security over speed unless * it's still in use. */ kfree_skb(skb); return 0; } goto discard; case TCP_SYN_SENT: queued = tcp_rcv_synsent_state_process(sk, skb, th, len); if (queued >= 0) return queued; /* Do step6 onward by hand. */ tcp_urg(sk, skb, th); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } res = tcp_validate_incoming(sk, skb, th, 0); if (res <= 0) return -res; /* step 5: check the ACK field */ if (th->ack) { int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH) > 0; switch (sk->sk_state) { case TCP_SYN_RECV: if (acceptable) { tp->copied_seq = tp->rcv_nxt; smp_mb(); tcp_set_state(sk, TCP_ESTABLISHED); sk->sk_state_change(sk); /* Note, that this wakeup is only for marginal * crossed SYN case. Passively open sockets * are not waked up, because sk->sk_sleep == * NULL and sk->sk_socket == NULL. */ if (sk->sk_socket) sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); tp->snd_una = TCP_SKB_CB(skb)->ack_seq; tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale; tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); if (tp->rx_opt.tstamp_ok) tp->advmss -= TCPOLEN_TSTAMP_ALIGNED; /* Make sure socket is routed, for * correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_metrics(sk); tcp_init_congestion_control(sk); /* Prevent spurious tcp_cwnd_restart() on * first data packet. */ tp->lsndtime = tcp_time_stamp; tcp_mtup_init(sk); tcp_initialize_rcv_mss(sk); tcp_init_buffer_space(sk); tcp_fast_path_on(tp); } else { return 1; } break; case TCP_FIN_WAIT1: if (tp->snd_una == tp->write_seq) { tcp_set_state(sk, TCP_FIN_WAIT2); sk->sk_shutdown |= SEND_SHUTDOWN; dst_confirm(__sk_dst_get(sk)); if (!sock_flag(sk, SOCK_DEAD)) /* Wake up lingering close() */ sk->sk_state_change(sk); else { int tmo; if (tp->linger2 < 0 || (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) { tcp_done(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA); return 1; } tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else if (th->fin || sock_owned_by_user(sk)) { /* Bad case. We could lose such FIN otherwise. * It is not a big problem, but it looks confusing * and not so rare event. We still can lose it now, * if it spins in bh_lock_sock(), but it is really * marginal case. */ inet_csk_reset_keepalive_timer(sk, tmo); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto discard; } } } break; case TCP_CLOSING: if (tp->snd_una == tp->write_seq) { tcp_time_wait(sk, TCP_TIME_WAIT, 0); goto discard; } break; case TCP_LAST_ACK: if (tp->snd_una == tp->write_seq) { tcp_update_metrics(sk); tcp_done(sk); goto discard; } break; } } else goto discard; /* step 6: check the URG bit */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ switch (sk->sk_state) { case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; case TCP_FIN_WAIT1: case TCP_FIN_WAIT2: /* RFC 793 says to queue data in these states, * RFC 1122 says we MUST send a reset. * BSD 4.4 also does reset. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA); tcp_reset(sk); return 1; } } /* Fall through */ case TCP_ESTABLISHED: tcp_data_queue(sk, skb); queued = 1; break; } /* tcp_data could move socket to TIME-WAIT */ if (sk->sk_state != TCP_CLOSE) { tcp_data_snd_check(sk); tcp_ack_snd_check(sk); } if (!queued) { discard: __kfree_skb(skb); } return 0; } Commit Message: tcp: drop SYN+FIN messages Denys Fedoryshchenko reported that SYN+FIN attacks were bringing his linux machines to their limits. Dont call conn_request() if the TCP flags includes SYN flag Reported-by: Denys Fedoryshchenko <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int queued = 0; int res; tp->rx_opt.saw_tstamp = 0; switch (sk->sk_state) { case TCP_CLOSE: goto discard; case TCP_LISTEN: if (th->ack) return 1; if (th->rst) goto discard; if (th->syn) { if (th->fin) goto discard; if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) return 1; /* Now we have several options: In theory there is * nothing else in the frame. KA9Q has an option to * send data with the syn, BSD accepts data with the * syn up to the [to be] advertised window and * Solaris 2.1 gives you a protocol error. For now * we just ignore it, that fits the spec precisely * and avoids incompatibilities. It would be nice in * future to drop through and process the data. * * Now that TTCP is starting to be used we ought to * queue this data. * But, this leaves one open to an easy denial of * service attack, and SYN cookies can't defend * against this problem. So, we drop the data * in the interest of security over speed unless * it's still in use. */ kfree_skb(skb); return 0; } goto discard; case TCP_SYN_SENT: queued = tcp_rcv_synsent_state_process(sk, skb, th, len); if (queued >= 0) return queued; /* Do step6 onward by hand. */ tcp_urg(sk, skb, th); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } res = tcp_validate_incoming(sk, skb, th, 0); if (res <= 0) return -res; /* step 5: check the ACK field */ if (th->ack) { int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH) > 0; switch (sk->sk_state) { case TCP_SYN_RECV: if (acceptable) { tp->copied_seq = tp->rcv_nxt; smp_mb(); tcp_set_state(sk, TCP_ESTABLISHED); sk->sk_state_change(sk); /* Note, that this wakeup is only for marginal * crossed SYN case. Passively open sockets * are not waked up, because sk->sk_sleep == * NULL and sk->sk_socket == NULL. */ if (sk->sk_socket) sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); tp->snd_una = TCP_SKB_CB(skb)->ack_seq; tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale; tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); if (tp->rx_opt.tstamp_ok) tp->advmss -= TCPOLEN_TSTAMP_ALIGNED; /* Make sure socket is routed, for * correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_metrics(sk); tcp_init_congestion_control(sk); /* Prevent spurious tcp_cwnd_restart() on * first data packet. */ tp->lsndtime = tcp_time_stamp; tcp_mtup_init(sk); tcp_initialize_rcv_mss(sk); tcp_init_buffer_space(sk); tcp_fast_path_on(tp); } else { return 1; } break; case TCP_FIN_WAIT1: if (tp->snd_una == tp->write_seq) { tcp_set_state(sk, TCP_FIN_WAIT2); sk->sk_shutdown |= SEND_SHUTDOWN; dst_confirm(__sk_dst_get(sk)); if (!sock_flag(sk, SOCK_DEAD)) /* Wake up lingering close() */ sk->sk_state_change(sk); else { int tmo; if (tp->linger2 < 0 || (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) { tcp_done(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA); return 1; } tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else if (th->fin || sock_owned_by_user(sk)) { /* Bad case. We could lose such FIN otherwise. * It is not a big problem, but it looks confusing * and not so rare event. We still can lose it now, * if it spins in bh_lock_sock(), but it is really * marginal case. */ inet_csk_reset_keepalive_timer(sk, tmo); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto discard; } } } break; case TCP_CLOSING: if (tp->snd_una == tp->write_seq) { tcp_time_wait(sk, TCP_TIME_WAIT, 0); goto discard; } break; case TCP_LAST_ACK: if (tp->snd_una == tp->write_seq) { tcp_update_metrics(sk); tcp_done(sk); goto discard; } break; } } else goto discard; /* step 6: check the URG bit */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ switch (sk->sk_state) { case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; case TCP_FIN_WAIT1: case TCP_FIN_WAIT2: /* RFC 793 says to queue data in these states, * RFC 1122 says we MUST send a reset. * BSD 4.4 also does reset. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA); tcp_reset(sk); return 1; } } /* Fall through */ case TCP_ESTABLISHED: tcp_data_queue(sk, skb); queued = 1; break; } /* tcp_data could move socket to TIME-WAIT */ if (sk->sk_state != TCP_CLOSE) { tcp_data_snd_check(sk); tcp_ack_snd_check(sk); } if (!queued) { discard: __kfree_skb(skb); } return 0; }
166,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); } if(rctx->topdown) { iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); } rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } Commit Message: Fixed a bug that could cause invalid memory to be accessed The bug could happen when transparency is removed from an image. Also fixed a semi-related BMP error handling logic bug. Fixes issue #21 CWE ID: CWE-787
static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); goto done; } if(rctx->topdown) { iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); goto done; } rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; }
168,117
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(ptr))); ptr++; /* Disconnect Code */ ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(ptr))); ptr++; /* Control Protocol Number */ ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str, "Direction-#%u", *((const u_char *)ptr++)))); if (length > 5) { ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length-5); } } 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_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 5) { ND_PRINT((ndo, "AVP too short")); return; } /* Disconnect Code */ ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(dat))); dat += 2; length -= 2; /* Control Protocol Number */ ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(dat))); dat += 2; length -= 2; /* Direction */ ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str, "Direction-#%u", EXTRACT_8BITS(ptr)))); ptr++; length--; if (length != 0) { ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length); } }
167,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SetManualFallbacksForFilling(bool enabled) { if (enabled) { scoped_feature_list_.InitAndEnableFeature( password_manager::features::kEnableManualFallbacksFilling); } else { scoped_feature_list_.InitAndDisableFeature( password_manager::features::kEnableManualFallbacksFilling); } } Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature. Fixing names of password_manager kEnableManualFallbacksFilling feature as per the naming convention. Bug: 785953 Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03 Reviewed-on: https://chromium-review.googlesource.com/900566 Reviewed-by: Vaclav Brozek <[email protected]> Commit-Queue: NIKHIL SAHNI <[email protected]> Cr-Commit-Position: refs/heads/master@{#534923} CWE ID: CWE-264
void SetManualFallbacksForFilling(bool enabled) { if (enabled) { scoped_feature_list_.InitAndEnableFeature( password_manager::features::kManualFallbacksFilling); } else { scoped_feature_list_.InitAndDisableFeature( password_manager::features::kManualFallbacksFilling); } }
171,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<base::DictionaryValue> ParsePrintSettings( int command_id, const base::DictionaryValue* params, HeadlessPrintSettings* settings) { if (const base::Value* landscape_value = params->FindKey("landscape")) settings->landscape = landscape_value->GetBool(); if (const base::Value* display_header_footer_value = params->FindKey("displayHeaderFooter")) { settings->display_header_footer = display_header_footer_value->GetBool(); } if (const base::Value* should_print_backgrounds_value = params->FindKey("printBackground")) { settings->should_print_backgrounds = should_print_backgrounds_value->GetBool(); } if (const base::Value* scale_value = params->FindKey("scale")) settings->scale = scale_value->GetDouble(); if (settings->scale > kScaleMaxVal / 100 || settings->scale < kScaleMinVal / 100) return CreateInvalidParamResponse(command_id, "scale"); if (const base::Value* page_ranges_value = params->FindKey("pageRanges")) settings->page_ranges = page_ranges_value->GetString(); if (const base::Value* ignore_invalid_page_ranges_value = params->FindKey("ignoreInvalidPageRanges")) { settings->ignore_invalid_page_ranges = ignore_invalid_page_ranges_value->GetBool(); } double paper_width_in_inch = printing::kLetterWidthInch; if (const base::Value* paper_width_value = params->FindKey("paperWidth")) paper_width_in_inch = paper_width_value->GetDouble(); double paper_height_in_inch = printing::kLetterHeightInch; if (const base::Value* paper_height_value = params->FindKey("paperHeight")) paper_height_in_inch = paper_height_value->GetDouble(); if (paper_width_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperWidth"); if (paper_height_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperHeight"); settings->paper_size_in_points = gfx::Size(paper_width_in_inch * printing::kPointsPerInch, paper_height_in_inch * printing::kPointsPerInch); double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch; double margin_top_in_inch = default_margin_in_inch; double margin_bottom_in_inch = default_margin_in_inch; double margin_left_in_inch = default_margin_in_inch; double margin_right_in_inch = default_margin_in_inch; if (const base::Value* margin_top_value = params->FindKey("marginTop")) margin_top_in_inch = margin_top_value->GetDouble(); if (const base::Value* margin_bottom_value = params->FindKey("marginBottom")) margin_bottom_in_inch = margin_bottom_value->GetDouble(); if (const base::Value* margin_left_value = params->FindKey("marginLeft")) margin_left_in_inch = margin_left_value->GetDouble(); if (const base::Value* margin_right_value = params->FindKey("marginRight")) margin_right_in_inch = margin_right_value->GetDouble(); if (margin_top_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginTop"); if (margin_bottom_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginBottom"); if (margin_left_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginLeft"); if (margin_right_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginRight"); settings->margins_in_points.top = margin_top_in_inch * printing::kPointsPerInch; settings->margins_in_points.bottom = margin_bottom_in_inch * printing::kPointsPerInch; settings->margins_in_points.left = margin_left_in_inch * printing::kPointsPerInch; settings->margins_in_points.right = margin_right_in_inch * printing::kPointsPerInch; return nullptr; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
std::unique_ptr<base::DictionaryValue> ParsePrintSettings( int command_id, const base::DictionaryValue* params, HeadlessPrintSettings* settings) { if (const base::Value* landscape_value = params->FindKey("landscape")) settings->landscape = landscape_value->GetBool(); if (const base::Value* display_header_footer_value = params->FindKey("displayHeaderFooter")) { settings->display_header_footer = display_header_footer_value->GetBool(); } if (const base::Value* should_print_backgrounds_value = params->FindKey("printBackground")) { settings->should_print_backgrounds = should_print_backgrounds_value->GetBool(); } if (const base::Value* scale_value = params->FindKey("scale")) settings->scale = scale_value->GetDouble(); if (settings->scale > kScaleMaxVal / 100 || settings->scale < kScaleMinVal / 100) return CreateInvalidParamResponse(command_id, "scale"); if (const base::Value* page_ranges_value = params->FindKey("pageRanges")) settings->page_ranges = page_ranges_value->GetString(); if (const base::Value* ignore_invalid_page_ranges_value = params->FindKey("ignoreInvalidPageRanges")) { settings->ignore_invalid_page_ranges = ignore_invalid_page_ranges_value->GetBool(); } double paper_width_in_inch = printing::kLetterWidthInch; if (const base::Value* paper_width_value = params->FindKey("paperWidth")) paper_width_in_inch = paper_width_value->GetDouble(); double paper_height_in_inch = printing::kLetterHeightInch; if (const base::Value* paper_height_value = params->FindKey("paperHeight")) paper_height_in_inch = paper_height_value->GetDouble(); if (paper_width_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperWidth"); if (paper_height_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperHeight"); settings->paper_size_in_points = gfx::Size(paper_width_in_inch * printing::kPointsPerInch, paper_height_in_inch * printing::kPointsPerInch); double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch; double margin_top_in_inch = default_margin_in_inch; double margin_bottom_in_inch = default_margin_in_inch; double margin_left_in_inch = default_margin_in_inch; double margin_right_in_inch = default_margin_in_inch; if (const base::Value* margin_top_value = params->FindKey("marginTop")) margin_top_in_inch = margin_top_value->GetDouble(); if (const base::Value* margin_bottom_value = params->FindKey("marginBottom")) margin_bottom_in_inch = margin_bottom_value->GetDouble(); if (const base::Value* margin_left_value = params->FindKey("marginLeft")) margin_left_in_inch = margin_left_value->GetDouble(); if (const base::Value* margin_right_value = params->FindKey("marginRight")) margin_right_in_inch = margin_right_value->GetDouble(); if (const base::Value* header_template_value = params->FindKey("headerTemplate")) { settings->header_template = header_template_value->GetString(); } if (const base::Value* footer_template_value = params->FindKey("footerTemplate")) { settings->footer_template = footer_template_value->GetString(); } if (margin_top_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginTop"); if (margin_bottom_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginBottom"); if (margin_left_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginLeft"); if (margin_right_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginRight"); settings->margins_in_points.top = margin_top_in_inch * printing::kPointsPerInch; settings->margins_in_points.bottom = margin_bottom_in_inch * printing::kPointsPerInch; settings->margins_in_points.left = margin_left_in_inch * printing::kPointsPerInch; settings->margins_in_points.right = margin_right_in_inch * printing::kPointsPerInch; return nullptr; }
172,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET])
167,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const BlockEntry* Cluster::GetEntry(const CuePoint& cp, const CuePoint::TrackPosition& tp) const { assert(m_pSegment); #if 0 LoadBlockEntries(); if (m_entries == NULL) return NULL; const long long count = m_entries_count; if (count <= 0) return NULL; const long long tc = cp.GetTimeCode(); if ((tp.m_block > 0) && (tp.m_block <= count)) { const size_t block = static_cast<size_t>(tp.m_block); const size_t index = block - 1; const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } const BlockEntry* const* i = m_entries; const BlockEntry* const* const j = i + count; while (i != j) { #ifdef _DEBUG const ptrdiff_t idx = i - m_entries; idx; #endif const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) continue; const long long tc_ = pBlock->GetTimeCode(this); assert(tc_ >= 0); if (tc_ < tc) continue; if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) //audio return pEntry; if (type != 1) //not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } return NULL; #else const long long tc = cp.GetTimeCode(); if (tp.m_block > 0) { const long block = static_cast<long>(tp.m_block); const long index = block - 1; while (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) { ++index; continue; } const long long tc_ = pBlock->GetTimeCode(this); if (tc_ < tc) { ++index; continue; } if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) // audio return pEntry; if (type != 1) // not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } #endif } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const BlockEntry* Cluster::GetEntry(const CuePoint& cp, const CuePoint::TrackPosition& tp) const { assert(m_pSegment); const long long tc = cp.GetTimeCode(); if (tp.m_block > 0) { const long block = static_cast<long>(tp.m_block); const long index = block - 1; while (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) { ++index; continue; } const long long tc_ = pBlock->GetTimeCode(this); if (tc_ < tc) { ++index; continue; } if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) // audio return pEntry; if (type != 1) // not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } }
173,817
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __net_exit sctp_net_exit(struct net *net) { /* Free the local address list */ sctp_free_addr_wq(net); sctp_free_local_addr_list(net); /* Free the control endpoint. */ inet_ctl_sock_destroy(net->sctp.ctl_sock); sctp_dbg_objcnt_exit(net); sctp_proc_exit(net); cleanup_sctp_mibs(net); sctp_sysctl_net_unregister(net); } Commit Message: sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static void __net_exit sctp_net_exit(struct net *net) static void __net_exit sctp_defaults_exit(struct net *net) { /* Free the local address list */ sctp_free_addr_wq(net); sctp_free_local_addr_list(net); sctp_dbg_objcnt_exit(net); sctp_proc_exit(net); cleanup_sctp_mibs(net); sctp_sysctl_net_unregister(net); }
166,607
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpeg_size(unsigned char* data, unsigned int data_size, int *width, int *height) { int i = 0; if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 && data[i+2] == 0xFF && data[i+3] == 0xE0) { i += 4; if(i + 6 < data_size && data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && data[i+5] == 'F' && data[i+6] == 0x00) { unsigned short block_length = data[i] * 256 + data[i+1]; while(i<data_size) { i+=block_length; if((i + 1) >= data_size) return -1; if(data[i] != 0xFF) return -1; if(data[i+1] == 0xC0) { *height = data[i+5]*256 + data[i+6]; *width = data[i+7]*256 + data[i+8]; return 0; } i+=2; block_length = data[i] * 256 + data[i+1]; } } } return -1; } Commit Message: jpeg: Fix another possible buffer overrun Found via the clang libfuzzer CWE ID: CWE-125
static int jpeg_size(unsigned char* data, unsigned int data_size, int *width, int *height) { int i = 0; if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 && data[i+2] == 0xFF && data[i+3] == 0xE0) { i += 4; if(i + 6 < data_size && data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && data[i+5] == 'F' && data[i+6] == 0x00) { unsigned short block_length = data[i] * 256 + data[i+1]; while(i<data_size) { i+=block_length; if((i + 1) >= data_size) return -1; if(data[i] != 0xFF) return -1; if(data[i+1] == 0xC0) { *height = data[i+5]*256 + data[i+6]; *width = data[i+7]*256 + data[i+8]; return 0; } i+=2; if (i + 1 < data_size) block_length = data[i] * 256 + data[i+1]; } } } return -1; }
169,235
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: on_handler_vanished(GDBusConnection *connection, const gchar *name, gpointer user_data) { struct tcmur_handler *handler = user_data; struct dbus_info *info = handler->opaque; if (info->register_invocation) { char *reason; reason = g_strdup_printf("Cannot find handler bus name: " "org.kernel.TCMUService1.HandlerManager1.%s", handler->subtype); g_dbus_method_invocation_return_value(info->register_invocation, g_variant_new("(bs)", FALSE, reason)); g_free(reason); } tcmur_unregister_handler(handler); dbus_unexport_handler(handler); } Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS Trying to unregister an internal handler ended up in a SEGFAULT, because the tcmur_handler->opaque was NULL. Way to reproduce: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow we use a newly introduced boolean in struct tcmur_handler for keeping track of external handlers. As suggested by mikechristie adjusting the public data structure is acceptable. CWE ID: CWE-476
on_handler_vanished(GDBusConnection *connection, const gchar *name, gpointer user_data) { struct tcmur_handler *handler = user_data; struct dbus_info *info = handler->opaque; if (info->register_invocation) { char *reason; reason = g_strdup_printf("Cannot find handler bus name: " "org.kernel.TCMUService1.HandlerManager1.%s", handler->subtype); g_dbus_method_invocation_return_value(info->register_invocation, g_variant_new("(bs)", FALSE, reason)); g_free(reason); } tcmur_unregister_dbus_handler(handler); dbus_unexport_handler(handler); }
167,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::allocate_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = m_out_mem_ptr; for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer"); close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
OMX_ERRORTYPE omx_video::allocate_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = m_out_mem_ptr; for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = NULL; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer"); m_pOutput_pmem[i].buffer = NULL; close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); if (m_pOutput_pmem[i].buffer == NULL) { DEBUG_PRINT_ERROR("%s: Failed to allocate native-handle", __func__); return OMX_ErrorInsufficientResources; } (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; }
173,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FakeCrosDisksClient::Mount(const std::string& source_path, const std::string& source_format, const std::string& mount_label, const std::vector<std::string>& mount_options, MountAccessMode access_mode, RemountOption remount, VoidDBusMethodCallback callback) { MountType type = source_format.empty() ? MOUNT_TYPE_DEVICE : MOUNT_TYPE_ARCHIVE; if (GURL(source_path).is_valid()) type = MOUNT_TYPE_NETWORK_STORAGE; base::FilePath mounted_path; switch (type) { case MOUNT_TYPE_ARCHIVE: mounted_path = GetArchiveMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_DEVICE: mounted_path = GetRemovableDiskMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_NETWORK_STORAGE: if (custom_mount_point_callback_) { mounted_path = custom_mount_point_callback_.Run(source_path, mount_options); } break; case MOUNT_TYPE_INVALID: NOTREACHED(); return; } mounted_paths_.insert(mounted_path); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PerformFakeMount, source_path, mounted_path), base::BindOnce(&FakeCrosDisksClient::DidMount, weak_ptr_factory_.GetWeakPtr(), source_path, type, mounted_path, std::move(callback))); } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <[email protected]> Commit-Queue: Sam McNally <[email protected]> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID:
void FakeCrosDisksClient::Mount(const std::string& source_path, const std::string& source_format, const std::string& mount_label, const std::vector<std::string>& mount_options, MountAccessMode access_mode, RemountOption remount, VoidDBusMethodCallback callback) { MountType type = source_format.empty() ? MOUNT_TYPE_DEVICE : MOUNT_TYPE_ARCHIVE; if (GURL(source_path).is_valid()) type = MOUNT_TYPE_NETWORK_STORAGE; base::FilePath mounted_path; switch (type) { case MOUNT_TYPE_ARCHIVE: mounted_path = GetArchiveMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_DEVICE: mounted_path = GetRemovableDiskMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_NETWORK_STORAGE: if (custom_mount_point_callback_) { mounted_path = custom_mount_point_callback_.Run(source_path, mount_options); } break; case MOUNT_TYPE_INVALID: NOTREACHED(); return; } mounted_paths_.insert(mounted_path); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PerformFakeMount, source_path, mounted_path, type), base::BindOnce(&FakeCrosDisksClient::DidMount, weak_ptr_factory_.GetWeakPtr(), source_path, type, mounted_path, std::move(callback))); }
171,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, bigint *modulus, bigint *pub_exp) { int i, size; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; i = 10; /* start at the first possible non-padded byte */ while (block[i++] && i < sig_len); size = sig_len - i; /* get only the bit we want */ if (size > 0) { int len; const uint8_t *sig_ptr = get_signature(&block[i], &len); if (sig_ptr) { bir = bi_import(ctx, sig_ptr, len); } } free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; } Commit Message: Apply CVE fixes for X509 parsing Apply patches developed by Sze Yiu which correct a vulnerability in X509 parsing. See CVE-2018-16150 and CVE-2018-16149 for more info. CWE ID: CWE-347
static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, uint8_t sig_type, bigint *modulus, bigint *pub_exp) { int i; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); const uint8_t *sig_prefix = NULL; uint8_t sig_prefix_size = 0, hash_len = 0; /* adjust our expections */ switch (sig_type) { case SIG_TYPE_MD5: sig_prefix = sig_prefix_md5; sig_prefix_size = sizeof(sig_prefix_md5); break; case SIG_TYPE_SHA1: sig_prefix = sig_prefix_sha1; sig_prefix_size = sizeof(sig_prefix_sha1); break; case SIG_TYPE_SHA256: sig_prefix = sig_prefix_sha256; sig_prefix_size = sizeof(sig_prefix_sha256); break; case SIG_TYPE_SHA384: sig_prefix = sig_prefix_sha384; sig_prefix_size = sizeof(sig_prefix_sha384); break; case SIG_TYPE_SHA512: sig_prefix = sig_prefix_sha512; sig_prefix_size = sizeof(sig_prefix_sha512); break; } if (sig_prefix) hash_len = sig_prefix[sig_prefix_size - 1]; /* check length (#A) */ if (sig_len < 2 + 8 + 1 + sig_prefix_size + hash_len) goto err; /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* check the first 2 bytes */ if (block[0] != 0 || block[1] != 1) goto err; /* check the padding */ i = 2; /* start at the first padding byte */ while (i < sig_len - 1 - sig_prefix_size - hash_len) { /* together with (#A), we require at least 8 bytes of padding */ if (block[i++] != 0xFF) goto err; } /* check end of padding */ if (block[i++] != 0) goto err; /* check the ASN.1 metadata */ if (memcmp_P(block+i, sig_prefix, sig_prefix_size)) goto err; /* now we can get the hash we need */ bir = bi_import(ctx, block + i + sig_prefix_size, hash_len); err: free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; }
169,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { if ((*q++ = *key << 1)) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\0'; p = (u_char *) data->output + 9; } else { /* * "old"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); } Commit Message: CWE ID: CWE-310
_crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { *q++ = *key << 1; if (*key) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\0'; p = (u_char *) data->output + 9; } else { /* * "old"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); }
165,028