instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Atom::Clear() { delete[] m_string_uid; m_string_uid = NULL; while (m_displays_count > 0) { Display& d = m_displays[--m_displays_count]; d.Clear(); } delete[] m_displays; m_displays = NULL; m_displays_size = 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Atom::Clear()
174,245
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void filter_average_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { uint8_t tmp[64 * 64]; assert(output_width <= 64); assert(output_height <= 64); filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64, output_width, output_height); block2d_average_c(tmp, 64, dst_ptr, dst_stride, output_width, output_height); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void filter_average_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { uint8_t tmp[kMaxDimension * kMaxDimension]; assert(output_width <= kMaxDimension); assert(output_height <= kMaxDimension); filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64, output_width, output_height); block2d_average_c(tmp, 64, dst_ptr, dst_stride, output_width, output_height); }
174,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static InputMethodStatusConnection* GetConnection( void* language_library, LanguageCurrentInputMethodMonitorFunction current_input_method_changed, LanguageRegisterImePropertiesFunction register_ime_properties, LanguageUpdateImePropertyFunction update_ime_property, LanguageConnectionChangeMonitorFunction connection_change_handler) { DCHECK(language_library); DCHECK(current_input_method_changed), DCHECK(register_ime_properties); DCHECK(update_ime_property); InputMethodStatusConnection* object = GetInstance(); if (!object->language_library_) { object->language_library_ = language_library; object->current_input_method_changed_ = current_input_method_changed; object->register_ime_properties_= register_ime_properties; object->update_ime_property_ = update_ime_property; object->connection_change_handler_ = connection_change_handler; object->MaybeRestoreConnections(); } else if (object->language_library_ != language_library) { LOG(ERROR) << "Unknown language_library is passed"; } return object; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static InputMethodStatusConnection* GetConnection( // TODO(satorux,yusukes): Remove use of singleton here. static IBusControllerImpl* GetInstance() { return Singleton<IBusControllerImpl, LeakySingletonTraits<IBusControllerImpl> >::get(); }
170,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_HELP: default: usage(); break; } } /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); numcmpts = jas_image_numcmpts(image); width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; } Commit Message: Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes. CWE ID: CWE-476
int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; debug = 0; /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); numcmpts = jas_image_numcmpts(image); width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }
168,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheUpdateJob::OnDestructionImminent(AppCacheHost* host) { PendingMasters::iterator found = pending_master_entries_.find(host->pending_master_entry_url()); DCHECK(found != pending_master_entries_.end()); PendingHosts& hosts = found->second; PendingHosts::iterator it = std::find(hosts.begin(), hosts.end(), host); DCHECK(it != hosts.end()); hosts.erase(it); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheUpdateJob::OnDestructionImminent(AppCacheHost* host) { PendingMasters::iterator found = pending_master_entries_.find(host->pending_master_entry_url()); CHECK(found != pending_master_entries_.end()); PendingHosts& hosts = found->second; PendingHosts::iterator it = std::find(hosts.begin(), hosts.end(), host); CHECK(it != hosts.end()); hosts.erase(it); }
171,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void llc_conn_handler(struct llc_sap *sap, struct sk_buff *skb) { struct llc_addr saddr, daddr; struct sock *sk; llc_pdu_decode_sa(skb, saddr.mac); llc_pdu_decode_ssap(skb, &saddr.lsap); llc_pdu_decode_da(skb, daddr.mac); llc_pdu_decode_dsap(skb, &daddr.lsap); sk = __llc_lookup(sap, &saddr, &daddr); if (!sk) goto drop; bh_lock_sock(sk); /* * This has to be done here and not at the upper layer ->accept * method because of the way the PROCOM state machine works: * it needs to set several state variables (see, for instance, * llc_adm_actions_2 in net/llc/llc_c_st.c) and send a packet to * the originator of the new connection, and this state has to be * in the newly created struct sock private area. -acme */ if (unlikely(sk->sk_state == TCP_LISTEN)) { struct sock *newsk = llc_create_incoming_sock(sk, skb->dev, &saddr, &daddr); if (!newsk) goto drop_unlock; skb_set_owner_r(skb, newsk); } else { /* * Can't be skb_set_owner_r, this will be done at the * llc_conn_state_process function, later on, when we will use * skb_queue_rcv_skb to send it to upper layers, this is * another trick required to cope with how the PROCOM state * machine works. -acme */ skb->sk = sk; } if (!sock_owned_by_user(sk)) llc_conn_rcv(sk, skb); else { dprintk("%s: adding to backlog...\n", __func__); llc_set_backlog_type(skb, LLC_PACKET); if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) goto drop_unlock; } out: bh_unlock_sock(sk); sock_put(sk); return; drop: kfree_skb(skb); return; drop_unlock: kfree_skb(skb); goto out; } Commit Message: net/llc: avoid BUG_ON() in skb_orphan() It seems nobody used LLC since linux-3.12. Fortunately fuzzers like syzkaller still know how to run this code, otherwise it would be no fun. Setting skb->sk without skb->destructor leads to all kinds of bugs, we now prefer to be very strict about it. Ideally here we would use skb_set_owner() but this helper does not exist yet, only CAN seems to have a private helper for that. Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
void llc_conn_handler(struct llc_sap *sap, struct sk_buff *skb) { struct llc_addr saddr, daddr; struct sock *sk; llc_pdu_decode_sa(skb, saddr.mac); llc_pdu_decode_ssap(skb, &saddr.lsap); llc_pdu_decode_da(skb, daddr.mac); llc_pdu_decode_dsap(skb, &daddr.lsap); sk = __llc_lookup(sap, &saddr, &daddr); if (!sk) goto drop; bh_lock_sock(sk); /* * This has to be done here and not at the upper layer ->accept * method because of the way the PROCOM state machine works: * it needs to set several state variables (see, for instance, * llc_adm_actions_2 in net/llc/llc_c_st.c) and send a packet to * the originator of the new connection, and this state has to be * in the newly created struct sock private area. -acme */ if (unlikely(sk->sk_state == TCP_LISTEN)) { struct sock *newsk = llc_create_incoming_sock(sk, skb->dev, &saddr, &daddr); if (!newsk) goto drop_unlock; skb_set_owner_r(skb, newsk); } else { /* * Can't be skb_set_owner_r, this will be done at the * llc_conn_state_process function, later on, when we will use * skb_queue_rcv_skb to send it to upper layers, this is * another trick required to cope with how the PROCOM state * machine works. -acme */ skb_orphan(skb); sock_hold(sk); skb->sk = sk; skb->destructor = sock_efree; } if (!sock_owned_by_user(sk)) llc_conn_rcv(sk, skb); else { dprintk("%s: adding to backlog...\n", __func__); llc_set_backlog_type(skb, LLC_PACKET); if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) goto drop_unlock; } out: bh_unlock_sock(sk); sock_put(sk); return; drop: kfree_skb(skb); return; drop_unlock: kfree_skb(skb); goto out; }
168,348
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void VectorClamp3(DDSVector3 *value) { value->x = MinF(1.0f,MaxF(0.0f,value->x)); value->y = MinF(1.0f,MaxF(0.0f,value->y)); value->z = MinF(1.0f,MaxF(0.0f,value->z)); } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static inline void VectorClamp3(DDSVector3 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); }
168,907
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dhcpv6_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint16_t type, optlen; i = 0; while (i < length) { tlv = cp + i; type = EXTRACT_16BITS(tlv); optlen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 4 )); switch (type) { case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: { if (optlen % 16 != 0) { ND_PRINT((ndo, " %s", istr)); return -1; } for (t = 0; t < optlen; t += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t))); } break; case DH6OPT_DOMAIN_LIST: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 4 + optlen; } return 0; } Commit Message: CVE-2017-13042/HNCP: add DHCPv6-Data bounds checks hncp_print_rec() validates each HNCP TLV to be within the declared as well as the on-the-wire packet space. However, dhcpv6_print() in the same file didn't do the same for the DHCPv6 options within the HNCP DHCPv6-Data TLV value, which could cause an out-of-bounds read when decoding an invalid packet. Add missing checks to dhcpv6_print(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
dhcpv6_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint16_t type, optlen; i = 0; while (i < length) { if (i + 4 > length) return -1; tlv = cp + i; type = EXTRACT_16BITS(tlv); optlen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 4 )); if (i + 4 + optlen > length) return -1; switch (type) { case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: { if (optlen % 16 != 0) { ND_PRINT((ndo, " %s", istr)); return -1; } for (t = 0; t < optlen; t += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t))); } break; case DH6OPT_DOMAIN_LIST: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 4 + optlen; } return 0; }
167,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ContainOnlyOneKeyboardLayout( const ImeConfigValue& value) { return (value.type == ImeConfigValue::kValueTypeStringList && value.string_list_value.size() == 1 && chromeos::input_method::IsKeyboardLayout( value.string_list_value[0])); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ContainOnlyOneKeyboardLayout( const input_method::ImeConfigValue& value) { return (value.type == input_method::ImeConfigValue::kValueTypeStringList && value.string_list_value.size() == 1 && input_method::IsKeyboardLayout( value.string_list_value[0])); }
170,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = rnd.Rand8() - rnd.Rand8(); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = (rnd.Rand16() & mask_) - (rnd.Rand16() & mask_); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } }
174,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ZSTD_encodeSequences_body( void* dst, size_t dstCapacity, FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, seqDef const* sequences, size_t nbSeq, int longOffsets) { BIT_CStream_t blockStream; FSE_CState_t stateMatchLength; FSE_CState_t stateOffsetBits; FSE_CState_t stateLitLength; CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ /* first symbols */ FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); if (longOffsets) { U32 const ofBits = ofCodeTable[nbSeq-1]; int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); BIT_flushBits(&blockStream); } BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, ofBits - extraBits); } else { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); } BIT_flushBits(&blockStream); { size_t n; for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */ BYTE const llCode = llCodeTable[n]; BYTE const ofCode = ofCodeTable[n]; BYTE const mlCode = mlCodeTable[n]; U32 const llBits = LL_bits[llCode]; U32 const ofBits = ofCode; U32 const mlBits = ML_bits[mlCode]; DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u", sequences[n].litLength, sequences[n].matchLength + MINMATCH, sequences[n].offset); /* 32b*/ /* 64b*/ /* (7)*/ /* (7)*/ FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */ FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */ if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/ FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */ if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog))) BIT_flushBits(&blockStream); /* (7)*/ BIT_addBits(&blockStream, sequences[n].litLength, llBits); if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); if (longOffsets) { int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[n].offset, extraBits); BIT_flushBits(&blockStream); /* (7)*/ } BIT_addBits(&blockStream, sequences[n].offset >> extraBits, ofBits - extraBits); /* 31 */ } else { BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ } BIT_flushBits(&blockStream); /* (7)*/ } } DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog); FSE_flushCState(&blockStream, &stateMatchLength); DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog); FSE_flushCState(&blockStream, &stateOffsetBits); DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog); FSE_flushCState(&blockStream, &stateLitLength); { size_t const streamSize = BIT_closeCStream(&blockStream); if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */ return streamSize; } } Commit Message: fixed T36302429 CWE ID: CWE-362
ZSTD_encodeSequences_body( void* dst, size_t dstCapacity, FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, seqDef const* sequences, size_t nbSeq, int longOffsets) { BIT_CStream_t blockStream; FSE_CState_t stateMatchLength; FSE_CState_t stateOffsetBits; FSE_CState_t stateLitLength; CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)", (int)(blockStream.endPtr - blockStream.startPtr), (unsigned)dstCapacity); /* first symbols */ FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); if (longOffsets) { U32 const ofBits = ofCodeTable[nbSeq-1]; int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); BIT_flushBits(&blockStream); } BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, ofBits - extraBits); } else { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); } BIT_flushBits(&blockStream); { size_t n; for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */ BYTE const llCode = llCodeTable[n]; BYTE const ofCode = ofCodeTable[n]; BYTE const mlCode = mlCodeTable[n]; U32 const llBits = LL_bits[llCode]; U32 const ofBits = ofCode; U32 const mlBits = ML_bits[mlCode]; DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u", sequences[n].litLength, sequences[n].matchLength + MINMATCH, sequences[n].offset); /* 32b*/ /* 64b*/ /* (7)*/ /* (7)*/ FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */ FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */ if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/ FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */ if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog))) BIT_flushBits(&blockStream); /* (7)*/ BIT_addBits(&blockStream, sequences[n].litLength, llBits); if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); if (longOffsets) { int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[n].offset, extraBits); BIT_flushBits(&blockStream); /* (7)*/ } BIT_addBits(&blockStream, sequences[n].offset >> extraBits, ofBits - extraBits); /* 31 */ } else { BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ } BIT_flushBits(&blockStream); /* (7)*/ DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr)); } } DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog); FSE_flushCState(&blockStream, &stateMatchLength); DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog); FSE_flushCState(&blockStream, &stateOffsetBits); DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog); FSE_flushCState(&blockStream, &stateLitLength); { size_t const streamSize = BIT_closeCStream(&blockStream); if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */ return streamSize; } }
169,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while (y < height) { int c = getc(IN); if (c == EOF) { return OPJ_FALSE; } if (c) { int j, c1_int; OPJ_UINT8 c1; c1_int = getc(IN); if (c1_int == EOF) { return OPJ_FALSE; } c1 = (OPJ_UINT8)c1_int; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = c1; } } else { c = getc(IN); if (c == EOF) { return OPJ_FALSE; } if (c == 0x00) { /* EOL */ x = 0; ++y; pix = pData + y * stride + x; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); if (c == EOF) { return OPJ_FALSE; } x += (OPJ_UINT32)c; c = getc(IN); if (c == EOF) { return OPJ_FALSE; } y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 */ int j; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { int c1_int; OPJ_UINT8 c1; c1_int = getc(IN); if (c1_int == EOF) { return OPJ_FALSE; } c1 = (OPJ_UINT8)c1_int; *pix = c1; } if ((OPJ_UINT32)c & 1U) { /* skip padding byte */ c = getc(IN); if (c == EOF) { return OPJ_FALSE; } } } } }/* while() */ return OPJ_TRUE; } Commit Message: convertbmp: detect invalid file dimensions early width/length dimensions read from bmp headers are not necessarily valid. For instance they may have been maliciously set to very large values with the intention to cause DoS (large memory allocation, stack overflow). In these cases we want to detect the invalid size as early as possible. This commit introduces a counter which verifies that the number of written bytes corresponds to the advertized width/length. Fixes #1059 (CVE-2018-6616). CWE ID: CWE-400
static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y, written; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = written = 0U; while (y < height) { int c = getc(IN); if (c == EOF) { return OPJ_FALSE; } if (c) { int j, c1_int; OPJ_UINT8 c1; c1_int = getc(IN); if (c1_int == EOF) { return OPJ_FALSE; } c1 = (OPJ_UINT8)c1_int; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = c1; written++; } } else { c = getc(IN); if (c == EOF) { return OPJ_FALSE; } if (c == 0x00) { /* EOL */ x = 0; ++y; pix = pData + y * stride + x; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); if (c == EOF) { return OPJ_FALSE; } x += (OPJ_UINT32)c; c = getc(IN); if (c == EOF) { return OPJ_FALSE; } y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 */ int j; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { int c1_int; OPJ_UINT8 c1; c1_int = getc(IN); if (c1_int == EOF) { return OPJ_FALSE; } c1 = (OPJ_UINT8)c1_int; *pix = c1; written++; } if ((OPJ_UINT32)c & 1U) { /* skip padding byte */ c = getc(IN); if (c == EOF) { return OPJ_FALSE; } } } } }/* while() */ if (written != width * height) { fprintf(stderr, "warning, image's actual size does not match advertized one\n"); return OPJ_FALSE; } return OPJ_TRUE; }
169,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pseudo_ulog( ClassAd *ad ) { ULogEvent *event = instantiateEvent(ad); int result = 0; char const *critical_error = NULL; MyString CriticalErrorBuf; bool event_already_logged = false; bool put_job_on_hold = false; char const *hold_reason = NULL; char *hold_reason_buf = NULL; int hold_reason_code = 0; int hold_reason_sub_code = 0; if(!event) { MyString add_str; ad->sPrint(add_str); dprintf( D_ALWAYS, "invalid event ClassAd in pseudo_ulog: %s\n", add_str.Value()); return -1; } if(ad->LookupInteger(ATTR_HOLD_REASON_CODE,hold_reason_code)) { put_job_on_hold = true; ad->LookupInteger(ATTR_HOLD_REASON_SUBCODE,hold_reason_sub_code); ad->LookupString(ATTR_HOLD_REASON,&hold_reason_buf); if(hold_reason_buf) { hold_reason = hold_reason_buf; } } if( event->eventNumber == ULOG_REMOTE_ERROR ) { RemoteErrorEvent *err = (RemoteErrorEvent *)event; if(!err->getExecuteHost() || !*err->getExecuteHost()) { char *execute_host = NULL; thisRemoteResource->getMachineName(execute_host); err->setExecuteHost(execute_host); delete[] execute_host; } if(err->isCriticalError()) { CriticalErrorBuf.sprintf( "Error from %s: %s", err->getExecuteHost(), err->getErrorText()); critical_error = CriticalErrorBuf.Value(); if(!hold_reason) { hold_reason = critical_error; } BaseShadow::log_except(critical_error); event_already_logged = true; } } if( !event_already_logged && !Shadow->uLog.writeEvent( event, ad ) ) { MyString add_str; ad->sPrint(add_str); dprintf( D_ALWAYS, "unable to log event in pseudo_ulog: %s\n", add_str.Value()); result = -1; } if(put_job_on_hold) { hold_reason = critical_error; if(!hold_reason) { hold_reason = "Job put on hold by remote host."; } Shadow->holdJobAndExit(hold_reason,hold_reason_code,hold_reason_sub_code); } if( critical_error ) { Shadow->exception_already_logged = true; EXCEPT(critical_error); } delete event; return result; } Commit Message: CWE ID: CWE-134
pseudo_ulog( ClassAd *ad ) { ULogEvent *event = instantiateEvent(ad); int result = 0; char const *critical_error = NULL; MyString CriticalErrorBuf; bool event_already_logged = false; bool put_job_on_hold = false; char const *hold_reason = NULL; char *hold_reason_buf = NULL; int hold_reason_code = 0; int hold_reason_sub_code = 0; if(!event) { MyString add_str; ad->sPrint(add_str); dprintf( D_ALWAYS, "invalid event ClassAd in pseudo_ulog: %s\n", add_str.Value()); return -1; } if(ad->LookupInteger(ATTR_HOLD_REASON_CODE,hold_reason_code)) { put_job_on_hold = true; ad->LookupInteger(ATTR_HOLD_REASON_SUBCODE,hold_reason_sub_code); ad->LookupString(ATTR_HOLD_REASON,&hold_reason_buf); if(hold_reason_buf) { hold_reason = hold_reason_buf; } } if( event->eventNumber == ULOG_REMOTE_ERROR ) { RemoteErrorEvent *err = (RemoteErrorEvent *)event; if(!err->getExecuteHost() || !*err->getExecuteHost()) { char *execute_host = NULL; thisRemoteResource->getMachineName(execute_host); err->setExecuteHost(execute_host); delete[] execute_host; } if(err->isCriticalError()) { CriticalErrorBuf.sprintf( "Error from %s: %s", err->getExecuteHost(), err->getErrorText()); critical_error = CriticalErrorBuf.Value(); if(!hold_reason) { hold_reason = critical_error; } BaseShadow::log_except(critical_error); event_already_logged = true; } } if( !event_already_logged && !Shadow->uLog.writeEvent( event, ad ) ) { MyString add_str; ad->sPrint(add_str); dprintf( D_ALWAYS, "unable to log event in pseudo_ulog: %s\n", add_str.Value()); result = -1; } if(put_job_on_hold) { hold_reason = critical_error; if(!hold_reason) { hold_reason = "Job put on hold by remote host."; } Shadow->holdJobAndExit(hold_reason,hold_reason_code,hold_reason_sub_code); } if( critical_error ) { Shadow->exception_already_logged = true; EXCEPT("%s", critical_error); } delete event; return result; }
165,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssize_t nbd_wr_syncv(QIOChannel *ioc, struct iovec *iov, size_t niov, size_t length, bool do_read) { ssize_t done = 0; Error *local_err = NULL; struct iovec *local_iov = g_new(struct iovec, niov); struct iovec *local_iov_head = local_iov; unsigned int nlocal_iov = niov; nlocal_iov = iov_copy(local_iov, nlocal_iov, iov, niov, 0, length); while (nlocal_iov > 0) { ssize_t len; if (do_read) { len = qio_channel_readv(ioc, local_iov, nlocal_iov, &local_err); } else { len = qio_channel_writev(ioc, local_iov, nlocal_iov, &local_err); } if (len == QIO_CHANNEL_ERR_BLOCK) { if (qemu_in_coroutine()) { /* XXX figure out if we can create a variant on * qio_channel_yield() that works with AIO contexts * and consider using that in this branch */ qemu_coroutine_yield(); } else if (done) { /* XXX this is needed by nbd_reply_ready. */ qio_channel_wait(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } } else if (done) { /* XXX this is needed by nbd_reply_ready. */ qio_channel_wait(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } continue; } if (len < 0) { TRACE("I/O error: %s", error_get_pretty(local_err)); error_free(local_err); /* XXX handle Error objects */ done = -EIO; goto cleanup; } if (do_read && len == 0) { break; } iov_discard_front(&local_iov, &nlocal_iov, len); done += len; } Commit Message: CWE ID: CWE-20
ssize_t nbd_wr_syncv(QIOChannel *ioc, struct iovec *iov, size_t niov, size_t length, bool do_read) { ssize_t done = 0; Error *local_err = NULL; struct iovec *local_iov = g_new(struct iovec, niov); struct iovec *local_iov_head = local_iov; unsigned int nlocal_iov = niov; nlocal_iov = iov_copy(local_iov, nlocal_iov, iov, niov, 0, length); while (nlocal_iov > 0) { ssize_t len; if (do_read) { len = qio_channel_readv(ioc, local_iov, nlocal_iov, &local_err); } else { len = qio_channel_writev(ioc, local_iov, nlocal_iov, &local_err); } if (len == QIO_CHANNEL_ERR_BLOCK) { if (qemu_in_coroutine()) { qio_channel_yield(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } } else if (done) { /* XXX this is needed by nbd_reply_ready. */ qio_channel_wait(ioc, do_read ? G_IO_IN : G_IO_OUT); } else { return -EAGAIN; } continue; } if (len < 0) { TRACE("I/O error: %s", error_get_pretty(local_err)); error_free(local_err); /* XXX handle Error objects */ done = -EIO; goto cleanup; } if (do_read && len == 0) { break; } iov_discard_front(&local_iov, &nlocal_iov, len); done += len; }
165,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed( const GURL& method_manifest_url, const std::vector<GURL>& default_applications, const std::vector<url::Origin>& supported_origins, bool all_origins_supported) { number_of_payment_method_manifest_to_parse_--; if (web_contents() == nullptr) return; content::PermissionManager* permission_manager = web_contents()->GetBrowserContext()->GetPermissionManager(); if (permission_manager == nullptr) return; for (const auto& url : default_applications) { if (downloaded_web_app_manifests_.find(url) != downloaded_web_app_manifests_.end()) { continue; } if (permission_manager->GetPermissionStatus( content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(), url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) { continue; } number_of_web_app_manifest_to_download_++; downloaded_web_app_manifests_.insert(url); downloader_->DownloadWebAppManifest( url, base::BindOnce( &InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded, weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url)); } FinishCrawlingPaymentAppsIfReady(); } Commit Message: [Payments] Restrict just-in-time payment handler to payment method domain and its subdomains Bug: 853937 Change-Id: I148b3d96950a9d90fa362e580e9593caa6b92a36 Reviewed-on: https://chromium-review.googlesource.com/1132116 Reviewed-by: Mathieu Perreault <mathp@chromium.org> Commit-Queue: Ganggui Tang <gogerald@chromium.org> Cr-Commit-Position: refs/heads/master@{#573911} CWE ID:
void InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed( const GURL& method_manifest_url, const std::vector<GURL>& default_applications, const std::vector<url::Origin>& supported_origins, bool all_origins_supported) { number_of_payment_method_manifest_to_parse_--; if (web_contents() == nullptr) return; content::PermissionManager* permission_manager = web_contents()->GetBrowserContext()->GetPermissionManager(); if (permission_manager == nullptr) return; for (const auto& url : default_applications) { if (downloaded_web_app_manifests_.find(url) != downloaded_web_app_manifests_.end()) { continue; } if (!net::registry_controlled_domains::SameDomainOrHost( method_manifest_url, url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { WarnIfPossible("Installable payment app from " + url.spec() + " is not allowed for the method " + method_manifest_url.spec()); continue; } if (permission_manager->GetPermissionStatus( content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(), url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) { continue; } number_of_web_app_manifest_to_download_++; downloaded_web_app_manifests_.insert(url); downloader_->DownloadWebAppManifest( url, base::BindOnce( &InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded, weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url)); } FinishCrawlingPaymentAppsIfReady(); }
172,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!arp_checkentry(&e->arp)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-264
static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!arp_checkentry(&e->arp)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
167,216
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } #ifdef HAVE_GETSPNAM if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif if (strcmp(user_password, (char *) crypt(password, user_password)) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); return -1; } */ return 0; #endif } Commit Message: Don't crash if crypt() fails. It can fail, so make sure it doesn't before comparing its result with the password. This addresses Include Security issue F12: [libpcap] Remote Packet Capture Daemon Null Pointer Dereference Denial of Service. CWE ID: CWE-476
daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif char *crypt_password; if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } #ifdef HAVE_GETSPNAM if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif crypt_password = crypt(password, user_password); if (crypt_password == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } if (strcmp(user_password, crypt_password) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); return -1; } */ return 0; #endif }
169,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sig_server_connect_copy(SERVER_CONNECT_REC **dest, IRC_SERVER_CONNECT_REC *src) { IRC_SERVER_CONNECT_REC *rec; g_return_if_fail(dest != NULL); if (!IS_IRC_SERVER_CONNECT(src)) return; rec = g_new0(IRC_SERVER_CONNECT_REC, 1); rec->chat_type = IRC_PROTOCOL; rec->max_cmds_at_once = src->max_cmds_at_once; rec->cmd_queue_speed = src->cmd_queue_speed; rec->max_query_chans = src->max_query_chans; rec->max_kicks = src->max_kicks; rec->max_modes = src->max_modes; rec->max_msgs = src->max_msgs; rec->max_whois = src->max_whois; rec->usermode = g_strdup(src->usermode); rec->alternate_nick = g_strdup(src->alternate_nick); rec->sasl_mechanism = src->sasl_mechanism; rec->sasl_username = src->sasl_username; rec->sasl_password = src->sasl_password; *dest = (SERVER_CONNECT_REC *) rec; } Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect copy sasl username and password values CWE ID: CWE-416
static void sig_server_connect_copy(SERVER_CONNECT_REC **dest, IRC_SERVER_CONNECT_REC *src) { IRC_SERVER_CONNECT_REC *rec; g_return_if_fail(dest != NULL); if (!IS_IRC_SERVER_CONNECT(src)) return; rec = g_new0(IRC_SERVER_CONNECT_REC, 1); rec->chat_type = IRC_PROTOCOL; rec->max_cmds_at_once = src->max_cmds_at_once; rec->cmd_queue_speed = src->cmd_queue_speed; rec->max_query_chans = src->max_query_chans; rec->max_kicks = src->max_kicks; rec->max_modes = src->max_modes; rec->max_msgs = src->max_msgs; rec->max_whois = src->max_whois; rec->usermode = g_strdup(src->usermode); rec->alternate_nick = g_strdup(src->alternate_nick); rec->sasl_mechanism = src->sasl_mechanism; rec->sasl_username = g_strdup(src->sasl_username); rec->sasl_password = g_strdup(src->sasl_password); *dest = (SERVER_CONNECT_REC *) rec; }
169,643
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) { if (address < payload()) return nullptr; if (!m_objectStartBitMapComputed) populateObjectStartBitMap(); size_t objectOffset = address - payload(); size_t objectStartNumber = objectOffset / allocationGranularity; size_t mapIndex = objectStartNumber / 8; ASSERT(mapIndex < objectStartBitMapSize); size_t bit = objectStartNumber & 7; uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1); while (!byte) { ASSERT(mapIndex > 0); byte = m_objectStartBitMap[--mapIndex]; } int leadingZeroes = numberOfLeadingZeroes(byte); objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes; objectOffset = objectStartNumber * allocationGranularity; Address objectAddress = objectOffset + payload(); HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress); if (header->isFree()) return nullptr; ASSERT(header->checkHeader()); return header; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) { if (address < payload()) return nullptr; if (!m_objectStartBitMapComputed) populateObjectStartBitMap(); size_t objectOffset = address - payload(); size_t objectStartNumber = objectOffset / allocationGranularity; size_t mapIndex = objectStartNumber / 8; ASSERT(mapIndex < objectStartBitMapSize); size_t bit = objectStartNumber & 7; uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1); while (!byte) { ASSERT(mapIndex > 0); byte = m_objectStartBitMap[--mapIndex]; } int leadingZeroes = numberOfLeadingZeroes(byte); objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes; objectOffset = objectStartNumber * allocationGranularity; Address objectAddress = objectOffset + payload(); HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress); if (header->isFree()) return nullptr; header->checkHeader(); return header; }
172,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioOutputDevice::AudioOutputDevice( AudioOutputIPC* ipc, const scoped_refptr<base::MessageLoopProxy>& io_loop) : ScopedLoopObserver(io_loop), input_channels_(0), callback_(NULL), ipc_(ipc), stream_id_(0), play_on_start_(true), is_started_(false), audio_thread_(new AudioDeviceThread()) { CHECK(ipc_); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
AudioOutputDevice::AudioOutputDevice( AudioOutputIPC* ipc, const scoped_refptr<base::MessageLoopProxy>& io_loop) : ScopedLoopObserver(io_loop), input_channels_(0), callback_(NULL), ipc_(ipc), stream_id_(0), play_on_start_(true), is_started_(false) { CHECK(ipc_); }
170,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::CreateBlockGroup(long long start_offset, long long size, long long discard_padding) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = start_offset; const long long stop = start_offset + size; long long prev = 1; // nonce long long next = 0; // nonce long long duration = -1; // really, this is unsigned long long bpos = -1; long long bsize = -1; 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); // TODO assert((pos + len) <= stop); pos += len; // consume size if (id == 0x21) { // Block ID if (bpos < 0) { // Block ID bpos = pos; bsize = size; } } else if (id == 0x1B) { // Duration ID assert(size <= 8); duration = UnserializeUInt(pReader, pos, size); assert(duration >= 0); // TODO } else if (id == 0x7B) { // ReferenceBlock assert(size <= 8); const long size_ = static_cast<long>(size); long long time; long status = UnserializeInt(pReader, pos, size_, time); assert(status == 0); if (status != 0) return -1; if (time <= 0) // see note above prev = time; else // weird next = time; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); assert(bpos >= 0); assert(bsize >= 0); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding); if (pEntry == NULL) return -1; // generic error BlockGroup* const p = static_cast<BlockGroup*>(pEntry); const long status = p->Parse(); if (status == 0) { // success ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } 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
long Cluster::CreateBlockGroup(long long start_offset, long long size, long long discard_padding) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = start_offset; const long long stop = start_offset + size; long long prev = 1; // nonce long long next = 0; // nonce long long duration = -1; // really, this is unsigned long long bpos = -1; long long bsize = -1; while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if (id < 0 || (pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume size if (id == 0x21) { // Block ID if (bpos < 0) { // Block ID bpos = pos; bsize = size; } } else if (id == 0x1B) { // Duration ID if (size > 8) return E_FILE_FORMAT_INVALID; duration = UnserializeUInt(pReader, pos, size); if (duration < 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x7B) { // ReferenceBlock if (size > 8 || size <= 0) return E_FILE_FORMAT_INVALID; const long size_ = static_cast<long>(size); long long time; long status = UnserializeInt(pReader, pos, size_, time); assert(status == 0); if (status != 0) return -1; if (time <= 0) // see note above prev = time; else // weird next = time; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (bpos < 0) return E_FILE_FORMAT_INVALID; if (pos != stop) return E_FILE_FORMAT_INVALID; assert(bsize >= 0); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding); if (pEntry == NULL) return -1; // generic error BlockGroup* const p = static_cast<BlockGroup*>(pEntry); const long status = p->Parse(); if (status == 0) { // success ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; }
173,806
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, struct flowi *fl, struct request_sock *req, struct tcp_fastopen_cookie *foc, bool attach_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &fl->u.ip6; struct sk_buff *skb; int err = -ENOMEM; /* First, grab a route. */ if (!dst && (dst = inet6_csk_route_req(sk, fl6, req, IPPROTO_TCP)) == NULL) goto done; skb = tcp_make_synack(sk, dst, req, foc, attach_req); if (skb) { __tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; if (np->repflow && ireq->pktopts) fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); err = ip6_xmit(sk, skb, fl6, np->opt, np->tclass); err = net_xmit_eval(err); } done: return err; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, struct flowi *fl, struct request_sock *req, struct tcp_fastopen_cookie *foc, bool attach_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &fl->u.ip6; struct sk_buff *skb; int err = -ENOMEM; /* First, grab a route. */ if (!dst && (dst = inet6_csk_route_req(sk, fl6, req, IPPROTO_TCP)) == NULL) goto done; skb = tcp_make_synack(sk, dst, req, foc, attach_req); if (skb) { __tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; if (np->repflow && ireq->pktopts) fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); err = ip6_xmit(sk, skb, fl6, rcu_dereference(np->opt), np->tclass); err = net_xmit_eval(err); } done: return err; }
167,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: hash_foreach (gpointer key, gpointer val, gpointer user_data) { const char *keystr = key; const char *valstr = val; guint *count = user_data; *count += (strlen (keystr) + strlen (valstr)); g_print ("%s -> %s\n", keystr, valstr); } Commit Message: CWE ID: CWE-264
hash_foreach (gpointer key, gpointer val, gpointer user_data)
165,084
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if (p == q || size < 16 || size > 256) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); } Commit Message: CWE ID: CWE-189
Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if ((p == q) || (size < 16) || (size > 256)) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); }
168,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) { int code = 0; font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42"); if (!font->font) return gs_throw(gs_error_VMerror, "out of memory"); /* no shortage of things to initialize */ { gs_font_type42 *p42 = (gs_font_type42*) font->font; /* Common to all fonts: */ p42->next = 0; p42->prev = 0; p42->memory = ctx->memory; p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ p42->base = font->font; /* NB also set by gs_definefont later */ p42->is_resource = false; gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); p42->id = gs_next_ids(ctx->memory, 1); p42->client_data = font; /* that's us */ /* this is overwritten in grid_fit() */ gs_make_identity(&p42->FontMatrix); gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ p42->FontType = ft_TrueType; p42->BitmapWidths = false; p42->ExactSize = fbit_use_outlines; p42->InBetweenSize = fbit_use_outlines; p42->TransformedChar = fbit_use_outlines; p42->WMode = 0; p42->PaintType = 0; p42->StrokeWidth = 0; p42->is_cached = 0; p42->procs.define_font = gs_no_define_font; p42->procs.make_font = gs_no_make_font; p42->procs.font_info = gs_type42_font_info; p42->procs.same_font = gs_default_same_font; p42->procs.encode_char = xps_true_callback_encode_char; p42->procs.decode_glyph = xps_true_callback_decode_glyph; p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; p42->procs.glyph_info = gs_type42_glyph_info; p42->procs.glyph_outline = gs_type42_glyph_outline; p42->procs.glyph_name = xps_true_callback_glyph_name; p42->procs.init_fstack = gs_default_init_fstack; p42->procs.next_char_glyph = gs_default_next_char_glyph; p42->procs.build_char = xps_true_callback_build_char; memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); xps_load_sfnt_name(font, (char*)p42->font_name.chars); p42->font_name.size = strlen((char*)p42->font_name.chars); memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); p42->key_name.size = strlen((char*)p42->key_name.chars); /* Base font specific: */ p42->FontBBox.p.x = 0; p42->FontBBox.p.y = 0; p42->FontBBox.q.x = 0; p42->FontBBox.q.y = 0; uid_set_UniqueID(&p42->UID, p42->id); p42->encoding_index = ENCODING_INDEX_UNKNOWN; p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; p42->FAPI = 0; p42->FAPI_font_data = 0; /* Type 42 specific: */ p42->data.string_proc = xps_true_callback_string_proc; p42->data.proc_data = font; gs_type42_font_init(p42, font->subfontid); p42->data.get_glyph_index = xps_true_get_glyph_index; } if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { return(code); } code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); return code; } Commit Message: CWE ID: CWE-119
xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) { int code = 0; font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42"); if (!font->font) return gs_throw(gs_error_VMerror, "out of memory"); /* no shortage of things to initialize */ { gs_font_type42 *p42 = (gs_font_type42*) font->font; /* Common to all fonts: */ p42->next = 0; p42->prev = 0; p42->memory = ctx->memory; p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ p42->base = font->font; /* NB also set by gs_definefont later */ p42->is_resource = false; gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); p42->id = gs_next_ids(ctx->memory, 1); p42->client_data = font; /* that's us */ /* this is overwritten in grid_fit() */ gs_make_identity(&p42->FontMatrix); gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ p42->FontType = ft_TrueType; p42->BitmapWidths = false; p42->ExactSize = fbit_use_outlines; p42->InBetweenSize = fbit_use_outlines; p42->TransformedChar = fbit_use_outlines; p42->WMode = 0; p42->PaintType = 0; p42->StrokeWidth = 0; p42->is_cached = 0; p42->procs.define_font = gs_no_define_font; p42->procs.make_font = gs_no_make_font; p42->procs.font_info = gs_type42_font_info; p42->procs.same_font = gs_default_same_font; p42->procs.encode_char = xps_true_callback_encode_char; p42->procs.decode_glyph = xps_true_callback_decode_glyph; p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; p42->procs.glyph_info = gs_type42_glyph_info; p42->procs.glyph_outline = gs_type42_glyph_outline; p42->procs.glyph_name = xps_true_callback_glyph_name; p42->procs.init_fstack = gs_default_init_fstack; p42->procs.next_char_glyph = gs_default_next_char_glyph; p42->procs.build_char = xps_true_callback_build_char; memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); xps_load_sfnt_name(font, (char*)p42->font_name.chars, sizeof(p42->font_name.chars)); p42->font_name.size = strlen((char*)p42->font_name.chars); memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); p42->key_name.size = strlen((char*)p42->key_name.chars); /* Base font specific: */ p42->FontBBox.p.x = 0; p42->FontBBox.p.y = 0; p42->FontBBox.q.x = 0; p42->FontBBox.q.y = 0; uid_set_UniqueID(&p42->UID, p42->id); p42->encoding_index = ENCODING_INDEX_UNKNOWN; p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; p42->FAPI = 0; p42->FAPI_font_data = 0; /* Type 42 specific: */ p42->data.string_proc = xps_true_callback_string_proc; p42->data.proc_data = font; gs_type42_font_init(p42, font->subfontid); p42->data.get_glyph_index = xps_true_get_glyph_index; } if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { return(code); } code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); return code; }
164,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); }
172,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sec_recv(RD_BOOL * is_fastpath) { uint8 fastpath_hdr, fastpath_flags; uint16 sec_flags; uint16 channel; STREAM s; while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL) { if (*is_fastpath == True) { /* If fastpath packet is encrypted, read data signature and decrypt */ /* FIXME: extracting flags from hdr could be made less obscure */ fastpath_flags = (fastpath_hdr & 0xC0) >> 6; if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED) { in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); } return s; } if (g_encryption || (!g_licence_issued && !g_licence_error_result)) { /* TS_SECURITY_HEADER */ in_uint16_le(s, sec_flags); in_uint8s(s, 2); /* skip sec_flags_hi */ if (g_encryption) { if (sec_flags & SEC_ENCRYPT) { in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); } if (sec_flags & SEC_LICENSE_PKT) { licence_process(s); continue; } if (sec_flags & SEC_REDIRECTION_PKT) { uint8 swapbyte; in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); /* Check for a redirect packet, starts with 00 04 */ if (s->p[0] == 0 && s->p[1] == 4) { /* for some reason the PDU and the length seem to be swapped. This isn't good, but we're going to do a byte for byte swap. So the first four value appear as: 00 04 XX YY, where XX YY is the little endian length. We're going to use 04 00 as the PDU type, so after our swap this will look like: XX YY 04 00 */ swapbyte = s->p[0]; s->p[0] = s->p[2]; s->p[2] = swapbyte; swapbyte = s->p[1]; s->p[1] = s->p[3]; s->p[3] = swapbyte; swapbyte = s->p[2]; s->p[2] = s->p[3]; s->p[3] = swapbyte; } } } else { if (sec_flags & SEC_LICENSE_PKT) { licence_process(s); continue; } s->p -= 4; } } if (channel != MCS_GLOBAL_CHANNEL) { channel_process(s, channel); continue; } return s; } return NULL; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
sec_recv(RD_BOOL * is_fastpath) { uint8 fastpath_hdr, fastpath_flags; uint16 sec_flags; uint16 channel; STREAM s; struct stream packet; while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL) { packet = *s; if (*is_fastpath == True) { /* If fastpath packet is encrypted, read data signature and decrypt */ /* FIXME: extracting flags from hdr could be made less obscure */ fastpath_flags = (fastpath_hdr & 0xC0) >> 6; if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED) { if (!s_check_rem(s, 8)) { rdp_protocol_error("sec_recv(), consume fastpath signature from stream would overrun", &packet); } in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); } return s; } if (g_encryption || (!g_licence_issued && !g_licence_error_result)) { /* TS_SECURITY_HEADER */ in_uint16_le(s, sec_flags); in_uint8s(s, 2); /* skip sec_flags_hi */ if (g_encryption) { if (sec_flags & SEC_ENCRYPT) { if (!s_check_rem(s, 8)) { rdp_protocol_error("sec_recv(), consume encrypt signature from stream would overrun", &packet); } in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); } if (sec_flags & SEC_LICENSE_PKT) { licence_process(s); continue; } if (sec_flags & SEC_REDIRECTION_PKT) { uint8 swapbyte; if (!s_check_rem(s, 8)) { rdp_protocol_error("sec_recv(), consume redirect signature from stream would overrun", &packet); } in_uint8s(s, 8); /* signature */ sec_decrypt(s->p, s->end - s->p); /* Check for a redirect packet, starts with 00 04 */ if (s->p[0] == 0 && s->p[1] == 4) { /* for some reason the PDU and the length seem to be swapped. This isn't good, but we're going to do a byte for byte swap. So the first four value appear as: 00 04 XX YY, where XX YY is the little endian length. We're going to use 04 00 as the PDU type, so after our swap this will look like: XX YY 04 00 */ swapbyte = s->p[0]; s->p[0] = s->p[2]; s->p[2] = swapbyte; swapbyte = s->p[1]; s->p[1] = s->p[3]; s->p[3] = swapbyte; swapbyte = s->p[2]; s->p[2] = s->p[3]; s->p[3] = swapbyte; } } } else { if (sec_flags & SEC_LICENSE_PKT) { licence_process(s); continue; } s->p -= 4; } } if (channel != MCS_GLOBAL_CHANNEL) { channel_process(s, channel); continue; } return s; } return NULL; }
169,811
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Add error logging on invalid cmap - DO NOT MERGE This patch logs instances of fonts with invalid cmap tables. Bug: 25645298 Bug: 26413177 Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e CWE ID: CWE-20
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { android_errorWriteLog(0x534e4554, "25645298"); return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { android_errorWriteLog(0x534e4554, "26413177"); return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
173,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::CreateBlockGroup( long long start_offset, long long size, long long discard_padding) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = start_offset; const long long stop = start_offset + size; long long prev = 1; //nonce long long next = 0; //nonce long long duration = -1; //really, this is unsigned long long bpos = -1; long long bsize = -1; 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); //TODO assert((pos + len) <= stop); pos += len; //consume size if (id == 0x21) //Block ID { if (bpos < 0) //Block ID { bpos = pos; bsize = size; } } else if (id == 0x1B) //Duration ID { assert(size <= 8); duration = UnserializeUInt(pReader, pos, size); assert(duration >= 0); //TODO } else if (id == 0x7B) //ReferenceBlock { assert(size <= 8); const long size_ = static_cast<long>(size); long long time; long status = UnserializeInt(pReader, pos, size_, time); assert(status == 0); if (status != 0) return -1; if (time <= 0) //see note above prev = time; else //weird next = time; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); assert(bpos >= 0); assert(bsize >= 0); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) BlockGroup( this, idx, bpos, bsize, prev, next, duration, discard_padding); if (pEntry == NULL) return -1; //generic error BlockGroup* const p = static_cast<BlockGroup*>(pEntry); const long status = p->Parse(); if (status == 0) //success { ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } 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 Cluster::CreateBlockGroup( const long status = Parse(pos, len); if (status < 0) { // error pLast = NULL; return status; } if (status > 0) // no new block break; }
174,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); 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_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; }
167,794
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintViewManager::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == print_preview_rfh_) print_preview_state_ = NOT_PREVIEWING; PrintViewManagerBase::RenderFrameDeleted(render_frame_host); } Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated(). BUG=694382,698622 Review-Url: https://codereview.chromium.org/2742853003 Cr-Commit-Position: refs/heads/master@{#457363} CWE ID: CWE-125
void PrintViewManager::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == print_preview_rfh_) PrintPreviewDone(); PrintViewManagerBase::RenderFrameDeleted(render_frame_host); }
172,405
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else if (type_ == INLINE_INSTALL_PROMPT) { return l10n_util::GetStringFUTF16( kTitleIds[type_], l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } }
170,981
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Segment::AppendCluster(Cluster* pCluster) { assert(pCluster); assert(pCluster->m_index >= 0); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); const long idx = pCluster->m_index; assert(idx == m_clusterCount); if (count >= size) { const long n = (size <= 0) ? 2048 : 2 * size; Cluster** const qq = new Cluster* [n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } if (m_clusterPreloadCount > 0) { assert(m_clusters); Cluster** const p = m_clusters + m_clusterCount; assert(*p); assert((*p)->m_index < 0); Cluster** q = p + m_clusterPreloadCount; assert(q < (m_clusters + size)); for (;;) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; } 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 Segment::AppendCluster(Cluster* pCluster) { bool Segment::AppendCluster(Cluster* pCluster) { if (pCluster == NULL || pCluster->m_index < 0) return false; const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; const long idx = pCluster->m_index; if (size < count || idx != m_clusterCount) return false; if (count >= size) { const long n = (size <= 0) ? 2048 : 2 * size; Cluster** const qq = new (std::nothrow) Cluster*[n]; if (qq == NULL) return false; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } if (m_clusterPreloadCount > 0) { Cluster** const p = m_clusters + m_clusterCount; if (*p == NULL || (*p)->m_index >= 0) return false; Cluster** q = p + m_clusterPreloadCount; if (q >= (m_clusters + size)) return false; for (;;) { Cluster** const qq = q - 1; if ((*qq)->m_index >= 0) return false; *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; return true; }
173,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FetchContext::DispatchWillSendRequest(unsigned long, ResourceRequest&, const ResourceResponse&, const FetchInitiatorInfo&) {} Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void FetchContext::DispatchWillSendRequest(unsigned long, ResourceRequest&, const ResourceResponse&, Resource::Type, const FetchInitiatorInfo&) {}
172,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringASCIICase(toElement(node)->getAttribute(roleAttr), role); }
171,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL || sec_attr_len) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; }
169,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, nbuf; bool input_wakeup = false; retry: ret = ipipe_prep(ipipe, flags); if (ret) return ret; ret = opipe_prep(opipe, flags); if (ret) return ret; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } if (!ipipe->nrbufs && !ipipe->writers) break; /* * Cannot make any progress, because either the input * pipe is empty or the output pipe is full. */ if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { /* Already processed some buffers, break */ if (ret) break; if (flags & SPLICE_F_NONBLOCK) { ret = -EAGAIN; break; } /* * We raced with another reader/writer and haven't * managed to process any buffers. A zero return * value means EOF, so retry instead. */ pipe_unlock(ipipe); pipe_unlock(opipe); goto retry; } ibuf = ipipe->bufs + ipipe->curbuf; nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); obuf = opipe->bufs + nbuf; if (len >= ibuf->len) { /* * Simply move the whole buffer from ipipe to opipe */ *obuf = *ibuf; ibuf->ops = NULL; opipe->nrbufs++; ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); ipipe->nrbufs--; input_wakeup = true; } else { /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; pipe_buf_mark_unmergeable(obuf); obuf->len = len; opipe->nrbufs++; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } ret += obuf->len; len -= obuf->len; } while (len); pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); if (input_wakeup) wakeup_pipe_writers(ipipe); return ret; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, nbuf; bool input_wakeup = false; retry: ret = ipipe_prep(ipipe, flags); if (ret) return ret; ret = opipe_prep(opipe, flags); if (ret) return ret; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } if (!ipipe->nrbufs && !ipipe->writers) break; /* * Cannot make any progress, because either the input * pipe is empty or the output pipe is full. */ if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { /* Already processed some buffers, break */ if (ret) break; if (flags & SPLICE_F_NONBLOCK) { ret = -EAGAIN; break; } /* * We raced with another reader/writer and haven't * managed to process any buffers. A zero return * value means EOF, so retry instead. */ pipe_unlock(ipipe); pipe_unlock(opipe); goto retry; } ibuf = ipipe->bufs + ipipe->curbuf; nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); obuf = opipe->bufs + nbuf; if (len >= ibuf->len) { /* * Simply move the whole buffer from ipipe to opipe */ *obuf = *ibuf; ibuf->ops = NULL; opipe->nrbufs++; ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); ipipe->nrbufs--; input_wakeup = true; } else { /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ if (!pipe_buf_get(ipipe, ibuf)) { if (ret == 0) ret = -EFAULT; break; } *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; pipe_buf_mark_unmergeable(obuf); obuf->len = len; opipe->nrbufs++; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } ret += obuf->len; len -= obuf->len; } while (len); pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); if (input_wakeup) wakeup_pipe_writers(ipipe); return ret; }
170,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltFindTemplate(xsltTransformContextPtr ctxt, const xmlChar *name, const xmlChar *nameURI) { xsltTemplatePtr cur; xsltStylesheetPtr style; if ((ctxt == NULL) || (name == NULL)) return(NULL); style = ctxt->style; while (style != NULL) { cur = style->templates; while (cur != NULL) { if (xmlStrEqual(name, cur->name)) { if (((nameURI == NULL) && (cur->nameURI == NULL)) || ((nameURI != NULL) && (cur->nameURI != NULL) && (xmlStrEqual(nameURI, cur->nameURI)))) { return(cur); } } cur = cur->next; } style = xsltNextImport(style); } return(NULL); } 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
xsltFindTemplate(xsltTransformContextPtr ctxt, const xmlChar *name, const xmlChar *nameURI) { xsltTemplatePtr cur; xsltStylesheetPtr style; if ((ctxt == NULL) || (name == NULL)) return(NULL); style = ctxt->style; while (style != NULL) { if (style->namedTemplates != NULL) { cur = (xsltTemplatePtr) xmlHashLookup2(style->namedTemplates, name, nameURI); if (cur != NULL) return(cur); } style = xsltNextImport(style); } return(NULL); }
173,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HeapVector<NotificationAction> Notification::actions() const { HeapVector<NotificationAction> actions; actions.grow(m_data.actions.size()); for (size_t i = 0; i < m_data.actions.size(); ++i) { actions[i].setAction(m_data.actions[i].action); actions[i].setTitle(m_data.actions[i].title); } return actions; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
HeapVector<NotificationAction> Notification::actions() const { HeapVector<NotificationAction> actions; actions.grow(m_data.actions.size()); for (size_t i = 0; i < m_data.actions.size(); ++i) { actions[i].setAction(m_data.actions[i].action); actions[i].setTitle(m_data.actions[i].title); actions[i].setIcon(m_data.actions[i].icon.string()); } return actions; }
171,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: seamless_process(STREAM s) { unsigned int pkglen; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL); xfree(buf); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
seamless_process(STREAM s) { unsigned int pkglen; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("seamless_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL); xfree(buf); }
169,808
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int try_read_command(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if (c->protocol == negotiating_prot || c->transport == udp_transport) { if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; } else { c->protocol = ascii_prot; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } } if (c->protocol == binary_prot) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_string(c, "SERVER_ERROR out of memory"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } } else { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) return 0; cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); } return 1; } Commit Message: Issue 102: Piping null to the server will crash it CWE ID: CWE-20
static int try_read_command(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if (c->protocol == negotiating_prot || c->transport == udp_transport) { if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; } else { c->protocol = ascii_prot; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } } if (c->protocol == binary_prot) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_string(c, "SERVER_ERROR out of memory"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } } else { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); } return 1; }
169,875
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { png_structp png_ptr = *ptr_ptr; #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_write_init() and should be recompiled."); #endif } i++; } while (png_libpng_ver[i] != 0 && user_png_ver[i] != 0); png_debug(1, "in png_write_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); *ptr_ptr = png_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, png_flush_ptr_NULL); /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT, 1, png_doublep_NULL, png_doublep_NULL); #endif } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { png_structp png_ptr = *ptr_ptr; #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_write_init() and should be recompiled."); #endif } i++; } while (png_libpng_ver[i] != 0 && user_png_ver[i] != 0); png_debug(1, "in png_write_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); *ptr_ptr = png_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, png_flush_ptr_NULL); /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); }
172,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_MINIT_FUNCTION(xml) { le_xml_parser = zend_register_list_destructors_ex(xml_parser_dtor, NULL, "xml", module_number); REGISTER_LONG_CONSTANT("XML_ERROR_NONE", XML_ERROR_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_MEMORY", XML_ERROR_NO_MEMORY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_SYNTAX", XML_ERROR_SYNTAX, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_ELEMENTS", XML_ERROR_NO_ELEMENTS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INVALID_TOKEN", XML_ERROR_INVALID_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_TOKEN", XML_ERROR_UNCLOSED_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARTIAL_CHAR", XML_ERROR_PARTIAL_CHAR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_TAG_MISMATCH", XML_ERROR_TAG_MISMATCH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_DUPLICATE_ATTRIBUTE", XML_ERROR_DUPLICATE_ATTRIBUTE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", XML_ERROR_JUNK_AFTER_DOC_ELEMENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARAM_ENTITY_REF", XML_ERROR_PARAM_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNDEFINED_ENTITY", XML_ERROR_UNDEFINED_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_RECURSIVE_ENTITY_REF", XML_ERROR_RECURSIVE_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ASYNC_ENTITY", XML_ERROR_ASYNC_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BAD_CHAR_REF", XML_ERROR_BAD_CHAR_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BINARY_ENTITY_REF", XML_ERROR_BINARY_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_MISPLACED_XML_PI", XML_ERROR_MISPLACED_XML_PI, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNKNOWN_ENCODING", XML_ERROR_UNKNOWN_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INCORRECT_ENCODING", XML_ERROR_INCORRECT_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_CDATA_SECTION", XML_ERROR_UNCLOSED_CDATA_SECTION, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_EXTERNAL_ENTITY_HANDLING", XML_ERROR_EXTERNAL_ENTITY_HANDLING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_CASE_FOLDING", PHP_XML_OPTION_CASE_FOLDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_TARGET_ENCODING", PHP_XML_OPTION_TARGET_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_TAGSTART", PHP_XML_OPTION_SKIP_TAGSTART, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_WHITE", PHP_XML_OPTION_SKIP_WHITE, CONST_CS|CONST_PERSISTENT); /* this object should not be pre-initialised at compile time, as the order of members may vary */ php_xml_mem_hdlrs.malloc_fcn = php_xml_malloc_wrapper; php_xml_mem_hdlrs.realloc_fcn = php_xml_realloc_wrapper; php_xml_mem_hdlrs.free_fcn = php_xml_free_wrapper; #ifdef LIBXML_EXPAT_COMPAT REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "libxml", CONST_CS|CONST_PERSISTENT); #else REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "expat", CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; } Commit Message: CWE ID: CWE-119
PHP_MINIT_FUNCTION(xml) { le_xml_parser = zend_register_list_destructors_ex(xml_parser_dtor, NULL, "xml", module_number); REGISTER_LONG_CONSTANT("XML_ERROR_NONE", XML_ERROR_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_MEMORY", XML_ERROR_NO_MEMORY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_SYNTAX", XML_ERROR_SYNTAX, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_ELEMENTS", XML_ERROR_NO_ELEMENTS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INVALID_TOKEN", XML_ERROR_INVALID_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_TOKEN", XML_ERROR_UNCLOSED_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARTIAL_CHAR", XML_ERROR_PARTIAL_CHAR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_TAG_MISMATCH", XML_ERROR_TAG_MISMATCH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_DUPLICATE_ATTRIBUTE", XML_ERROR_DUPLICATE_ATTRIBUTE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", XML_ERROR_JUNK_AFTER_DOC_ELEMENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARAM_ENTITY_REF", XML_ERROR_PARAM_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNDEFINED_ENTITY", XML_ERROR_UNDEFINED_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_RECURSIVE_ENTITY_REF", XML_ERROR_RECURSIVE_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ASYNC_ENTITY", XML_ERROR_ASYNC_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BAD_CHAR_REF", XML_ERROR_BAD_CHAR_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BINARY_ENTITY_REF", XML_ERROR_BINARY_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_MISPLACED_XML_PI", XML_ERROR_MISPLACED_XML_PI, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNKNOWN_ENCODING", XML_ERROR_UNKNOWN_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INCORRECT_ENCODING", XML_ERROR_INCORRECT_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_CDATA_SECTION", XML_ERROR_UNCLOSED_CDATA_SECTION, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_EXTERNAL_ENTITY_HANDLING", XML_ERROR_EXTERNAL_ENTITY_HANDLING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_CASE_FOLDING", PHP_XML_OPTION_CASE_FOLDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_TARGET_ENCODING", PHP_XML_OPTION_TARGET_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_TAGSTART", PHP_XML_OPTION_SKIP_TAGSTART, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_WHITE", PHP_XML_OPTION_SKIP_WHITE, CONST_CS|CONST_PERSISTENT); /* this object should not be pre-initialised at compile time, as the order of members may vary */ php_xml_mem_hdlrs.malloc_fcn = php_xml_malloc_wrapper; php_xml_mem_hdlrs.realloc_fcn = php_xml_realloc_wrapper; php_xml_mem_hdlrs.free_fcn = php_xml_free_wrapper; #ifdef LIBXML_EXPAT_COMPAT REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "libxml", CONST_CS|CONST_PERSISTENT); #else REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "expat", CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; }
165,038
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HostPortAllocatorSession::OnSessionRequestDone( UrlFetcher* url_fetcher, const net::URLRequestStatus& status, int response_code, const std::string& response) { url_fetchers_.erase(url_fetcher); delete url_fetcher; if (response_code != net::HTTP_OK) { LOG(WARNING) << "Received error when allocating relay session: " << response_code; TryCreateRelaySession(); return; } ReceiveSessionResponse(response); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void HostPortAllocatorSession::OnSessionRequestDone( void HostPortAllocatorSession::OnURLFetchComplete( const net::URLFetcher* source) { url_fetchers_.erase(source); delete source; if (source->GetResponseCode() != net::HTTP_OK) { LOG(WARNING) << "Received error when allocating relay session: " << source->GetResponseCode(); TryCreateRelaySession(); return; } std::string response; source->GetResponseAsString(&response); ReceiveSessionResponse(response); }
170,810
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VarianceTest<VarianceFunctionType>::RefTest() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = variance_(src_, width_, ref_, width_, &sse1)); const unsigned int var2 = variance_ref(src_, ref_, log2width_, log2height_, &sse2); EXPECT_EQ(sse1, sse2); EXPECT_EQ(var1, var2); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void VarianceTest<VarianceFunctionType>::RefTest() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < block_size_; j++) { if (!use_high_bit_depth_) { src_[j] = rnd_.Rand8(); ref_[j] = rnd_.Rand8(); #if CONFIG_VP9_HIGHBITDEPTH } else { CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() && mask_; CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() && mask_; #endif // CONFIG_VP9_HIGHBITDEPTH } } unsigned int sse1, sse2; unsigned int var1; const int stride_coeff = 1; ASM_REGISTER_STATE_CHECK( var1 = variance_(src_, width_, ref_, width_, &sse1)); const unsigned int var2 = variance_ref(src_, ref_, log2width_, log2height_, stride_coeff, stride_coeff, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2); EXPECT_EQ(var1, var2); } } template<typename VarianceFunctionType> void VarianceTest<VarianceFunctionType>::RefStrideTest() { for (int i = 0; i < 10; ++i) { int ref_stride_coeff = i % 2; int src_stride_coeff = (i >> 1) % 2; for (int j = 0; j < block_size_; j++) { int ref_ind = (j / width_) * ref_stride_coeff * width_ + j % width_; int src_ind = (j / width_) * src_stride_coeff * width_ + j % width_; if (!use_high_bit_depth_) { src_[src_ind] = rnd_.Rand8(); ref_[ref_ind] = rnd_.Rand8(); #if CONFIG_VP9_HIGHBITDEPTH } else { CONVERT_TO_SHORTPTR(src_)[src_ind] = rnd_.Rand16() && mask_; CONVERT_TO_SHORTPTR(ref_)[ref_ind] = rnd_.Rand16() && mask_; #endif // CONFIG_VP9_HIGHBITDEPTH } } unsigned int sse1, sse2; unsigned int var1; ASM_REGISTER_STATE_CHECK( var1 = variance_(src_, width_ * src_stride_coeff, ref_, width_ * ref_stride_coeff, &sse1)); const unsigned int var2 = variance_ref(src_, ref_, log2width_, log2height_, src_stride_coeff, ref_stride_coeff, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2); EXPECT_EQ(var1, var2); } }
174,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(params.surface_id); if (!view) return; delayed_send.Cancel(); view->AcceleratedSurfacePostSubBuffer(params, host_id_); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, params.surface_handle, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(params.surface_id); if (!view) return; delayed_send.Cancel(); view->AcceleratedSurfacePostSubBuffer(params, host_id_); }
171,359
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); const struct uac_to_guid { uint32_t uac; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } }; Commit Message: CWE ID: CWE-264
static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); struct ldb_context *ldb = ldb_module_get_ctx(ac->module); const struct uac_to_guid { uint32_t uac; uint32_t priv_to_change_from; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; bool admin_required; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_WORKSTATION_TRUST_ACCOUNT, .priv_to_change_from = UF_NORMAL_ACCOUNT, .error_string = "Swapping UF_NORMAL_ACCOUNT to UF_WORKSTATION_TRUST_ACCOUNT requires the user to be a member of the domain admins group" }, { .uac = UF_NORMAL_ACCOUNT, .priv_to_change_from = UF_WORKSTATION_TRUST_ACCOUNT, .error_string = "Swapping UF_WORKSTATION_TRUST_ACCOUNT to UF_NORMAL_ACCOUNT requires the user to be a member of the domain admins group" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } };
164,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr == NULL) return (NULL); if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* png_sizeof(char))); } #ifdef _WIN32_WCE { wchar_t time_buf[29]; wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, NULL, NULL); } #else #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*png_sizeof(char)); } #else png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif #endif /* _WIN32_WCE */ return ((png_charp)png_ptr->time_buffer); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr == NULL) return (NULL); if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* png_sizeof(char))); } #ifdef _WIN32_WCE { wchar_t time_buf[29]; wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, NULL, NULL); } #else #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*png_sizeof(char)); } #else png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif #endif /* _WIN32_WCE */ return ((png_charp)png_ptr->time_buffer); }
172,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, offsetExists) { char *fname; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetExists) { char *fname; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } }
165,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; } Commit Message: Fixed CVE-2018-8785 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119
int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; size_t used = 0; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; if (zgfx->OutputCount > UINT32_MAX - used) goto fail; if (used + zgfx->OutputCount > uncompressedSize) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; used += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; }
169,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } BufferMeta *buffer_meta; bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid; OMX_U8 *data = static_cast<OMX_U8 *>(params->pointer()); if (useBackup) { data = new (std::nothrow) OMX_U8[allottedSize]; if (data == NULL) { return NO_MEMORY; } memset(data, 0, allottedSize); if (allottedSize != params->size()) { CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data)); delete[] data; return BAD_VALUE; } buffer_meta = new BufferMeta( params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data); } else { buffer_meta = new BufferMeta( params, portIndex, false /* copyFromOmx */, false /* copyToOmx */, NULL); } OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, data); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, data)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; } Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer Bug: 29422020 Bug: 31412859 Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375 (cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2) CWE ID: CWE-200
status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } BufferMeta *buffer_meta; bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid; OMX_U8 *data = static_cast<OMX_U8 *>(params->pointer()); if (useBackup) { data = new (std::nothrow) OMX_U8[allottedSize]; if (data == NULL) { return NO_MEMORY; } memset(data, 0, allottedSize); if (allottedSize != params->size()) { CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data)); delete[] data; return BAD_VALUE; } buffer_meta = new BufferMeta( params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data); } else { buffer_meta = new BufferMeta( params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, NULL); } OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, data); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, data)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; }
174,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame( BrowserFrame* browser_frame, BrowserView* browser_view) { if (views::Widget::IsPureViews()) return new BrowserFrameViews(browser_frame, browser_view); return new BrowserFrameGtk(browser_frame, browser_view); } Commit Message: Fixed brekage when PureViews are enable but Desktop is not TBR=ben@chromium.org BUG=none TEST=chrome starts with --use-pure-views with touchui Review URL: http://codereview.chromium.org/7210037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91197 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame( BrowserFrame* browser_frame, BrowserView* browser_view) { if (views::Widget::IsPureViews() && views::ViewsDelegate::views_delegate->GetDefaultParentView()) return new BrowserFrameViews(browser_frame, browser_view); return new BrowserFrameGtk(browser_frame, browser_view); }
170,315
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ReturnsValidPath(int dir_type) { base::FilePath path; bool result = PathService::Get(dir_type, &path); bool check_path_exists = true; #if defined(OS_POSIX) if (dir_type == base::DIR_CACHE) check_path_exists = false; #endif #if defined(OS_LINUX) if (dir_type == base::DIR_USER_DESKTOP) check_path_exists = false; #endif #if defined(OS_WIN) if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) { if (base::win::GetVersion() < base::win::VERSION_VISTA) { wchar_t default_profile_path[MAX_PATH]; DWORD size = arraysize(default_profile_path); return (result && ::GetDefaultUserProfileDirectory(default_profile_path, &size) && StartsWith(path.value(), default_profile_path, false)); } } else if (dir_type == base::DIR_TASKBAR_PINS) { if (base::win::GetVersion() < base::win::VERSION_WIN7) check_path_exists = false; } #endif #if defined(OS_MAC) if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE && dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) { if (path.ReferencesParent()) return false; } #else if (path.ReferencesParent()) return false; #endif return result && !path.empty() && (!check_path_exists || file_util::PathExists(path)); } Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX. BUG=163208 TEST=none Review URL: https://codereview.chromium.org/12829005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ReturnsValidPath(int dir_type) { base::FilePath path; bool result = PathService::Get(dir_type, &path); bool check_path_exists = true; #if defined(OS_POSIX) if (dir_type == base::DIR_CACHE) check_path_exists = false; #endif #if defined(OS_LINUX) if (dir_type == base::DIR_USER_DESKTOP) check_path_exists = false; #endif #if defined(OS_WIN) if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) { if (base::win::GetVersion() < base::win::VERSION_VISTA) { wchar_t default_profile_path[MAX_PATH]; DWORD size = arraysize(default_profile_path); return (result && ::GetDefaultUserProfileDirectory(default_profile_path, &size) && StartsWith(path.value(), default_profile_path, false)); } } else if (dir_type == base::DIR_TASKBAR_PINS) { if (base::win::GetVersion() < base::win::VERSION_WIN7) check_path_exists = false; } #endif #if defined(OS_MACOSX) if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE && dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) { if (path.ReferencesParent()) return false; } #else if (path.ReferencesParent()) return false; #endif return result && !path.empty() && (!check_path_exists || file_util::PathExists(path)); }
171,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TaskManagerView::Init() { table_model_.reset(new TaskManagerTableModel(model_)); columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN, ui::TableColumn::LEFT, -1, 1)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, ui::TableColumn::LEFT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_FPS_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back( ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; tab_table_ = new BackgroundColorGroupTableView( table_model_.get(), columns_, highlight_background_resources_); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN, false); tab_table_->SetColumnVisibility( IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN, false); UpdateStatsCounters(); tab_table_->SetObserver(this); tab_table_->set_context_menu_controller(this); set_context_menu_controller(this); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kPurgeMemoryButton)) { purge_memory_button_ = new views::NativeTextButton(this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_PURGE_MEMORY)); } kill_button_ = new views::NativeTextButton( this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL)); kill_button_->AddAccelerator(ui::Accelerator(ui::VKEY_E, false, false, false)); kill_button_->SetAccessibleKeyboardShortcut(L"E"); kill_button_->set_prefix_type(views::TextButtonBase::PREFIX_SHOW); about_memory_link_ = new views::Link( l10n_util::GetStringUTF16(IDS_TASK_MANAGER_ABOUT_MEMORY_LINK)); about_memory_link_->set_listener(this); OnSelectionChanged(); } Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans. BUG=128242 R=ben@chromium.org Review URL: https://chromiumcodereview.appspot.com/10399085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void TaskManagerView::Init() { table_model_.reset(new TaskManagerTableModel(model_)); columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN, ui::TableColumn::LEFT, -1, 1)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, ui::TableColumn::LEFT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_FPS_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back( ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; tab_table_ = new BackgroundColorGroupTableView( table_model_.get(), columns_, highlight_background_resources_); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN, false); tab_table_->SetColumnVisibility( IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN, false); UpdateStatsCounters(); tab_table_->SetObserver(this); tab_table_->set_context_menu_controller(this); set_context_menu_controller(this); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kPurgeMemoryButton)) { purge_memory_button_ = new views::NativeTextButton(this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_PURGE_MEMORY)); } kill_button_ = new views::NativeTextButton( this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL)); kill_button_->AddAccelerator(ui::Accelerator(ui::VKEY_E, ui::EF_NONE)); kill_button_->SetAccessibleKeyboardShortcut(L"E"); kill_button_->set_prefix_type(views::TextButtonBase::PREFIX_SHOW); about_memory_link_ = new views::Link( l10n_util::GetStringUTF16(IDS_TASK_MANAGER_ABOUT_MEMORY_LINK)); about_memory_link_->set_listener(this); OnSelectionChanged(); }
170,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_background_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* Check for tRNS first: */ if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE) image_pixel_add_alpha(that, &display->this); /* This is only necessary if the alpha value is less than 1. */ if (that->alphaf < 1) { /* Now we do the background calculation without any gamma correction. */ if (that->alphaf <= 0) { that->redf = data.redf; that->greenf = data.greenf; that->bluef = data.bluef; that->rede = data.rede; that->greene = data.greene; that->bluee = data.bluee; that->red_sBIT= data.red_sBIT; that->green_sBIT= data.green_sBIT; that->blue_sBIT= data.blue_sBIT; } else /* 0 < alpha < 1 */ { double alf = 1 - that->alphaf; that->redf = that->redf * that->alphaf + data.redf * alf; that->rede = that->rede * that->alphaf + data.rede * alf + DBL_EPSILON; that->greenf = that->greenf * that->alphaf + data.greenf * alf; that->greene = that->greene * that->alphaf + data.greene * alf + DBL_EPSILON; that->bluef = that->bluef * that->alphaf + data.bluef * alf; that->bluee = that->bluee * that->alphaf + data.bluee * alf + DBL_EPSILON; } /* Remove the alpha type and set the alpha (not in that order.) */ that->alphaf = 1; that->alphae = 0; if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; /* PNG_COLOR_TYPE_PALETTE is not changed */ } this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_background_mod(PNG_CONST image_transform *this, image_transform_png_set_background_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Check for tRNS first: */ if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE) image_pixel_add_alpha(that, &display->this, 1/*for background*/); /* This is only necessary if the alpha value is less than 1. */ if (that->alphaf < 1) { /* Now we do the background calculation without any gamma correction. */ if (that->alphaf <= 0) { that->redf = data.redf; that->greenf = data.greenf; that->bluef = data.bluef; that->rede = data.rede; that->greene = data.greene; that->bluee = data.bluee; that->red_sBIT= data.red_sBIT; that->green_sBIT= data.green_sBIT; that->blue_sBIT= data.blue_sBIT; } else /* 0 < alpha < 1 */ { double alf = 1 - that->alphaf; that->redf = that->redf * that->alphaf + data.redf * alf; that->rede = that->rede * that->alphaf + data.rede * alf + DBL_EPSILON; that->greenf = that->greenf * that->alphaf + data.greenf * alf; that->greene = that->greene * that->alphaf + data.greene * alf + DBL_EPSILON; that->bluef = that->bluef * that->alphaf + data.bluef * alf; that->bluee = that->bluee * that->alphaf + data.bluee * alf + DBL_EPSILON; } /* Remove the alpha type and set the alpha (not in that order.) */ that->alphaf = 1; that->alphae = 0; } if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; /* PNG_COLOR_TYPE_PALETTE is not changed */ this->next->mod(this->next, that, pp, display); }
173,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const SystemProfileProto& MetricsLog::RecordEnvironment( DelegatingProvider* delegating_provider) { DCHECK(!has_environment_); has_environment_ = true; SystemProfileProto* system_profile = uma_proto()->mutable_system_profile(); WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(), system_profile); std::string brand_code; if (client_->GetBrand(&brand_code)) system_profile->set_brand_code(brand_code); SystemProfileProto::Hardware::CPU* cpu = system_profile->mutable_hardware()->mutable_cpu(); base::CPU cpu_info; cpu->set_vendor_name(cpu_info.vendor_name()); cpu->set_signature(cpu_info.signature()); cpu->set_num_cores(base::SysInfo::NumberOfProcessors()); delegating_provider->ProvideSystemProfileMetrics(system_profile); return *system_profile; } Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM. Bug: 907674 Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2 Reviewed-on: https://chromium-review.googlesource.com/c/1381376 Commit-Queue: Nik Bhagat <nikunjb@chromium.org> Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Cr-Commit-Position: refs/heads/master@{#618037} CWE ID: CWE-79
const SystemProfileProto& MetricsLog::RecordEnvironment( DelegatingProvider* delegating_provider) { DCHECK(!has_environment_); has_environment_ = true; SystemProfileProto* system_profile = uma_proto()->mutable_system_profile(); WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(), system_profile); std::string brand_code; if (client_->GetBrand(&brand_code)) system_profile->set_brand_code(brand_code); delegating_provider->ProvideSystemProfileMetrics(system_profile); return *system_profile; }
172,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vrend_create_shader(struct vrend_context *ctx, uint32_t handle, const struct pipe_stream_output_info *so_info, const char *shd_text, uint32_t offlen, uint32_t num_tokens, uint32_t type, uint32_t pkt_length) { struct vrend_shader_selector *sel = NULL; int ret_handle; bool new_shader = true, long_shader = false; bool finished = false; int ret; if (type > PIPE_SHADER_GEOMETRY) return EINVAL; if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT) new_shader = false; else if (((offlen + 3) / 4) > pkt_length) long_shader = true; /* if we have an in progress one - don't allow a new shader of that type or a different handle. */ if (ctx->sub->long_shader_in_progress_handle[type]) { if (new_shader == true) return EINVAL; if (handle != ctx->sub->long_shader_in_progress_handle[type]) return EINVAL; } if (new_shader) { sel = vrend_create_shader_state(ctx, so_info, type); if (sel == NULL) return ENOMEM; if (long_shader) { sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */ sel->tmp_buf = malloc(sel->buf_len); if (!sel->tmp_buf) { ret = ENOMEM; goto error; } memcpy(sel->tmp_buf, shd_text, pkt_length * 4); sel->buf_offset = pkt_length * 4; ctx->sub->long_shader_in_progress_handle[type] = handle; } else finished = true; } else { sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER); if (!sel) { fprintf(stderr, "got continuation without original shader %d\n", handle); ret = EINVAL; goto error; } offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT; if (offlen != sel->buf_offset) { fprintf(stderr, "Got mismatched shader continuation %d vs %d\n", offlen, sel->buf_offset); ret = EINVAL; goto error; } if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) { fprintf(stderr, "Got too large shader continuation %d vs %d\n", pkt_length * 4 + sel->buf_offset, sel->buf_len); shd_text = sel->tmp_buf; } } if (finished) { struct tgsi_token *tokens; tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token)); if (!tokens) { ret = ENOMEM; goto error; } if (vrend_dump_shaders) fprintf(stderr,"shader\n%s\n", shd_text); if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) { free(tokens); ret = EINVAL; goto error; } if (vrend_finish_shader(ctx, sel, tokens)) { free(tokens); ret = EINVAL; goto error; } else { free(sel->tmp_buf); sel->tmp_buf = NULL; } free(tokens); ctx->sub->long_shader_in_progress_handle[type] = 0; } if (new_shader) { ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER); if (ret_handle == 0) { ret = ENOMEM; goto error; } } return 0; error: if (new_shader) vrend_destroy_shader_selector(sel); else vrend_renderer_object_destroy(ctx, handle); return ret; } Commit Message: CWE ID: CWE-190
int vrend_create_shader(struct vrend_context *ctx, uint32_t handle, const struct pipe_stream_output_info *so_info, const char *shd_text, uint32_t offlen, uint32_t num_tokens, uint32_t type, uint32_t pkt_length) { struct vrend_shader_selector *sel = NULL; int ret_handle; bool new_shader = true, long_shader = false; bool finished = false; int ret; if (type > PIPE_SHADER_GEOMETRY) return EINVAL; if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT) new_shader = false; else if (((offlen + 3) / 4) > pkt_length) long_shader = true; /* if we have an in progress one - don't allow a new shader of that type or a different handle. */ if (ctx->sub->long_shader_in_progress_handle[type]) { if (new_shader == true) return EINVAL; if (handle != ctx->sub->long_shader_in_progress_handle[type]) return EINVAL; } if (new_shader) { sel = vrend_create_shader_state(ctx, so_info, type); if (sel == NULL) return ENOMEM; if (long_shader) { sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */ sel->tmp_buf = malloc(sel->buf_len); if (!sel->tmp_buf) { ret = ENOMEM; goto error; } memcpy(sel->tmp_buf, shd_text, pkt_length * 4); sel->buf_offset = pkt_length * 4; ctx->sub->long_shader_in_progress_handle[type] = handle; } else finished = true; } else { sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER); if (!sel) { fprintf(stderr, "got continuation without original shader %d\n", handle); ret = EINVAL; goto error; } offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT; if (offlen != sel->buf_offset) { fprintf(stderr, "Got mismatched shader continuation %d vs %d\n", offlen, sel->buf_offset); ret = EINVAL; goto error; } /*make sure no overflow */ if (pkt_length * 4 < pkt_length || pkt_length * 4 + sel->buf_offset < pkt_length * 4 || pkt_length * 4 + sel->buf_offset < sel->buf_offset) { ret = EINVAL; goto error; } if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) { fprintf(stderr, "Got too large shader continuation %d vs %d\n", pkt_length * 4 + sel->buf_offset, sel->buf_len); shd_text = sel->tmp_buf; } } if (finished) { struct tgsi_token *tokens; tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token)); if (!tokens) { ret = ENOMEM; goto error; } if (vrend_dump_shaders) fprintf(stderr,"shader\n%s\n", shd_text); if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) { free(tokens); ret = EINVAL; goto error; } if (vrend_finish_shader(ctx, sel, tokens)) { free(tokens); ret = EINVAL; goto error; } else { free(sel->tmp_buf); sel->tmp_buf = NULL; } free(tokens); ctx->sub->long_shader_in_progress_handle[type] = 0; } if (new_shader) { ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER); if (ret_handle == 0) { ret = ENOMEM; goto error; } } return 0; error: if (new_shader) vrend_destroy_shader_selector(sel); else vrend_renderer_object_destroy(ctx, handle); return ret; }
164,945
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AccessibilityExpanded AXNodeObject::isExpanded() const { if (getNode() && isHTMLSummaryElement(*getNode())) { if (getNode()->parentNode() && isHTMLDetailsElement(getNode()->parentNode())) return toElement(getNode()->parentNode())->hasAttribute(openAttr) ? ExpandedExpanded : ExpandedCollapsed; } const AtomicString& expanded = getAttribute(aria_expandedAttr); if (equalIgnoringCase(expanded, "true")) return ExpandedExpanded; if (equalIgnoringCase(expanded, "false")) return ExpandedCollapsed; return ExpandedUndefined; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AccessibilityExpanded AXNodeObject::isExpanded() const { if (getNode() && isHTMLSummaryElement(*getNode())) { if (getNode()->parentNode() && isHTMLDetailsElement(getNode()->parentNode())) return toElement(getNode()->parentNode())->hasAttribute(openAttr) ? ExpandedExpanded : ExpandedCollapsed; } const AtomicString& expanded = getAttribute(aria_expandedAttr); if (equalIgnoringASCIICase(expanded, "true")) return ExpandedExpanded; if (equalIgnoringASCIICase(expanded, "false")) return ExpandedCollapsed; return ExpandedUndefined; }
171,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int is_integer(char *string) { if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') { while (*++string && isdigit(*string)) ; /* deliberately empty */ if (!*string) return 1; } return 0; } Commit Message: Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char. CWE ID: CWE-119
static int is_integer(char *string) { if (isdigit((unsigned char) string[0]) || string[0] == '-' || string[0] == '+') { while (*++string && isdigit((unsigned char) *string)) ; /* deliberately empty */ if (!*string) return 1; } return 0; }
166,621
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; loff_t size; unsigned long len; int ret; struct file *file = vma->vm_file; struct inode *inode = file_inode(file); struct address_space *mapping = inode->i_mapping; handle_t *handle; get_block_t *get_block; int retries = 0; sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); /* Delalloc case is easy... */ if (test_opt(inode->i_sb, DELALLOC) && !ext4_should_journal_data(inode) && !ext4_nonda_switch(inode->i_sb)) { do { ret = block_page_mkwrite(vma, vmf, ext4_da_get_block_prep); } while (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)); goto out_ret; } lock_page(page); size = i_size_read(inode); /* Page got truncated from under us? */ if (page->mapping != mapping || page_offset(page) > size) { unlock_page(page); ret = VM_FAULT_NOPAGE; goto out; } if (page->index == size >> PAGE_CACHE_SHIFT) len = size & ~PAGE_CACHE_MASK; else len = PAGE_CACHE_SIZE; /* * Return if we have all the buffers mapped. This avoids the need to do * journal_start/journal_stop which can block and take a long time */ if (page_has_buffers(page)) { if (!ext4_walk_page_buffers(NULL, page_buffers(page), 0, len, NULL, ext4_bh_unmapped)) { /* Wait so that we don't change page under IO */ wait_for_stable_page(page); ret = VM_FAULT_LOCKED; goto out; } } unlock_page(page); /* OK, we need to fill the hole... */ if (ext4_should_dioread_nolock(inode)) get_block = ext4_get_block_write; else get_block = ext4_get_block; retry_alloc: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_writepage_trans_blocks(inode)); if (IS_ERR(handle)) { ret = VM_FAULT_SIGBUS; goto out; } ret = block_page_mkwrite(vma, vmf, get_block); if (!ret && ext4_should_journal_data(inode)) { if (ext4_walk_page_buffers(handle, page_buffers(page), 0, PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) { unlock_page(page); ret = VM_FAULT_SIGBUS; ext4_journal_stop(handle); goto out; } ext4_set_inode_state(inode, EXT4_STATE_JDATA); } ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_alloc; out_ret: ret = block_page_mkwrite_return(ret); out: sb_end_pagefault(inode->i_sb); return ret; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; loff_t size; unsigned long len; int ret; struct file *file = vma->vm_file; struct inode *inode = file_inode(file); struct address_space *mapping = inode->i_mapping; handle_t *handle; get_block_t *get_block; int retries = 0; sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); /* Delalloc case is easy... */ if (test_opt(inode->i_sb, DELALLOC) && !ext4_should_journal_data(inode) && !ext4_nonda_switch(inode->i_sb)) { do { ret = block_page_mkwrite(vma, vmf, ext4_da_get_block_prep); } while (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)); goto out_ret; } lock_page(page); size = i_size_read(inode); /* Page got truncated from under us? */ if (page->mapping != mapping || page_offset(page) > size) { unlock_page(page); ret = VM_FAULT_NOPAGE; goto out; } if (page->index == size >> PAGE_CACHE_SHIFT) len = size & ~PAGE_CACHE_MASK; else len = PAGE_CACHE_SIZE; /* * Return if we have all the buffers mapped. This avoids the need to do * journal_start/journal_stop which can block and take a long time */ if (page_has_buffers(page)) { if (!ext4_walk_page_buffers(NULL, page_buffers(page), 0, len, NULL, ext4_bh_unmapped)) { /* Wait so that we don't change page under IO */ wait_for_stable_page(page); ret = VM_FAULT_LOCKED; goto out; } } unlock_page(page); /* OK, we need to fill the hole... */ if (ext4_should_dioread_nolock(inode)) get_block = ext4_get_block_write; else get_block = ext4_get_block; retry_alloc: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_writepage_trans_blocks(inode)); if (IS_ERR(handle)) { ret = VM_FAULT_SIGBUS; goto out; } ret = block_page_mkwrite(vma, vmf, get_block); if (!ret && ext4_should_journal_data(inode)) { if (ext4_walk_page_buffers(handle, page_buffers(page), 0, PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) { unlock_page(page); ret = VM_FAULT_SIGBUS; ext4_journal_stop(handle); goto out; } ext4_set_inode_state(inode, EXT4_STATE_JDATA); } ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_alloc; out_ret: ret = block_page_mkwrite_return(ret); out: up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(inode->i_sb); return ret; }
167,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->headindex < psf->headend) { ptr [k] = psf->header [psf->headindex] ; psf->headindex ++ ; } else { psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ; ptr [k] = psf->header [psf->headindex] ; psf->headindex = psf->headend ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; if (psf->header.indx + bufsize >= psf->header.len && psf_bump_header_allocation (psf, bufsize)) return 0 ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->header.indx < psf->header.end) { ptr [k] = psf->header.ptr [psf->header.indx] ; psf->header.indx ++ ; } else { psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, 1, psf) ; ptr [k] = psf->header.ptr [psf->header.indx] ; psf->header.indx = psf->header.end ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */
170,047
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); for (length=0; (c=ReadBlobByte(image)) != EOF; length++) (void) fputc(c,file); offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/196 CWE ID: CWE-20
static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); }
168,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sync_lockstate_on_connect(btif_hh_device_t *p_dev) { int keylockstates; BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\ "reconnect...",__FUNCTION__); /*If the device is connected, update keyboard state */ update_keyboard_lockstates(p_dev); /*Check if the lockstate of caps,scroll,num is set. If so, send a report to the kernel so the lockstate is in sync */ keylockstates = get_keylockstates(); if (keylockstates) { BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); usleep(200000); toggle_os_keylockstates(p_dev->fd, keylockstates); } else { BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void sync_lockstate_on_connect(btif_hh_device_t *p_dev) { int keylockstates; BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\ "reconnect...",__FUNCTION__); /*If the device is connected, update keyboard state */ update_keyboard_lockstates(p_dev); /*Check if the lockstate of caps,scroll,num is set. If so, send a report to the kernel so the lockstate is in sync */ keylockstates = get_keylockstates(); if (keylockstates) { BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); TEMP_FAILURE_RETRY(usleep(200000)); toggle_os_keylockstates(p_dev->fd, keylockstates); } else { BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); } }
173,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: setkey_principal_2_svc(setkey_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal((void *)handle, arg->princ, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
setkey_principal_2_svc(setkey_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal((void *)handle, arg->princ, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _pango_emoji_iter_next (PangoEmojiIter *iter) { PangoEmojiType current_emoji_type = PANGO_EMOJI_TYPE_INVALID; if (iter->end == iter->text_end) return FALSE; iter->start = iter->end; for (; iter->end < iter->text_end; iter->end = g_utf8_next_char (iter->end)) { gunichar ch = g_utf8_get_char (iter->end); /* Except at the beginning, ZWJ just carries over the emoji or neutral * text type, VS15 & VS16 we just carry over as well, since we already * resolved those through lookahead. Also, don't downgrade to text * presentation for emoji that are part of a ZWJ sequence, example * U+1F441 U+200D U+1F5E8, eye (text presentation) + ZWJ + left speech * bubble, see below. */ if ((!(ch == kZeroWidthJoinerCharacter && !iter->is_emoji) && ch != kVariationSelector15Character && ch != kVariationSelector16Character && ch != kCombiningEnclosingCircleBackslashCharacter && !_pango_Is_Regional_Indicator(ch) && !((ch == kLeftSpeechBubbleCharacter || ch == kRainbowCharacter || ch == kMaleSignCharacter || ch == kFemaleSignCharacter || ch == kStaffOfAesculapiusCharacter) && !iter->is_emoji)) || current_emoji_type == PANGO_EMOJI_TYPE_INVALID) { current_emoji_type = _pango_get_emoji_type (ch); } if (g_utf8_next_char (iter->end) < iter->text_end) /* Optimize. */ { gunichar peek_char = g_utf8_get_char (g_utf8_next_char (iter->end)); /* Variation Selectors */ if (current_emoji_type == PANGO_EMOJI_TYPE_EMOJI_EMOJI && peek_char == kVariationSelector15Character) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_TEXT; } if ((current_emoji_type == PANGO_EMOJI_TYPE_EMOJI_TEXT || _pango_Is_Emoji_Keycap_Base(ch)) && peek_char == kVariationSelector16Character) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } /* Combining characters Keycap... */ if (_pango_Is_Emoji_Keycap_Base(ch) && peek_char == kCombiningEnclosingKeycapCharacter) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; }; /* Regional indicators */ if (_pango_Is_Regional_Indicator(ch) && _pango_Is_Regional_Indicator(peek_char)) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } /* Upgrade text presentation emoji to emoji presentation when followed by * ZWJ, Example U+1F441 U+200D U+1F5E8, eye + ZWJ + left speech bubble. */ if ((ch == kEyeCharacter || ch == kWavingWhiteFlagCharacter) && peek_char == kZeroWidthJoinerCharacter) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } } if (iter->is_emoji == (gboolean) 2) iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); if (iter->is_emoji == PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type)) { iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); return TRUE; } } iter->is_emoji = PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); return TRUE; } Commit Message: Prevent an assertion with invalid Unicode sequences Invalid Unicode sequences, such as 0x2665 0xfe0e 0xfe0f, can trick the Emoji iter code into returning an empty segment, which then triggers an assertion in the itemizer. Prevent this by ensuring that we make progress. This issue was reported by Jeffrey M. CWE ID: CWE-119
_pango_emoji_iter_next (PangoEmojiIter *iter) { PangoEmojiType current_emoji_type = PANGO_EMOJI_TYPE_INVALID; if (iter->end == iter->text_end) return FALSE; iter->start = iter->end; for (; iter->end < iter->text_end; iter->end = g_utf8_next_char (iter->end)) { gunichar ch = g_utf8_get_char (iter->end); /* Except at the beginning, ZWJ just carries over the emoji or neutral * text type, VS15 & VS16 we just carry over as well, since we already * resolved those through lookahead. Also, don't downgrade to text * presentation for emoji that are part of a ZWJ sequence, example * U+1F441 U+200D U+1F5E8, eye (text presentation) + ZWJ + left speech * bubble, see below. */ if ((!(ch == kZeroWidthJoinerCharacter && !iter->is_emoji) && ch != kVariationSelector15Character && ch != kVariationSelector16Character && ch != kCombiningEnclosingCircleBackslashCharacter && !_pango_Is_Regional_Indicator(ch) && !((ch == kLeftSpeechBubbleCharacter || ch == kRainbowCharacter || ch == kMaleSignCharacter || ch == kFemaleSignCharacter || ch == kStaffOfAesculapiusCharacter) && !iter->is_emoji)) || current_emoji_type == PANGO_EMOJI_TYPE_INVALID) { current_emoji_type = _pango_get_emoji_type (ch); } if (g_utf8_next_char (iter->end) < iter->text_end) /* Optimize. */ { gunichar peek_char = g_utf8_get_char (g_utf8_next_char (iter->end)); /* Variation Selectors */ if (current_emoji_type == PANGO_EMOJI_TYPE_EMOJI_EMOJI && peek_char == kVariationSelector15Character) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_TEXT; } if ((current_emoji_type == PANGO_EMOJI_TYPE_EMOJI_TEXT || _pango_Is_Emoji_Keycap_Base(ch)) && peek_char == kVariationSelector16Character) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } /* Combining characters Keycap... */ if (_pango_Is_Emoji_Keycap_Base(ch) && peek_char == kCombiningEnclosingKeycapCharacter) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; }; /* Regional indicators */ if (_pango_Is_Regional_Indicator(ch) && _pango_Is_Regional_Indicator(peek_char)) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } /* Upgrade text presentation emoji to emoji presentation when followed by * ZWJ, Example U+1F441 U+200D U+1F5E8, eye + ZWJ + left speech bubble. */ if ((ch == kEyeCharacter || ch == kWavingWhiteFlagCharacter) && peek_char == kZeroWidthJoinerCharacter) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } } if (iter->is_emoji == (gboolean) 2) iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); if (iter->is_emoji == PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type)) { iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); /* Make sure we make progress. Weird sequences, like a VC15 followed * by VC16, can trick us into stalling otherwise. */ if (iter->start == iter->end) iter->end = g_utf8_next_char (iter->end); return TRUE; } } iter->is_emoji = PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); return TRUE; }
169,108
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: String AXNodeObject::textFromDescendants(AXObjectSet& visited, bool recursive) const { if (!canHaveChildren() && recursive) return String(); StringBuilder accumulatedText; AXObject* previous = nullptr; AXObjectVector children; HeapVector<Member<AXObject>> ownedChildren; computeAriaOwnsChildren(ownedChildren); for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) { if (!axObjectCache().isAriaOwned(obj)) children.push_back(obj); } for (const auto& ownedChild : ownedChildren) children.push_back(ownedChild); for (AXObject* child : children) { if (equalIgnoringCase(child->getAttribute(aria_hiddenAttr), "true")) continue; if (previous && accumulatedText.length() && !isHTMLSpace(accumulatedText[accumulatedText.length() - 1])) { if (!isInSameNonInlineBlockFlow(child->getLayoutObject(), previous->getLayoutObject())) accumulatedText.append(' '); } String result; if (child->isPresentational()) result = child->textFromDescendants(visited, true); else result = recursiveTextAlternative(*child, false, visited); accumulatedText.append(result); previous = child; } return accumulatedText.toString(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
String AXNodeObject::textFromDescendants(AXObjectSet& visited, bool recursive) const { if (!canHaveChildren() && recursive) return String(); StringBuilder accumulatedText; AXObject* previous = nullptr; AXObjectVector children; HeapVector<Member<AXObject>> ownedChildren; computeAriaOwnsChildren(ownedChildren); for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) { if (!axObjectCache().isAriaOwned(obj)) children.push_back(obj); } for (const auto& ownedChild : ownedChildren) children.push_back(ownedChild); for (AXObject* child : children) { if (equalIgnoringASCIICase(child->getAttribute(aria_hiddenAttr), "true")) continue; if (previous && accumulatedText.length() && !isHTMLSpace(accumulatedText[accumulatedText.length() - 1])) { if (!isInSameNonInlineBlockFlow(child->getLayoutObject(), previous->getLayoutObject())) accumulatedText.append(' '); } String result; if (child->isPresentational()) result = child->textFromDescendants(visited, true); else result = recursiveTextAlternative(*child, false, visited); accumulatedText.append(result); previous = child; } return accumulatedText.toString(); }
171,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; in->data[plane] && plane < 4; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; in->data[plane] && plane < 4; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); }
165,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else if (pool->free_total < NW_BUF_POOL_MAX_SIZE) { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } else { free(buf); } }
169,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool MockContentSettingsClient::allowAutoplay(bool default_value) { return default_value || flags_->autoplay_allowed(); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} CWE ID: CWE-119
bool MockContentSettingsClient::allowAutoplay(bool default_value) { return flags_->autoplay_allowed(); }
172,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: interlace_row(png_bytep buffer, png_const_bytep imageRow, unsigned int pixel_size, png_uint_32 w, int pass) { png_uint_32 xin, xout, xstep; /* Note that this can, trivially, be optimized to a memcpy on pass 7, the * code is presented this way to make it easier to understand. In practice * consult the code in the libpng source to see other ways of doing this. */ xin = PNG_PASS_START_COL(pass); xstep = 1U<<PNG_PASS_COL_SHIFT(pass); for (xout=0; xin<w; xin+=xstep) { pixel_copy(buffer, xout, imageRow, xin, pixel_size); ++xout; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
interlace_row(png_bytep buffer, png_const_bytep imageRow,
173,659
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ pcap_close(fp); if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } Commit Message: In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs. CWE ID: CWE-918
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; // Is this a URL rather than a device? // If so, reject it. if (is_url(source)) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string refers to a remote device"); goto error; } if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ pcap_close(fp); if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; }
169,540
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sequential_row(standard_display *dp, png_structp pp, png_infop pi, PNG_CONST int iImage, PNG_CONST int iDisplay) { PNG_CONST int npasses = dp->npasses; PNG_CONST int do_interlace = dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7; PNG_CONST png_uint_32 height = standard_height(pp, dp->id); PNG_CONST png_uint_32 width = standard_width(pp, dp->id); PNG_CONST png_store* ps = dp->ps; int pass; for (pass=0; pass<npasses; ++pass) { png_uint_32 y; png_uint_32 wPass = PNG_PASS_COLS(width, pass); for (y=0; y<height; ++y) { if (do_interlace) { /* wPass may be zero or this row may not be in this pass. * png_read_row must not be called in either case. */ if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass)) { /* Read the row into a pair of temporary buffers, then do the * merge here into the output rows. */ png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX]; /* The following aids (to some extent) error detection - we can * see where png_read_row wrote. Use opposite values in row and * display to make this easier. Don't use 0xff (which is used in * the image write code to fill unused bits) or 0 (which is a * likely value to overwrite unused bits with). */ memset(row, 0xc5, sizeof row); memset(display, 0x5c, sizeof display); png_read_row(pp, row, display); if (iImage >= 0) deinterlace_row(store_image_row(ps, pp, iImage, y), row, dp->pixel_size, dp->w, pass); if (iDisplay >= 0) deinterlace_row(store_image_row(ps, pp, iDisplay, y), display, dp->pixel_size, dp->w, pass); } } else png_read_row(pp, iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL, iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL); } } /* And finish the read operation (only really necessary if the caller wants * to find additional data in png_info from chunks after the last IDAT.) */ png_read_end(pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
sequential_row(standard_display *dp, png_structp pp, png_infop pi, const int iImage, const int iDisplay) { const int npasses = dp->npasses; const int do_interlace = dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7; const png_uint_32 height = standard_height(pp, dp->id); const png_uint_32 width = standard_width(pp, dp->id); const png_store* ps = dp->ps; int pass; for (pass=0; pass<npasses; ++pass) { png_uint_32 y; png_uint_32 wPass = PNG_PASS_COLS(width, pass); for (y=0; y<height; ++y) { if (do_interlace) { /* wPass may be zero or this row may not be in this pass. * png_read_row must not be called in either case. */ if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass)) { /* Read the row into a pair of temporary buffers, then do the * merge here into the output rows. */ png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX]; /* The following aids (to some extent) error detection - we can * see where png_read_row wrote. Use opposite values in row and * display to make this easier. Don't use 0xff (which is used in * the image write code to fill unused bits) or 0 (which is a * likely value to overwrite unused bits with). */ memset(row, 0xc5, sizeof row); memset(display, 0x5c, sizeof display); png_read_row(pp, row, display); if (iImage >= 0) deinterlace_row(store_image_row(ps, pp, iImage, y), row, dp->pixel_size, dp->w, pass, dp->littleendian); if (iDisplay >= 0) deinterlace_row(store_image_row(ps, pp, iDisplay, y), display, dp->pixel_size, dp->w, pass, dp->littleendian); } } else png_read_row(pp, iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL, iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL); } } /* And finish the read operation (only really necessary if the caller wants * to find additional data in png_info from chunks after the last IDAT.) */ png_read_end(pp, pi); }
173,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ospf6_print_lshdr(netdissect_options *ndo, register const struct lsa6_hdr *lshp, const u_char *dataend) { if ((const u_char *)(lshp + 1) > dataend) goto trunc; ND_TCHECK(lshp->ls_type); ND_TCHECK(lshp->ls_seq); ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u", ipaddr_string(ndo, &lshp->ls_router), EXTRACT_32BITS(&lshp->ls_seq), EXTRACT_16BITS(&lshp->ls_age), EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid); return (0); trunc: return (1); } Commit Message: (for 4.9.3) CVE-2018-14880/OSPFv3: Fix a bounds check Need to test bounds check for the last field of the structure lsa6_hdr. No need to test other fields. Include Security working under the Mozilla SOS program had independently identified this vulnerability in 2018 by means of code audit. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
ospf6_print_lshdr(netdissect_options *ndo, register const struct lsa6_hdr *lshp, const u_char *dataend) { if ((const u_char *)(lshp + 1) > dataend) goto trunc; ND_TCHECK(lshp->ls_length); /* last field of struct lsa6_hdr */ ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u", ipaddr_string(ndo, &lshp->ls_router), EXTRACT_32BITS(&lshp->ls_seq), EXTRACT_16BITS(&lshp->ls_age), EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid); return (0); trunc: return (1); }
169,834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } Commit Message: Support all the new variables added CWE ID: CWE-264
const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); _(NPPVpluginUrlRequestsDisplayedBool); _(NPPVpluginWantsAllNetworkStreams); _(NPPVpluginNativeAccessibleAtkPlugId); _(NPPVpluginCancelSrcStream); _(NPPVSupportsAdvancedKeyHandling); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; }
165,866
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp) { int result; u_char c; int saw_digit; int neg; int too_large; if (len == 0) goto trunc; ND_TCHECK(*bp); too_large = 0; neg = 0; if (*bp == '-') { neg = 1; bp++; len--; } result = 0; saw_digit = 0; for (;;) { if (len == 0) goto trunc; ND_TCHECK(*bp); c = *bp; if (!(c >= '0' && c <= '9')) { if (!saw_digit) goto invalid; break; } c -= '0'; if (result > (INT_MAX / 10)) { /* This will overflow an int when we multiply it by 10. */ too_large = 1; } else { result *= 10; if (result == INT_MAX && c > (INT_MAX % 10)) { /* This will overflow an int when we add c */ too_large = 1; } else result += c; } bp++; len--; saw_digit = 1; } if (!saw_digit) goto invalid; /* * OK, the next thing should be \r\n. */ if (len == 0) goto trunc; ND_TCHECK(*bp); if (*bp != '\r') goto invalid; bp++; len--; if (len == 0) goto trunc; ND_TCHECK(*bp); if (*bp != '\n') goto invalid; bp++; len--; *endp = bp; if (neg) { /* -1 means "null", anything else is invalid */ if (too_large || result != 1) return (-4); result = -1; } return (too_large ? -3 : result); trunc: return (-2); invalid: return (-5); } Commit Message: CVE-2017-12989/RESP: Make sure resp_get_length() advances the pointer for invalid lengths. Make sure that it always sends *endp before returning and that, for invalid lengths where we don't like a character in the length string, what it sets *endp to is past the character in question, so we don't run the risk of infinitely looping (or doing something else random) if a character in the length is invalid. This fixes an infinite loop discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-835
resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp) { int result; u_char c; int saw_digit; int neg; int too_large; if (len == 0) goto trunc; ND_TCHECK(*bp); too_large = 0; neg = 0; if (*bp == '-') { neg = 1; bp++; len--; } result = 0; saw_digit = 0; for (;;) { if (len == 0) goto trunc; ND_TCHECK(*bp); c = *bp; if (!(c >= '0' && c <= '9')) { if (!saw_digit) { bp++; goto invalid; } break; } c -= '0'; if (result > (INT_MAX / 10)) { /* This will overflow an int when we multiply it by 10. */ too_large = 1; } else { result *= 10; if (result == INT_MAX && c > (INT_MAX % 10)) { /* This will overflow an int when we add c */ too_large = 1; } else result += c; } bp++; len--; saw_digit = 1; } if (!saw_digit) goto invalid; /* * OK, the next thing should be \r\n. */ if (len == 0) goto trunc; ND_TCHECK(*bp); if (*bp != '\r') { bp++; goto invalid; } bp++; len--; if (len == 0) goto trunc; ND_TCHECK(*bp); if (*bp != '\n') { bp++; goto invalid; } bp++; len--; *endp = bp; if (neg) { /* -1 means "null", anything else is invalid */ if (too_large || result != 1) return (-4); result = -1; } return (too_large ? -3 : result); trunc: *endp = bp; return (-2); invalid: *endp = bp; return (-5); }
167,928
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copyMono8( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] << 8; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMono8( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] << 8; } }
174,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Atom::Atom() { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Chapters::Atom::Atom() long long SegmentInfo::GetDuration() const { if (m_duration < 0) return -1; assert(m_timecodeScale >= 1); const double dd = double(m_duration) * double(m_timecodeScale); const long long d = static_cast<long long>(dd); return d; }
174,238
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionBookmarksTest() : client_(NULL), model_(NULL), node_(NULL), folder_(NULL) {} Commit Message: Added unit test for new portion of GetMetaInfo API BUG=383600 Review URL: https://codereview.chromium.org/348833003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@278908 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ExtensionBookmarksTest()
171,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int nfs4_intent_set_file(struct nameidata *nd, struct path *path, struct nfs4_state *state) { struct file *filp; int ret; /* If the open_intent is for execute, we have an extra check to make */ if (nd->intent.open.flags & FMODE_EXEC) { ret = nfs_may_open(state->inode, state->owner->so_cred, nd->intent.open.flags); if (ret < 0) goto out_close; } filp = lookup_instantiate_filp(nd, path->dentry, NULL); if (!IS_ERR(filp)) { struct nfs_open_context *ctx; ctx = nfs_file_open_context(filp); ctx->state = state; return 0; } ret = PTR_ERR(filp); out_close: nfs4_close_sync(path, state, nd->intent.open.flags); return ret; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static int nfs4_intent_set_file(struct nameidata *nd, struct path *path, struct nfs4_state *state) static int nfs4_intent_set_file(struct nameidata *nd, struct path *path, struct nfs4_state *state, fmode_t fmode) { struct file *filp; int ret; /* If the open_intent is for execute, we have an extra check to make */ if (fmode & FMODE_EXEC) { ret = nfs_may_open(state->inode, state->owner->so_cred, nd->intent.open.flags); if (ret < 0) goto out_close; } filp = lookup_instantiate_filp(nd, path->dentry, NULL); if (!IS_ERR(filp)) { struct nfs_open_context *ctx; ctx = nfs_file_open_context(filp); ctx->state = state; return 0; } ret = PTR_ERR(filp); out_close: nfs4_close_sync(path, state, fmode & (FMODE_READ|FMODE_WRITE)); return ret; }
165,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: asmlinkage long sys_oabi_semtimedop(int semid, struct oabi_sembuf __user *tsops, unsigned nsops, const struct timespec __user *timeout) { struct sembuf *sops; struct timespec local_timeout; long err; int i; if (nsops < 1) return -EINVAL; sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL); if (!sops) return -ENOMEM; err = 0; for (i = 0; i < nsops; i++) { __get_user_error(sops[i].sem_num, &tsops->sem_num, err); __get_user_error(sops[i].sem_op, &tsops->sem_op, err); __get_user_error(sops[i].sem_flg, &tsops->sem_flg, err); tsops++; } if (timeout) { /* copy this as well before changing domain protection */ err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout)); timeout = &local_timeout; } if (err) { err = -EFAULT; } else { mm_segment_t fs = get_fs(); set_fs(KERNEL_DS); err = sys_semtimedop(semid, sops, nsops, timeout); set_fs(fs); } kfree(sops); return err; } Commit Message: ARM: 6891/1: prevent heap corruption in OABI semtimedop When CONFIG_OABI_COMPAT is set, the wrapper for semtimedop does not bound the nsops argument. A sufficiently large value will cause an integer overflow in allocation size, followed by copying too much data into the allocated buffer. Fix this by restricting nsops to SEMOPM. Untested. Cc: stable@kernel.org Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk> CWE ID: CWE-189
asmlinkage long sys_oabi_semtimedop(int semid, struct oabi_sembuf __user *tsops, unsigned nsops, const struct timespec __user *timeout) { struct sembuf *sops; struct timespec local_timeout; long err; int i; if (nsops < 1 || nsops > SEMOPM) return -EINVAL; sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL); if (!sops) return -ENOMEM; err = 0; for (i = 0; i < nsops; i++) { __get_user_error(sops[i].sem_num, &tsops->sem_num, err); __get_user_error(sops[i].sem_op, &tsops->sem_op, err); __get_user_error(sops[i].sem_flg, &tsops->sem_flg, err); tsops++; } if (timeout) { /* copy this as well before changing domain protection */ err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout)); timeout = &local_timeout; } if (err) { err = -EFAULT; } else { mm_segment_t fs = get_fs(); set_fs(KERNEL_DS); err = sys_semtimedop(semid, sops, nsops, timeout); set_fs(fs); } kfree(sops); return err; }
165,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void close_uinput (void) { BTIF_TRACE_DEBUG("%s", __FUNCTION__); if (uinput_fd > 0) { ioctl(uinput_fd, UI_DEV_DESTROY); close(uinput_fd); uinput_fd = -1; } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void close_uinput (void) { BTIF_TRACE_DEBUG("%s", __FUNCTION__); if (uinput_fd > 0) { TEMP_FAILURE_RETRY(ioctl(uinput_fd, UI_DEV_DESTROY)); close(uinput_fd); uinput_fd = -1; } }
173,450
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); put_io_context(ioc); } } Commit Message: block: Fix io_context leak after clone with CLONE_IO With CLONE_IO, copy_io() increments both ioc->refcount and ioc->nr_tasks. However exit_io_context() only decrements ioc->refcount if ioc->nr_tasks reaches 0. Always call put_io_context() in exit_io_context(). Signed-off-by: Louis Rilling <louis.rilling@kerlabs.com> Signed-off-by: Jens Axboe <jens.axboe@oracle.com> CWE ID: CWE-20
void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); } put_io_context(ioc); }
165,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int user_match(const struct key *key, const struct key_match_data *match_data) { return strcmp(key->description, match_data->raw_data) == 0; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
int user_match(const struct key *key, const struct key_match_data *match_data)
168,443
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, IncludePrivacySensitiveFields include_privacy_sensitive_fields) { NOTIMPLEMENTED(); return NULL; } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index) { NOTIMPLEMENTED(); return NULL; }
171,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error) { GArray *array; int i; int j; j = 0; array = (GArray *)g_value_get_boxed (variant); for (i = 0; i <= 2; i++) { j = g_array_index (array, int, i); if (j != i + 1) goto error; } return TRUE; error: *error = g_error_new (MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "Error decoding a variant of type ai (i + 1 = %i, j = %i)", i, j + 1); return FALSE; } Commit Message: CWE ID: CWE-264
my_object_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error)
165,115
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mb_split) { char *arg_pattern; int arg_pattern_len; php_mb_regex_t *re; OnigRegion *regs = NULL; char *string; OnigUChar *pos, *chunk_pos; int string_len; int n, err; long count = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) { RETURN_FALSE; } if (count > 0) { count--; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC)) == NULL) { RETURN_FALSE; } array_init(return_value); chunk_pos = pos = (OnigUChar *)string; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while (count != 0 && (pos - (OnigUChar *)string) < string_len) { int beg, end; err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0); if (err < 0) { break; } beg = regs->beg[0], end = regs->end[0]; /* add it to the array */ if ((pos - (OnigUChar *)string) < end) { if (beg < string_len && beg >= (chunk_pos - (OnigUChar *)string)) { add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos), 1); --count; } else { err = -2; break; } /* point at our new starting point */ chunk_pos = pos = (OnigUChar *)string + end; } else { pos++; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str); zval_dtor(return_value); RETURN_FALSE; } /* otherwise we just have one last element to add to the array */ n = ((OnigUChar *)(string + string_len) - chunk_pos); if (n > 0) { add_next_index_stringl(return_value, (char *)chunk_pos, n, 1); } else { add_next_index_stringl(return_value, "", 0, 1); } } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
PHP_FUNCTION(mb_split) { char *arg_pattern; int arg_pattern_len; php_mb_regex_t *re; OnigRegion *regs = NULL; char *string; OnigUChar *pos, *chunk_pos; int string_len; int n, err; long count = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) { RETURN_FALSE; } if (count > 0) { count--; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC)) == NULL) { RETURN_FALSE; } array_init(return_value); chunk_pos = pos = (OnigUChar *)string; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while (count != 0 && (pos - (OnigUChar *)string) < string_len) { int beg, end; err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0); if (err < 0) { break; } beg = regs->beg[0], end = regs->end[0]; /* add it to the array */ if ((pos - (OnigUChar *)string) < end) { if (beg < string_len && beg >= (chunk_pos - (OnigUChar *)string)) { add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos), 1); --count; } else { err = -2; break; } /* point at our new starting point */ chunk_pos = pos = (OnigUChar *)string + end; } else { pos++; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str); zval_dtor(return_value); RETURN_FALSE; } /* otherwise we just have one last element to add to the array */ n = ((OnigUChar *)(string + string_len) - chunk_pos); if (n > 0) { add_next_index_stringl(return_value, (char *)chunk_pos, n, 1); } else { add_next_index_stringl(return_value, "", 0, 1); } }
167,115
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const { return url.SchemeIs(chrome::kChromeDevToolsScheme) || url.SchemeIs(chrome::kChromeInternalScheme) || url.SchemeIs(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const {
171,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long gfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len) { struct inode *inode = file->f_path.dentry->d_inode; struct gfs2_sbd *sdp = GFS2_SB(inode); struct gfs2_inode *ip = GFS2_I(inode); unsigned int data_blocks = 0, ind_blocks = 0, rblocks; loff_t bytes, max_bytes; struct gfs2_alloc *al; int error; loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1); loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift; next = (next + 1) << sdp->sd_sb.sb_bsize_shift; /* We only support the FALLOC_FL_KEEP_SIZE mode */ if (mode & ~FALLOC_FL_KEEP_SIZE) return -EOPNOTSUPP; offset &= bsize_mask; len = next - offset; bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2; if (!bytes) bytes = UINT_MAX; bytes &= bsize_mask; if (bytes == 0) bytes = sdp->sd_sb.sb_bsize; gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh); error = gfs2_glock_nq(&ip->i_gh); if (unlikely(error)) goto out_uninit; if (!gfs2_write_alloc_required(ip, offset, len)) goto out_unlock; while (len > 0) { if (len < bytes) bytes = len; al = gfs2_alloc_get(ip); if (!al) { error = -ENOMEM; goto out_unlock; } error = gfs2_quota_lock_check(ip); if (error) goto out_alloc_put; retry: gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks); al->al_requested = data_blocks + ind_blocks; error = gfs2_inplace_reserve(ip); if (error) { if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) { bytes >>= 1; bytes &= bsize_mask; if (bytes == 0) bytes = sdp->sd_sb.sb_bsize; goto retry; } goto out_qunlock; } max_bytes = bytes; calc_max_reserv(ip, len, &max_bytes, &data_blocks, &ind_blocks); al->al_requested = data_blocks + ind_blocks; rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA + RES_RG_HDR + gfs2_rg_blocks(ip); if (gfs2_is_jdata(ip)) rblocks += data_blocks ? data_blocks : 1; error = gfs2_trans_begin(sdp, rblocks, PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize); if (error) goto out_trans_fail; error = fallocate_chunk(inode, offset, max_bytes, mode); gfs2_trans_end(sdp); if (error) goto out_trans_fail; len -= max_bytes; offset += max_bytes; gfs2_inplace_release(ip); gfs2_quota_unlock(ip); gfs2_alloc_put(ip); } goto out_unlock; out_trans_fail: gfs2_inplace_release(ip); out_qunlock: gfs2_quota_unlock(ip); out_alloc_put: gfs2_alloc_put(ip); out_unlock: gfs2_glock_dq(&ip->i_gh); out_uninit: gfs2_holder_uninit(&ip->i_gh); return error; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com> Signed-off-by: Steven Whitehouse <swhiteho@redhat.com> CWE ID: CWE-119
static long gfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len) { struct inode *inode = file->f_path.dentry->d_inode; struct gfs2_sbd *sdp = GFS2_SB(inode); struct gfs2_inode *ip = GFS2_I(inode); unsigned int data_blocks = 0, ind_blocks = 0, rblocks; loff_t bytes, max_bytes; struct gfs2_alloc *al; int error; loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1); loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift; loff_t max_chunk_size = UINT_MAX & bsize_mask; next = (next + 1) << sdp->sd_sb.sb_bsize_shift; /* We only support the FALLOC_FL_KEEP_SIZE mode */ if (mode & ~FALLOC_FL_KEEP_SIZE) return -EOPNOTSUPP; offset &= bsize_mask; len = next - offset; bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2; if (!bytes) bytes = UINT_MAX; bytes &= bsize_mask; if (bytes == 0) bytes = sdp->sd_sb.sb_bsize; gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh); error = gfs2_glock_nq(&ip->i_gh); if (unlikely(error)) goto out_uninit; if (!gfs2_write_alloc_required(ip, offset, len)) goto out_unlock; while (len > 0) { if (len < bytes) bytes = len; al = gfs2_alloc_get(ip); if (!al) { error = -ENOMEM; goto out_unlock; } error = gfs2_quota_lock_check(ip); if (error) goto out_alloc_put; retry: gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks); al->al_requested = data_blocks + ind_blocks; error = gfs2_inplace_reserve(ip); if (error) { if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) { bytes >>= 1; bytes &= bsize_mask; if (bytes == 0) bytes = sdp->sd_sb.sb_bsize; goto retry; } goto out_qunlock; } max_bytes = bytes; calc_max_reserv(ip, (len > max_chunk_size)? max_chunk_size: len, &max_bytes, &data_blocks, &ind_blocks); al->al_requested = data_blocks + ind_blocks; rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA + RES_RG_HDR + gfs2_rg_blocks(ip); if (gfs2_is_jdata(ip)) rblocks += data_blocks ? data_blocks : 1; error = gfs2_trans_begin(sdp, rblocks, PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize); if (error) goto out_trans_fail; error = fallocate_chunk(inode, offset, max_bytes, mode); gfs2_trans_end(sdp); if (error) goto out_trans_fail; len -= max_bytes; offset += max_bytes; gfs2_inplace_release(ip); gfs2_quota_unlock(ip); gfs2_alloc_put(ip); } goto out_unlock; out_trans_fail: gfs2_inplace_release(ip); out_qunlock: gfs2_quota_unlock(ip); out_alloc_put: gfs2_alloc_put(ip); out_unlock: gfs2_glock_dq(&ip->i_gh); out_uninit: gfs2_holder_uninit(&ip->i_gh); return error; }
166,213
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sanity_check_ckpt(struct f2fs_sb_info *sbi) { unsigned int total, fsmeta; struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); unsigned int ovp_segments, reserved_segments; total = le32_to_cpu(raw_super->segment_count); fsmeta = le32_to_cpu(raw_super->segment_count_ckpt); fsmeta += le32_to_cpu(raw_super->segment_count_sit); fsmeta += le32_to_cpu(raw_super->segment_count_nat); fsmeta += le32_to_cpu(ckpt->rsvd_segment_count); fsmeta += le32_to_cpu(raw_super->segment_count_ssa); if (unlikely(fsmeta >= total)) return 1; ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); if (unlikely(fsmeta < F2FS_MIN_SEGMENTS || ovp_segments == 0 || reserved_segments == 0)) { f2fs_msg(sbi->sb, KERN_ERR, "Wrong layout: check mkfs.f2fs version"); return 1; } if (unlikely(f2fs_cp_error(sbi))) { f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck"); return 1; } return 0; } Commit Message: f2fs: sanity check checkpoint segno and blkoff Make sure segno and blkoff read from raw image are valid. Cc: stable@vger.kernel.org Signed-off-by: Jin Qian <jinqian@google.com> [Jaegeuk Kim: adjust minor coding style] Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-129
int sanity_check_ckpt(struct f2fs_sb_info *sbi) { unsigned int total, fsmeta; struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); unsigned int ovp_segments, reserved_segments; unsigned int main_segs, blocks_per_seg; int i; total = le32_to_cpu(raw_super->segment_count); fsmeta = le32_to_cpu(raw_super->segment_count_ckpt); fsmeta += le32_to_cpu(raw_super->segment_count_sit); fsmeta += le32_to_cpu(raw_super->segment_count_nat); fsmeta += le32_to_cpu(ckpt->rsvd_segment_count); fsmeta += le32_to_cpu(raw_super->segment_count_ssa); if (unlikely(fsmeta >= total)) return 1; ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); if (unlikely(fsmeta < F2FS_MIN_SEGMENTS || ovp_segments == 0 || reserved_segments == 0)) { f2fs_msg(sbi->sb, KERN_ERR, "Wrong layout: check mkfs.f2fs version"); return 1; } main_segs = le32_to_cpu(raw_super->segment_count_main); blocks_per_seg = sbi->blocks_per_seg; for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) { if (le32_to_cpu(ckpt->cur_node_segno[i]) >= main_segs || le16_to_cpu(ckpt->cur_node_blkoff[i]) >= blocks_per_seg) return 1; } for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) { if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs || le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg) return 1; } if (unlikely(f2fs_cp_error(sbi))) { f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck"); return 1; } return 0; }
168,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fbCompositeGeneral (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; Bool srcRepeat = FALSE; Bool maskRepeat = FALSE; int w, h; CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH*3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData compose_data; if (pSrc->pDrawable) srcRepeat = pSrc->repeatType == RepeatNormal && !pSrc->transform && (pSrc->pDrawable->width != 1 || pSrc->pDrawable->height != 1); if (pMask && pMask->pDrawable) maskRepeat = pMask->repeatType == RepeatNormal && !pMask->transform && (pMask->pDrawable->width != 1 || pMask->pDrawable->height != 1); if (op == PictOpOver && !pMask && !pSrc->transform && !PICT_FORMAT_A(pSrc->format) && !pSrc->alphaMap) op = PictOpSrc; if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; compose_data.op = op; compose_data.src = pSrc; compose_data.mask = pMask; compose_data.dest = pDst; if (width > SCANLINE_BUFFER_LENGTH) scanline_buffer = (CARD32 *) malloc(width * 3 * sizeof(CARD32)); n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; compose_data.ySrc = pbox->y1 - yDst + ySrc; compose_data.yMask = pbox->y1 - yDst + yMask; compose_data.yDest = pbox->y1; while (h) { compose_data.height = h; w = pbox->x2 - pbox->x1; compose_data.xSrc = pbox->x1 - xDst + xSrc; compose_data.xMask = pbox->x1 - xDst + xMask; compose_data.xDest = pbox->x1; if (maskRepeat) { compose_data.yMask = mod (compose_data.yMask, pMask->pDrawable->height); if (compose_data.height > pMask->pDrawable->height - compose_data.yMask) compose_data.height = pMask->pDrawable->height - compose_data.yMask; } if (srcRepeat) { compose_data.ySrc = mod (compose_data.ySrc, pSrc->pDrawable->height); if (compose_data.height > pSrc->pDrawable->height - compose_data.ySrc) compose_data.height = pSrc->pDrawable->height - compose_data.ySrc; } while (w) { compose_data.width = w; if (maskRepeat) { compose_data.xMask = mod (compose_data.xMask, pMask->pDrawable->width); if (compose_data.width > pMask->pDrawable->width - compose_data.xMask) compose_data.width = pMask->pDrawable->width - compose_data.xMask; } if (srcRepeat) { compose_data.xSrc = mod (compose_data.xSrc, pSrc->pDrawable->width); if (compose_data.width > pSrc->pDrawable->width - compose_data.xSrc) compose_data.width = pSrc->pDrawable->width - compose_data.xSrc; } fbCompositeRect(&compose_data, scanline_buffer); w -= compose_data.width; compose_data.xSrc += compose_data.width; compose_data.xMask += compose_data.width; compose_data.xDest += compose_data.width; } h -= compose_data.height; compose_data.ySrc += compose_data.height; compose_data.yMask += compose_data.height; compose_data.yDest += compose_data.height; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); if (scanline_buffer != _scanline_buffer) free(scanline_buffer); } Commit Message: CWE ID: CWE-189
fbCompositeGeneral (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { return fbComposite (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); }
165,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct bsg_device *bd = file->private_data; ssize_t bytes_written; int ret; dprintk("%s: write %Zd bytes\n", bd->name, count); bsg_set_block(bd, file); bytes_written = 0; ret = __bsg_write(bd, buf, count, &bytes_written, file->f_mode & FMODE_WRITE); *ppos = bytes_written; /* * return bytes written on non-fatal errors */ if (!bytes_written || err_block_err(ret)) bytes_written = ret; dprintk("%s: returning %Zd\n", bd->name, bytes_written); return bytes_written; } Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS Both damn things interpret userland pointers embedded into the payload; worse, they are actually traversing those. Leaving aside the bad API design, this is very much _not_ safe to call with KERNEL_DS. Bail out early if that happens. Cc: stable@vger.kernel.org Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-416
bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct bsg_device *bd = file->private_data; ssize_t bytes_written; int ret; dprintk("%s: write %Zd bytes\n", bd->name, count); if (unlikely(segment_eq(get_fs(), KERNEL_DS))) return -EINVAL; bsg_set_block(bd, file); bytes_written = 0; ret = __bsg_write(bd, buf, count, &bytes_written, file->f_mode & FMODE_WRITE); *ppos = bytes_written; /* * return bytes written on non-fatal errors */ if (!bytes_written || err_block_err(ret)) bytes_written = ret; dprintk("%s: returning %Zd\n", bd->name, bytes_written); return bytes_written; }
166,840
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<DrawingBuffer> DrawingBuffer::Create( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, Client* client, const IntSize& size, bool premultiplied_alpha, bool want_alpha_channel, bool want_depth_buffer, bool want_stencil_buffer, bool want_antialiasing, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) { DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; return nullptr; } std::unique_ptr<Extensions3DUtil> extensions_util = Extensions3DUtil::Create(context_provider->ContextGL()); if (!extensions_util->IsValid()) { return nullptr; } DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample") || extensions_util->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) && extensions_util->SupportsExtension("GL_OES_rgb8_rgba8"); if (multisample_supported) { extensions_util->EnsureExtensionEnabled("GL_OES_rgb8_rgba8"); if (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample")) extensions_util->EnsureExtensionEnabled( "GL_CHROMIUM_framebuffer_multisample"); else extensions_util->EnsureExtensionEnabled( "GL_EXT_multisampled_render_to_texture"); } bool discard_framebuffer_supported = extensions_util->SupportsExtension("GL_EXT_discard_framebuffer"); if (discard_framebuffer_supported) extensions_util->EnsureExtensionEnabled("GL_EXT_discard_framebuffer"); RefPtr<DrawingBuffer> drawing_buffer = AdoptRef(new DrawingBuffer( std::move(context_provider), std::move(extensions_util), client, discard_framebuffer_supported, want_alpha_channel, premultiplied_alpha, preserve, web_gl_version, want_depth_buffer, want_stencil_buffer, chromium_image_usage, color_params)); if (!drawing_buffer->Initialize(size, multisample_supported)) { drawing_buffer->BeginDestruction(); return PassRefPtr<DrawingBuffer>(); } return drawing_buffer; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
PassRefPtr<DrawingBuffer> DrawingBuffer::Create( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, Client* client, const IntSize& size, bool premultiplied_alpha, bool want_alpha_channel, bool want_depth_buffer, bool want_stencil_buffer, bool want_antialiasing, PreserveDrawingBuffer preserve, WebGLVersion webgl_version, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) { DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; return nullptr; } std::unique_ptr<Extensions3DUtil> extensions_util = Extensions3DUtil::Create(context_provider->ContextGL()); if (!extensions_util->IsValid()) { return nullptr; } DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample") || extensions_util->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) && extensions_util->SupportsExtension("GL_OES_rgb8_rgba8"); if (multisample_supported) { extensions_util->EnsureExtensionEnabled("GL_OES_rgb8_rgba8"); if (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample")) extensions_util->EnsureExtensionEnabled( "GL_CHROMIUM_framebuffer_multisample"); else extensions_util->EnsureExtensionEnabled( "GL_EXT_multisampled_render_to_texture"); } bool discard_framebuffer_supported = extensions_util->SupportsExtension("GL_EXT_discard_framebuffer"); if (discard_framebuffer_supported) extensions_util->EnsureExtensionEnabled("GL_EXT_discard_framebuffer"); RefPtr<DrawingBuffer> drawing_buffer = AdoptRef(new DrawingBuffer( std::move(context_provider), std::move(extensions_util), client, discard_framebuffer_supported, want_alpha_channel, premultiplied_alpha, preserve, webgl_version, want_depth_buffer, want_stencil_buffer, chromium_image_usage, color_params)); if (!drawing_buffer->Initialize(size, multisample_supported)) { drawing_buffer->BeginDestruction(); return PassRefPtr<DrawingBuffer>(); } return drawing_buffer; }
172,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int entersafe_gen_key(sc_card_t *card, sc_entersafe_gen_key_data *data) { int r; size_t len = data->key_length >> 3; sc_apdu_t apdu; u8 rbuf[300]; u8 sbuf[4],*p; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* MSE */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x01, 0xB8); apdu.lc=0x04; sbuf[0]=0x83; sbuf[1]=0x02; sbuf[2]=data->key_id; sbuf[3]=0x2A; apdu.data = sbuf; apdu.datalen=4; apdu.lc=4; apdu.le=0; r=entersafe_transmit_apdu(card, &apdu, 0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe set MSE failed"); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.le = 0; sbuf[0] = (u8)(data->key_length >> 8); sbuf[1] = (u8)(data->key_length); apdu.data = sbuf; apdu.lc = 2; apdu.datalen = 2; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe generate keypair failed"); /* read public key via READ PUBLIC KEY */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xE6, 0x2A, data->key_id); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get pukey failed"); data->modulus = malloc(len); if (!data->modulus) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_OUT_OF_MEMORY); p=rbuf; assert(*p=='E'); p+=2+p[1]; /* N */ assert(*p=='N'); ++p; if(*p++>0x80) { u8 len_bytes=(*(p-1))&0x0f; size_t module_len=0; while(len_bytes!=0) { module_len=module_len<<8; module_len+=*p++; --len_bytes; } } entersafe_reverse_buffer(p,len); memcpy(data->modulus,p,len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static int entersafe_gen_key(sc_card_t *card, sc_entersafe_gen_key_data *data) { int r; size_t len = data->key_length >> 3; sc_apdu_t apdu; u8 rbuf[300]; u8 sbuf[4],*p; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* MSE */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x01, 0xB8); apdu.lc=0x04; sbuf[0]=0x83; sbuf[1]=0x02; sbuf[2]=data->key_id; sbuf[3]=0x2A; apdu.data = sbuf; apdu.datalen=4; apdu.lc=4; apdu.le=0; r=entersafe_transmit_apdu(card, &apdu, 0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe set MSE failed"); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.le = 0; sbuf[0] = (u8)(data->key_length >> 8); sbuf[1] = (u8)(data->key_length); apdu.data = sbuf; apdu.lc = 2; apdu.datalen = 2; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe generate keypair failed"); /* read public key via READ PUBLIC KEY */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xE6, 0x2A, data->key_id); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get pukey failed"); data->modulus = malloc(len); if (!data->modulus) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); p=rbuf; if (*p!='E') SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_DATA); p+=2+p[1]; /* N */ if (*p!='N') SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_DATA); ++p; if(*p++>0x80) { u8 len_bytes=(*(p-1))&0x0f; size_t module_len=0; while(len_bytes!=0) { module_len=module_len<<8; module_len+=*p++; --len_bytes; } } entersafe_reverse_buffer(p,len); memcpy(data->modulus,p,len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS); }
169,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zlib_end(struct zlib *zlib) { /* Output the summary line now; this ensures a summary line always gets * output regardless of the manner of exit. */ if (!zlib->global->quiet) { if (zlib->ok_bits < 16) /* stream was read ok */ { const char *reason; if (zlib->cksum) reason = "CHK"; /* checksum error */ else if (zlib->ok_bits > zlib->file_bits) reason = "TFB"; /* fixing a too-far-back error */ else if (zlib->ok_bits == zlib->file_bits) reason = "OK "; else reason = "OPT"; /* optimizing window bits */ /* SUMMARY FORMAT (for a successful zlib inflate): * * IDAT reason flevel file-bits ok-bits compressed uncompressed file */ type_name(zlib->chunk->chunk_type, stdout); printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits, zlib->ok_bits); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits, stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } else { /* This is a zlib read error; the chunk will be skipped. For an IDAT * stream this will also cause a fatal read error (via stop()). * * SUMMARY FORMAT: * * IDAT SKP flevel file-bits z-rc compressed message file * * z-rc is the zlib failure code; message is the error message with * spaces replaced by '-'. The compressed byte count indicates where * in the zlib stream the error occured. */ type_name(zlib->chunk->chunk_type, stdout); printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits, zlib_rc(zlib)); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } } if (zlib->state >= 0) { zlib->rc = inflateEnd(&zlib->z); if (zlib->rc != Z_OK) zlib_message(zlib, 1/*unexpected*/); } CLEAR(*zlib); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
zlib_end(struct zlib *zlib) { /* Output the summary line now; this ensures a summary line always gets * output regardless of the manner of exit. */ if (!zlib->global->quiet) { if (zlib->ok_bits < 16) /* stream was read ok */ { const char *reason; if (zlib->cksum) reason = "CHK"; /* checksum error */ else if (zlib->ok_bits > zlib->file_bits) reason = "TFB"; /* fixing a too-far-back error */ else if (zlib->ok_bits == zlib->file_bits) reason = "OK "; else reason = "OPT"; /* optimizing window bits */ /* SUMMARY FORMAT (for a successful zlib inflate): * * IDAT reason flevel file-bits ok-bits compressed uncompressed file */ type_name(zlib->chunk->chunk_type, stdout); printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits, zlib->ok_bits); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits, stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } else { /* This is a zlib read error; the chunk will be skipped. For an IDAT * stream this will also cause a fatal read error (via stop()). * * SUMMARY FORMAT: * * IDAT SKP flevel file-bits z-rc compressed message file * * z-rc is the zlib failure code; message is the error message with * spaces replaced by '-'. The compressed byte count indicates where * in the zlib stream the error occurred. */ type_name(zlib->chunk->chunk_type, stdout); printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits, zlib_rc(zlib)); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } } if (zlib->state >= 0) { zlib->rc = inflateEnd(&zlib->z); if (zlib->rc != Z_OK) zlib_message(zlib, 1/*unexpected*/); } CLEAR(*zlib); }
173,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InitializeOriginStatFromOriginRequestSummary( OriginStat* origin, const OriginRequestSummary& summary) { origin->set_origin(summary.origin.spec()); origin->set_number_of_hits(1); origin->set_average_position(summary.first_occurrence + 1); origin->set_always_access_network(summary.always_access_network); origin->set_accessed_network(summary.accessed_network); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void InitializeOriginStatFromOriginRequestSummary( OriginStat* origin, const OriginRequestSummary& summary) { origin->set_origin(summary.origin.GetURL().spec()); origin->set_number_of_hits(1); origin->set_average_position(summary.first_occurrence + 1); origin->set_always_access_network(summary.always_access_network); origin->set_accessed_network(summary.accessed_network); }
172,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; } Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers We had for some reason overlooked the AIO interface, and it didn't use the proper rw_verify_area() helper function that checks (for example) mandatory locking on the file, and that the size of the access doesn't cause us to overflow the provided offset limits etc. Instead, AIO did just the security_file_permission() thing (that rw_verify_area() also does) directly. This fixes it to do all the proper helper functions, which not only means that now mandatory file locking works with AIO too, we can actually remove lines of code. Reported-by: Manish Honap <manish_honap_vit@yahoo.co.in> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID:
static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = aio_setup_single_vector(READ, file, kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = aio_setup_single_vector(WRITE, file, kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; }
167,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 || tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } Commit Message: Unsupported TGA bpp/alphabit combinations should error gracefully Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are really supported. All other combinations will be rejected with a warning. CWE ID: CWE-125
BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; }
167,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms) { M_fs_file_t *fd_old; M_fs_file_t *fd_new; M_fs_info_t *info = NULL; unsigned char temp[M_FS_BUF_SIZE]; size_t read_len; size_t wrote_len; size_t wrote_total = 0; size_t offset; M_fs_error_t res; /* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it * to new file. */ if (M_fs_perms_can_access(path_new, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { /* Try to delete the file since we'll be overwrite it. This is so when we create the file we create it without * any permissions and to ensure that anything that has the file already open won't be able to read the new * contents we're writing to the file or be able to change the perms. There is an unavoidable race condition * between deleting and creating the file where someone could create the file and have access. However, * depending on the OS they may have access even if the file is created with no perms... */ res = M_fs_delete(path_new, M_FALSE, NULL, M_FS_PROGRESS_NOEXTRA); if (res != M_FS_ERROR_SUCCESS) { return res; } } /* Open the old file */ res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL); if (res != M_FS_ERROR_SUCCESS) { return res; } if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) { res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } perms = M_fs_info_get_perms(info); } res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms); M_fs_info_destroy(info); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } /* Copy the contents of old into new. */ while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) { offset = 0; while (offset < read_len) { res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL); offset += wrote_len; wrote_total += wrote_len; if (cb) { M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, wrote_total); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } if (res != M_FS_ERROR_SUCCESS) { break; } } M_fs_file_close(fd_old); M_fs_file_close(fd_new); if (res != M_FS_ERROR_SUCCESS) { return res; } return M_FS_ERROR_SUCCESS; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms) { M_fs_file_t *fd_old; M_fs_file_t *fd_new; M_fs_info_t *info = NULL; unsigned char temp[M_FS_BUF_SIZE]; size_t read_len; size_t wrote_len; size_t wrote_total = 0; size_t offset; M_fs_error_t res; /* Open the old file */ res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL); if (res != M_FS_ERROR_SUCCESS) { return res; } if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) { res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } perms = M_fs_info_get_perms(info); } /* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it * to new file. */ res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms); M_fs_info_destroy(info); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } /* Copy the contents of old into new. */ while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) { offset = 0; while (offset < read_len) { res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL); offset += wrote_len; wrote_total += wrote_len; if (cb) { M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, wrote_total); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } if (res != M_FS_ERROR_SUCCESS) { break; } } M_fs_file_close(fd_old); M_fs_file_close(fd_new); if (res != M_FS_ERROR_SUCCESS) { return res; } return M_FS_ERROR_SUCCESS; }
169,142