instruction
stringclasses
1 value
input
stringlengths
64
129k
output
int64
0
1
__index_level_0__
int64
0
30k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p) { struct session_state *state = ssh->state; u_int padlen, need; u_char *cp; u_int maclen, aadlen = 0, authlen = 0, block_size; struct sshenc *enc = NULL; struct sshmac *mac = NULL; struct sshcomp *comp = NULL; int r; *typep = SSH_MSG_NONE; if (state->packet_discard) return 0; if (state->newkeys[MODE_IN] != NULL) { enc = &state->newkeys[MODE_IN]->enc; mac = &state->newkeys[MODE_IN]->mac; comp = &state->newkeys[MODE_IN]->comp; /* disable mac for authenticated encryption */ if ((authlen = cipher_authlen(enc->cipher)) != 0) mac = NULL; } maclen = mac && mac->enabled ? mac->mac_len : 0; block_size = enc ? enc->block_size : 8; aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0; if (aadlen && state->packlen == 0) { if (cipher_get_length(state->receive_context, &state->packlen, state->p_read.seqnr, sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0) return 0; if (state->packlen < 1 + 4 || state->packlen > PACKET_MAX_SIZE) { #ifdef PACKET_DEBUG sshbuf_dump(state->input, stderr); #endif logit("Bad packet length %u.", state->packlen); if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0) return r; return SSH_ERR_CONN_CORRUPT; } sshbuf_reset(state->incoming_packet); } else if (state->packlen == 0) { /* * check if input size is less than the cipher block size, * decrypt first block and extract length of incoming packet */ if (sshbuf_len(state->input) < block_size) return 0; sshbuf_reset(state->incoming_packet); if ((r = sshbuf_reserve(state->incoming_packet, block_size, &cp)) != 0) goto out; if ((r = cipher_crypt(state->receive_context, state->p_send.seqnr, cp, sshbuf_ptr(state->input), block_size, 0, 0)) != 0) goto out; state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet)); if (state->packlen < 1 + 4 || state->packlen > PACKET_MAX_SIZE) { #ifdef PACKET_DEBUG fprintf(stderr, "input: \n"); sshbuf_dump(state->input, stderr); fprintf(stderr, "incoming_packet: \n"); sshbuf_dump(state->incoming_packet, stderr); #endif logit("Bad packet length %u.", state->packlen); return ssh_packet_start_discard(ssh, enc, mac, 0, PACKET_MAX_SIZE); } if ((r = sshbuf_consume(state->input, block_size)) != 0) goto out; } DBG(debug("input: packet len %u", state->packlen+4)); if (aadlen) { /* only the payload is encrypted */ need = state->packlen; } else { /* * the payload size and the payload are encrypted, but we * have a partial packet of block_size bytes */ need = 4 + state->packlen - block_size; } DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d," " aadlen %d", block_size, need, maclen, authlen, aadlen)); if (need % block_size != 0) { logit("padding error: need %d block %d mod %d", need, block_size, need % block_size); return ssh_packet_start_discard(ssh, enc, mac, 0, PACKET_MAX_SIZE - block_size); } /* * check if the entire packet has been received and * decrypt into incoming_packet: * 'aadlen' bytes are unencrypted, but authenticated. * 'need' bytes are encrypted, followed by either * 'authlen' bytes of authentication tag or * 'maclen' bytes of message authentication code. */ if (sshbuf_len(state->input) < aadlen + need + authlen + maclen) return 0; /* packet is incomplete */ #ifdef PACKET_DEBUG fprintf(stderr, "read_poll enc/full: "); sshbuf_dump(state->input, stderr); #endif /* EtM: check mac over encrypted input */ if (mac && mac->enabled && mac->etm) { if ((r = mac_check(mac, state->p_read.seqnr, sshbuf_ptr(state->input), aadlen + need, sshbuf_ptr(state->input) + aadlen + need + authlen, maclen)) != 0) { if (r == SSH_ERR_MAC_INVALID) logit("Corrupted MAC on input."); goto out; } } if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need, &cp)) != 0) goto out; if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp, sshbuf_ptr(state->input), need, aadlen, authlen)) != 0) goto out; if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0) goto out; if (mac && mac->enabled) { /* Not EtM: check MAC over cleartext */ if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr, sshbuf_ptr(state->incoming_packet), sshbuf_len(state->incoming_packet), sshbuf_ptr(state->input), maclen)) != 0) { if (r != SSH_ERR_MAC_INVALID) goto out; logit("Corrupted MAC on input."); if (need > PACKET_MAX_SIZE) return SSH_ERR_INTERNAL_ERROR; return ssh_packet_start_discard(ssh, enc, mac, sshbuf_len(state->incoming_packet), PACKET_MAX_SIZE - need); } /* Remove MAC from input buffer */ DBG(debug("MAC #%d ok", state->p_read.seqnr)); if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0) goto out; } if (seqnr_p != NULL) *seqnr_p = state->p_read.seqnr; if (++state->p_read.seqnr == 0) logit("incoming seqnr wraps around"); if (++state->p_read.packets == 0) if (!(ssh->compat & SSH_BUG_NOREKEY)) return SSH_ERR_NEED_REKEY; state->p_read.blocks += (state->packlen + 4) / block_size; state->p_read.bytes += state->packlen + 4; /* get padlen */ padlen = sshbuf_ptr(state->incoming_packet)[4]; DBG(debug("input: padlen %d", padlen)); if (padlen < 4) { if ((r = sshpkt_disconnect(ssh, "Corrupted padlen %d on input.", padlen)) != 0 || (r = ssh_packet_write_wait(ssh)) != 0) return r; return SSH_ERR_CONN_CORRUPT; } /* skip packet size + padlen, discard padding */ if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 || ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0)) goto out; DBG(debug("input: len before de-compress %zd", sshbuf_len(state->incoming_packet))); if (comp && comp->enabled) { sshbuf_reset(state->compression_buffer); if ((r = uncompress_buffer(ssh, state->incoming_packet, state->compression_buffer)) != 0) goto out; sshbuf_reset(state->incoming_packet); if ((r = sshbuf_putb(state->incoming_packet, state->compression_buffer)) != 0) goto out; DBG(debug("input: len after de-compress %zd", sshbuf_len(state->incoming_packet))); } /* * get packet type, implies consume. * return length of payload (without type field) */ if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0) goto out; if (ssh_packet_log_type(*typep)) debug3("receive packet: type %u", *typep); if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) { if ((r = sshpkt_disconnect(ssh, "Invalid ssh2 packet type: %d", *typep)) != 0 || (r = ssh_packet_write_wait(ssh)) != 0) return r; return SSH_ERR_PROTOCOL_ERROR; } if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side) r = ssh_packet_enable_delayed_compress(ssh); else r = 0; #ifdef PACKET_DEBUG fprintf(stderr, "read/plain[%d]:\r\n", *typep); sshbuf_dump(state->incoming_packet, stderr); #endif /* reset for next packet */ state->packlen = 0; /* do we need to rekey? */ if (ssh_packet_need_rekeying(ssh, 0)) { debug3("%s: rekex triggered", __func__); if ((r = kex_start_rekex(ssh)) != 0) return r; } out: return r; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
0
19,572
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: update_stat(char *port, uint64_t traffic) { if (verbose) { LOGI("update traffic %" PRIu64 " for port %s", traffic, port); } void *ret = cork_hash_table_get(server_table, (void *)port); if (ret != NULL) { struct server *server = (struct server *)ret; server->traffic = traffic; } } Commit Message: Fix #1734 CWE ID: CWE-78
0
28,110
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void MetricsWebContentsObserver::NotifyPageEndAllLoadsWithTimestamp( PageEndReason page_end_reason, UserInitiatedInfo user_initiated_info, base::TimeTicks timestamp, bool is_certainly_browser_timestamp) { if (committed_load_) { committed_load_->NotifyPageEnd(page_end_reason, user_initiated_info, timestamp, is_certainly_browser_timestamp); } for (const auto& kv : provisional_loads_) { kv.second->NotifyPageEnd(page_end_reason, user_initiated_info, timestamp, is_certainly_browser_timestamp); } for (const auto& tracker : aborted_provisional_loads_) { if (tracker->IsLikelyProvisionalAbort(timestamp)) { tracker->UpdatePageEnd(page_end_reason, user_initiated_info, timestamp, is_certainly_browser_timestamp); } } aborted_provisional_loads_.clear(); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <sullivan@chromium.org> Reviewed-by: Bryan McQuade <bmcquade@chromium.org> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79
0
6,380
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event, bool line_status) { if (!irqchip_in_kernel(kvm)) return -ENXIO; irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID, irq_event->irq, irq_event->level, line_status); return 0; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <ahonig@google.com> Cc: stable@vger.kernel.org Signed-off-by: Andrew Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-20
0
17,570
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: DocumentState* Document::FormElementsState() const { if (!form_controller_) return 0; return form_controller_->FormElementsState(); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
0
4,087
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: error::Error GLES2DecoderImpl::HandleGetActiveUniformBlockiv( uint32_t immediate_data_size, const volatile void* cmd_data) { if (!feature_info_->IsWebGL2OrES3Context()) return error::kUnknownCommand; const volatile gles2::cmds::GetActiveUniformBlockiv& c = *static_cast<const volatile gles2::cmds::GetActiveUniformBlockiv*>( cmd_data); GLuint program_id = c.program; GLuint index = static_cast<GLuint>(c.index); GLenum pname = static_cast<GLenum>(c.pname); Program* program = GetProgramInfoNotShader( program_id, "glGetActiveUniformBlockiv"); if (!program) { return error::kNoError; } GLuint service_id = program->service_id(); GLint link_status = GL_FALSE; api()->glGetProgramivFn(service_id, GL_LINK_STATUS, &link_status); if (link_status != GL_TRUE) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glGetActiveActiveUniformBlockiv", "program not linked"); return error::kNoError; } if (index >= program->uniform_block_size_info().size()) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "glGetActiveUniformBlockiv", "uniformBlockIndex >= active uniform blocks"); return error::kNoError; } GLsizei num_values = 1; if (pname == GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES) { GLint num = 0; api()->glGetActiveUniformBlockivFn(service_id, index, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &num); GLenum error = api()->glGetErrorFn(); if (error != GL_NO_ERROR) { LOCAL_SET_GL_ERROR(error, "GetActiveUniformBlockiv", ""); return error::kNoError; } num_values = static_cast<GLsizei>(num); } typedef cmds::GetActiveUniformBlockiv::Result Result; uint32_t checked_size = 0; if (!Result::ComputeSize(num_values).AssignIfValid(&checked_size)) { return error::kOutOfBounds; } Result* result = GetSharedMemoryAs<Result*>( c.params_shm_id, c.params_shm_offset, checked_size); GLint* params = result ? result->GetData() : nullptr; if (params == nullptr) { return error::kOutOfBounds; } if (result->size != 0) { return error::kInvalidArguments; } api()->glGetActiveUniformBlockivFn(service_id, index, pname, params); result->SetNumResults(num_values); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
0
11,806
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: CopyCursorToImage(CursorPtr pCursor, CARD32 *image) { int width = pCursor->bits->width; int height = pCursor->bits->height; int npixels = width * height; if (pCursor->bits->argb) memcpy(image, pCursor->bits->argb, npixels * sizeof(CARD32)); else { unsigned char *srcLine = pCursor->bits->source; unsigned char *mskLine = pCursor->bits->mask; int stride = BitmapBytePad(width); int x, y; CARD32 fg, bg; fg = (0xff000000 | ((pCursor->foreRed & 0xff00) << 8) | (pCursor->foreGreen & 0xff00) | (pCursor->foreBlue >> 8)); bg = (0xff000000 | ((pCursor->backRed & 0xff00) << 8) | (pCursor->backGreen & 0xff00) | (pCursor->backBlue >> 8)); for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { if (GetBit(mskLine, x)) { if (GetBit(srcLine, x)) *image++ = fg; else *image++ = bg; } else *image++ = 0; } srcLine += stride; mskLine += stride; } } } Commit Message: CWE ID: CWE-20
0
6,894
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void seq_startplay(void) { int this_one, action; unsigned long flags; while (qlen > 0) { spin_lock_irqsave(&lock,flags); qhead = ((this_one = qhead) + 1) % SEQ_MAX_QUEUE; qlen--; spin_unlock_irqrestore(&lock,flags); seq_playing = 1; if ((action = play_event(&queue[this_one * EV_SZ]))) { /* Suspend playback. Next timer routine invokes this routine again */ if (action == 2) { qlen++; qhead = this_one; } return; } } seq_playing = 0; if ((SEQ_MAX_QUEUE - qlen) >= output_threshold) wake_up(&seq_sleeper); } Commit Message: sound/oss: remove offset from load_patch callbacks Was: [PATCH] sound/oss/midi_synth: prevent underflow, use of uninitialized value, and signedness issue The offset passed to midi_synth_load_patch() can be essentially arbitrary. If it's greater than the header length, this will result in a copy_from_user(dst, src, negative_val). While this will just return -EFAULT on x86, on other architectures this may cause memory corruption. Additionally, the length field of the sysex_info structure may not be initialized prior to its use. Finally, a signed comparison may result in an unintentionally large loop. On suggestion by Takashi Iwai, version two removes the offset argument from the load_patch callbacks entirely, which also resolves similar issues in opl3. Compile tested only. v3 adjusts comments and hopefully gets copy offsets right. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-189
0
29,412
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl) { return evdns_server_request_add_reply( req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET, ttl, -1, 1, cname); } Commit Message: evdns: fix searching empty hostnames From #332: Here follows a bug report by **Guido Vranken** via the _Tor bug bounty program_. Please credit Guido accordingly. ## Bug report The DNS code of Libevent contains this rather obvious OOB read: ```c static char * search_make_new(const struct search_state *const state, int n, const char *const base_name) { const size_t base_len = strlen(base_name); const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; ``` If the length of ```base_name``` is 0, then line 3125 reads 1 byte before the buffer. This will trigger a crash on ASAN-protected builds. To reproduce: Build libevent with ASAN: ``` $ CFLAGS='-fomit-frame-pointer -fsanitize=address' ./configure && make -j4 ``` Put the attached ```resolv.conf``` and ```poc.c``` in the source directory and then do: ``` $ gcc -fsanitize=address -fomit-frame-pointer poc.c .libs/libevent.a $ ./a.out ================================================================= ==22201== ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60060000efdf at pc 0x4429da bp 0x7ffe1ed47300 sp 0x7ffe1ed472f8 READ of size 1 at 0x60060000efdf thread T0 ``` P.S. we can add a check earlier, but since this is very uncommon, I didn't add it. Fixes: #332 CWE ID: CWE-125
0
15,410
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int udf_setsize(struct inode *inode, loff_t newsize) { int err; struct udf_inode_info *iinfo; int bsize = 1 << inode->i_blkbits; if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))) return -EINVAL; if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; iinfo = UDF_I(inode); if (newsize > inode->i_size) { down_write(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { if (bsize < (udf_file_entry_alloc_offset(inode) + newsize)) { err = udf_expand_file_adinicb(inode); if (err) return err; down_write(&iinfo->i_data_sem); } else { iinfo->i_lenAlloc = newsize; goto set_size; } } err = udf_extend_file(inode, newsize); if (err) { up_write(&iinfo->i_data_sem); return err; } set_size: truncate_setsize(inode, newsize); up_write(&iinfo->i_data_sem); } else { if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); memset(iinfo->i_ext.i_data + iinfo->i_lenEAttr + newsize, 0x00, bsize - newsize - udf_file_entry_alloc_offset(inode)); iinfo->i_lenAlloc = newsize; truncate_setsize(inode, newsize); up_write(&iinfo->i_data_sem); goto update_time; } err = block_truncate_page(inode->i_mapping, newsize, udf_get_block); if (err) return err; down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); truncate_setsize(inode, newsize); udf_truncate_extents(inode); up_write(&iinfo->i_data_sem); } update_time: inode->i_mtime = inode->i_ctime = current_fs_time(inode->i_sb); if (IS_SYNC(inode)) udf_sync_inode(inode); else mark_inode_dirty(inode); return 0; } Commit Message: udf: Avoid infinite loop when processing indirect ICBs We did not implement any bound on number of indirect ICBs we follow when loading inode. Thus corrupted medium could cause kernel to go into an infinite loop, possibly causing a stack overflow. Fix the possible stack overflow by removing recursion from __udf_read_inode() and limit number of indirect ICBs we follow to avoid infinite loops. Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-399
0
5,149
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int lz4_decompress_unknownoutputsize(const unsigned char *src, size_t src_len, unsigned char *dest, size_t *dest_len) { int ret = -1; int out_len = 0; out_len = lz4_uncompress_unknownoutputsize(src, dest, src_len, *dest_len); if (out_len < 0) goto exit_0; *dest_len = out_len; return 0; exit_0: return ret; } Commit Message: lz4: ensure length does not wrap Given some pathologically compressed data, lz4 could possibly decide to wrap a few internal variables, causing unknown things to happen. Catch this before the wrapping happens and abort the decompression. Reported-by: "Don A. Bailey" <donb@securitymouse.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-20
0
4,375
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: query_fs_type (GFile *file, GCancellable *cancellable) { GFileInfo *fsinfo; char *ret; ret = NULL; fsinfo = g_file_query_filesystem_info (file, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, cancellable, NULL); if (fsinfo != NULL) { ret = g_strdup (g_file_info_get_attribute_string (fsinfo, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE)); g_object_unref (fsinfo); } if (ret == NULL) { /* ensure that we don't attempt to query * the FS type for each file in a given * directory, if it can't be queried. */ ret = g_strdup (""); } return ret; } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
0
8,823
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void Ins_PUSHB( INS_ARG ) { Int L, K; L = ((Int)CUR.opcode - 0xB0 + 1); if ( BOUNDS( L, CUR.stackSize+1-CUR.top ) ) { CUR.error = TT_Err_Stack_Overflow; return; } for ( K = 1; K <= L; K++ ) { args[K - 1] = CUR.code[CUR.IP + K]; DBG_PRINT1(" %d", args[K - 1]); } } Commit Message: CWE ID: CWE-125
0
7,935
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
0
15,762
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void ipa_region_paint(wmfAPI * API, wmfPolyRectangle_t * poly_rect) { if (poly_rect->count == 0) return; /* Save graphic wand */ (void) PushDrawingWand(WmfDrawingWand); if (TO_FILL (poly_rect)) { long i; draw_stroke_color_string(WmfDrawingWand,"none"); util_set_brush(API, poly_rect->dc, BrushApplyFill); for (i = 0; i < (long) poly_rect->count; i++) { DrawRectangle(WmfDrawingWand, XC(poly_rect->TL[i].x), YC(poly_rect->TL[i].y), XC(poly_rect->BR[i].x), YC(poly_rect->BR[i].y)); } } /* Restore graphic wand */ (void) PopDrawingWand(WmfDrawingWand); } Commit Message: CWE ID: CWE-119
0
17,370
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void set_texcoords_in_vertices(const float coord[4], float *out, unsigned stride) { out[0] = coord[0]; /*t0.s*/ out[1] = coord[1]; /*t0.t*/ out += stride; out[0] = coord[2]; /*t1.s*/ out[1] = coord[1]; /*t1.t*/ out += stride; out[0] = coord[2]; /*t2.s*/ out[1] = coord[3]; /*t2.t*/ out += stride; out[0] = coord[0]; /*t3.s*/ out[1] = coord[3]; /*t3.t*/ } Commit Message: CWE ID: CWE-772
0
1,534
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: std::string GetUploadData(const std::string& brand) { DCHECK(!brand.empty()); std::string data(kPostXml); const std::string placeholder("__BRANDCODE_PLACEHOLDER__"); size_t placeholder_pos = data.find(placeholder); DCHECK(placeholder_pos != std::string::npos); data.replace(placeholder_pos, placeholder.size(), brand); return data; } Commit Message: Use install_static::GetAppGuid instead of the hardcoded string in BrandcodeConfigFetcher. Bug: 769756 Change-Id: Ifdcb0a5145ffad1d563562e2b2ea2390ff074cdc Reviewed-on: https://chromium-review.googlesource.com/1213178 Reviewed-by: Dominic Battré <battre@chromium.org> Commit-Queue: Vasilii Sukhanov <vasilii@chromium.org> Cr-Commit-Position: refs/heads/master@{#590275} CWE ID: CWE-79
1
19,313
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void CompositorImpl::SetBackgroundColor(int color) { DCHECK(host_); host_->set_background_color(color); } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. R=piman@chromium.org Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <khushalsagar@chromium.org> Commit-Queue: Antoine Labour <piman@chromium.org> Reviewed-by: Antoine Labour <piman@chromium.org> Auto-Submit: Khushal <khushalsagar@chromium.org> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID:
0
18,168
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool HasEnvironmentVariable16(const std::wstring& variable_name) { return !!::GetEnvironmentVariable(variable_name.c_str(), nullptr, 0); } Commit Message: Ignore switches following "--" when parsing a command line. BUG=933004 R=wfh@chromium.org Change-Id: I911be4cbfc38a4d41dec85d85f7fe0f50ddca392 Reviewed-on: https://chromium-review.googlesource.com/c/1481210 Auto-Submit: Greg Thompson <grt@chromium.org> Commit-Queue: Julian Pastarmov <pastarmovj@chromium.org> Reviewed-by: Julian Pastarmov <pastarmovj@chromium.org> Cr-Commit-Position: refs/heads/master@{#634604} CWE ID: CWE-77
0
3,253
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const { if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode()) return containingBlockLogicalHeightForPositioned(containingBlock, false); if (style()->position() == FixedPosition && containingBlock->isRenderView()) { const RenderView* view = toRenderView(containingBlock); if (FrameView* frameView = view->frameView()) { LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect(); return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height(); } } if (containingBlock->isBox()) return toRenderBox(containingBlock)->clientLogicalWidth(); ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned()); const RenderInline* flow = toRenderInline(containingBlock); InlineFlowBox* first = flow->firstLineBox(); InlineFlowBox* last = flow->lastLineBox(); if (!first || !last) return 0; LayoutUnit fromLeft; LayoutUnit fromRight; if (containingBlock->style()->isLeftToRightDirection()) { fromLeft = first->logicalLeft() + first->borderLogicalLeft(); fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight(); } else { fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight(); fromLeft = last->logicalLeft() + last->borderLogicalLeft(); } return max<LayoutUnit>(0, fromRight - fromLeft); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. R=eseidel@chromium.org, esprehn@chromium.org, jchaffraix@chromium.org Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
5,334
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void fpm_child_free(struct fpm_child_s *child) /* {{{ */ { free(child); } /* }}} */ Commit Message: Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that. CWE ID: CWE-400
0
2,083
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: handle_atim(void) { /* the frame body for ATIM is null. */ return 1; } Commit Message: CVE-2017-13008/IEEE 802.11: Fix TIM bitmap copy to copy from p + offset. offset has already been advanced to point to the bitmap; we shouldn't add the amount to advance again. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). While we're at it, remove some redundant tests - we've already checked, before the case statement, whether we have captured the entire information element and whether the entire information element is present in the on-the-wire packet; in the cases for particular IEs, we only need to make sure we don't go past the end of the IE. CWE ID: CWE-125
0
4,854
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GF_Box *unkn_New() { ISOM_DECL_BOX_ALLOC(GF_UnknownBox, GF_ISOM_BOX_TYPE_UNKNOWN); return (GF_Box *) tmp; } Commit Message: prevent dref memleak on invalid input (#1183) CWE ID: CWE-400
0
13,525
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int param_set_audit(const char *val, struct kernel_param *kp) { int i; if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (!apparmor_enabled) return -EINVAL; if (!val) return -EINVAL; for (i = 0; i < AUDIT_MAX_INDEX; i++) { if (strcmp(val, audit_mode_names[i]) == 0) { aa_g_audit = i; return 0; } } return -EINVAL; } Commit Message: AppArmor: fix oops in apparmor_setprocattr When invalid parameters are passed to apparmor_setprocattr a NULL deref oops occurs when it tries to record an audit message. This is because it is passing NULL for the profile parameter for aa_audit. But aa_audit now requires that the profile passed is not NULL. Fix this by passing the current profile on the task that is trying to setprocattr. Signed-off-by: Kees Cook <kees@ubuntu.com> Signed-off-by: John Johansen <john.johansen@canonical.com> Cc: stable@kernel.org Signed-off-by: James Morris <jmorris@namei.org> CWE ID: CWE-20
0
12,491
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Ins_SRP2( INS_ARG ) { DO_SRP2 } Commit Message: CWE ID: CWE-119
0
3,310
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack) { addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack); } Commit Message: Unreviewed, rolling out r147402. http://trac.webkit.org/changeset/147402 https://bugs.webkit.org/show_bug.cgi?id=112903 Source/WebCore: * dom/Document.cpp: (WebCore::Document::processHttpEquiv): * loader/DocumentLoader.cpp: (WebCore::DocumentLoader::responseReceived): LayoutTests: * http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html: * http/tests/security/XFrameOptions/x-frame-options-deny.html: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
13,910
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int touch_released_count() const { return touch_released_count_; } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
18,465
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ProcLookupColor(ClientPtr client) { ColormapPtr pcmp; int rc; REQUEST(xLookupColorReq); REQUEST_FIXED_SIZE(xLookupColorReq, stuff->nbytes); rc = dixLookupResourceByType((void **) &pcmp, stuff->cmap, RT_COLORMAP, client, DixReadAccess); if (rc == Success) { CARD16 exactRed, exactGreen, exactBlue; if (OsLookupColor (pcmp->pScreen->myNum, (char *) &stuff[1], stuff->nbytes, &exactRed, &exactGreen, &exactBlue)) { xLookupColorReply lcr = { .type = X_Reply, .sequenceNumber = client->sequence, .length = 0, .exactRed = exactRed, .exactGreen = exactGreen, .exactBlue = exactBlue, .screenRed = exactRed, .screenGreen = exactGreen, .screenBlue = exactBlue }; (*pcmp->pScreen->ResolveColor) (&lcr.screenRed, &lcr.screenGreen, &lcr.screenBlue, pcmp->pVisual); WriteReplyToClient(client, sizeof(xLookupColorReply), &lcr); return Success; } return BadName; } else { client->errorValue = stuff->cmap; return rc; } } Commit Message: CWE ID: CWE-369
0
7,179
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RootWindow::Draw() { if (waiting_on_compositing_end_) { draw_on_compositing_end_ = true; defer_draw_scheduling_ = false; return; } if (compositor_lock_) { draw_on_compositor_unlock_ = true; defer_draw_scheduling_ = false; return; } waiting_on_compositing_end_ = true; TRACE_EVENT_ASYNC_BEGIN0("ui", "RootWindow::Draw", draw_trace_count_++); compositor_->Draw(false); defer_draw_scheduling_ = false; } Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS. BUG=119492 TEST=manually done Review URL: https://chromiumcodereview.appspot.com/10386124 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
23,053
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: server_close_pipe (int *pipefd) /* see comments below */ { close (pipefd[0]); /* close WRITE end first to cause an EOF on READ */ close (pipefd[1]); /* in giowin32, and end that thread. */ free (pipefd); return FALSE; } Commit Message: ssl: Validate hostnames Closes #524 CWE ID: CWE-310
0
6,686
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static Image *ReadPCDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickOffsetType offset; MagickSizeType number_pixels; register ssize_t i, y; register PixelPacket *q; register unsigned char *c1, *c2, *yy; size_t height, number_images, rotate, scene, width; ssize_t count, x; unsigned char *chroma1, *chroma2, *header, *luma; unsigned int overview; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCD file. */ header=(unsigned char *) AcquireQuantumMemory(0x800,3UL*sizeof(*header)); if (header == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,3*0x800,header); overview=LocaleNCompare((char *) header,"PCD_OPA",7) == 0; if ((count == 0) || ((LocaleNCompare((char *) header+0x800,"PCD",3) != 0) && (overview == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); rotate=header[0x0e02] & 0x03; number_images=(header[10] << 8) | header[11]; if (number_images > 65535) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); header=(unsigned char *) RelinquishMagickMemory(header); /* Determine resolution by scene specification. */ if ((image->columns == 0) || (image->rows == 0)) scene=3; else { width=192; height=128; for (scene=1; scene < 6; scene++) { if ((width >= image->columns) && (height >= image->rows)) break; width<<=1; height<<=1; } } if (image_info->number_scenes != 0) scene=(size_t) MagickMin(image_info->scene,6); if (overview != 0) scene=1; /* Initialize image structure. */ width=192; height=128; for (i=1; i < (ssize_t) MagickMin(scene,3); i++) { width<<=1; height<<=1; } image->columns=width; image->rows=height; image->depth=8; for ( ; i < (ssize_t) scene; i++) { image->columns<<=1; image->rows<<=1; } /* Allocate luma and chroma memory. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); chroma1=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma1)); chroma2=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma2)); luma=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*luma)); if ((chroma1 == (unsigned char *) NULL) || (chroma2 == (unsigned char *) NULL) || (luma == (unsigned char *) NULL)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Advance to image data. */ offset=93; if (overview != 0) offset=2; else if (scene == 2) offset=20; else if (scene <= 1) offset=1; for (i=0; i < (ssize_t) (offset*0x800); i++) (void) ReadBlobByte(image); if (overview != 0) { Image *overview_image; MagickProgressMonitor progress_monitor; register ssize_t j; /* Read thumbnails from overview image. */ for (j=1; j <= (ssize_t) number_images; j++) { progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) FormatLocaleString(image->filename,MaxTextExtent, "images/img%04ld.pcd",(long) j); (void) FormatLocaleString(image->magick_filename,MaxTextExtent, "images/img%04ld.pcd",(long) j); image->scene=(size_t) j; image->columns=width; image->rows=height; image->depth=8; yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,"PCDS") == 0) SetImageColorspace(image,sRGBColorspace); if (j < (ssize_t) number_images) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,j-1,number_images); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); image=GetFirstImageInList(image); overview_image=OverviewImage(image_info,image,exception); return(overview_image); } /* Read interleaved image. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } if (scene >= 4) { /* Recover luminance deltas for 1536x1024 image. */ Upsample(768,512,image->columns,luma); Upsample(384,256,image->columns,chroma1); Upsample(384,256,image->columns,chroma2); image->rows=1024; for (i=0; i < (4*0x800); i++) (void) ReadBlobByte(image); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 5) && status) { /* Recover luminance deltas for 3072x2048 image. */ Upsample(1536,1024,image->columns,luma); Upsample(768,512,image->columns,chroma1); Upsample(768,512,image->columns,chroma2); image->rows=2048; offset=TellBlob(image)/0x800+12; offset=SeekBlob(image,offset*0x800,SEEK_SET); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 6) && (status != MagickFalse)) { /* Recover luminance deltas for 6144x4096 image (vaporware). */ Upsample(3072,2048,image->columns,luma); Upsample(1536,1024,image->columns,chroma1); Upsample(1536,1024,image->columns,chroma2); image->rows=4096; } } } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); if (image_info->ping == MagickFalse) if ((rotate == 1) || (rotate == 3)) { double degrees; Image *rotate_image; /* Rotate image. */ degrees=rotate == 1 ? -90.0 : 90.0; rotate_image=RotateImage(image,degrees,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } } /* Set CCIR 709 primaries with a D65 white point. */ image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->gamma=1.000f/2.200f; image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,"PCDS") == 0) SetImageColorspace(image,sRGBColorspace); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
1
7,617
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) { idle_notification_delay_in_ms_ = initial_delay_ms; idle_timer_.Stop(); idle_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(initial_delay_ms), this, &RenderThreadImpl::IdleHandler); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
19,620
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Dispatcher::AddShutdown(const std::string& pattern, base::WaitableEvent* shutdown_event) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &Shutdown, shutdown_event); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
24,594
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void hci_uart_tty_wakeup(struct tty_struct *tty) { struct hci_uart *hu = tty->disc_data; BT_DBG(""); if (!hu) return; clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); if (tty != hu->tty) return; if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) hci_uart_tx_wakeup(hu); } Commit Message: Bluetooth: hci_ldisc: Postpone HCI_UART_PROTO_READY bit set in hci_uart_set_proto() task A: task B: hci_uart_set_proto flush_to_ldisc - p->open(hu) -> h5_open //alloc h5 - receive_buf - set_bit HCI_UART_PROTO_READY - tty_port_default_receive_buf - hci_uart_register_dev - tty_ldisc_receive_buf - hci_uart_tty_receive - test_bit HCI_UART_PROTO_READY - h5_recv - clear_bit HCI_UART_PROTO_READY while() { - p->open(hu) -> h5_close //free h5 - h5_rx_3wire_hdr - h5_reset() //use-after-free } It could use ioctl to set hci uart proto, but there is a use-after-free issue when hci_uart_register_dev() fail in hci_uart_set_proto(), see stack above, fix this by setting HCI_UART_PROTO_READY bit only when hci_uart_register_dev() return success. Reported-by: syzbot+899a33dc0fa0dbaf06a6@syzkaller.appspotmail.com Signed-off-by: Kefeng Wang <wangkefeng.wang@huawei.com> Reviewed-by: Jeremy Cline <jcline@redhat.com> Signed-off-by: Marcel Holtmann <marcel@holtmann.org> CWE ID: CWE-416
0
9,007
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ExtensionService::SetBrowserActionVisibility(const Extension* extension, bool visible) { extension_prefs_->SetBrowserActionVisibility(extension, visible); } Commit Message: Limit extent of webstore app to just chrome.google.com/webstore. BUG=93497 TEST=Try installing extensions and apps from the webstore, starting both being initially logged in, and not. Review URL: http://codereview.chromium.org/7719003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
8,147
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: cmsBool Type_vcgt_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsToneCurve** Curves = (cmsToneCurve**) Ptr; cmsUInt32Number i, j; if (cmsGetToneCurveParametricType(Curves[0]) == 5 && cmsGetToneCurveParametricType(Curves[1]) == 5 && cmsGetToneCurveParametricType(Curves[2]) == 5) { if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaFormulaType)) return FALSE; for (i=0; i < 3; i++) { _cmsVCGTGAMMA v; v.Gamma = Curves[i] ->Segments[0].Params[0]; v.Min = Curves[i] ->Segments[0].Params[5]; v.Max = pow(Curves[i] ->Segments[0].Params[1], v.Gamma) + v.Min; if (!_cmsWrite15Fixed16Number(io, v.Gamma)) return FALSE; if (!_cmsWrite15Fixed16Number(io, v.Min)) return FALSE; if (!_cmsWrite15Fixed16Number(io, v.Max)) return FALSE; } } else { if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaTableType)) return FALSE; if (!_cmsWriteUInt16Number(io, 3)) return FALSE; if (!_cmsWriteUInt16Number(io, 256)) return FALSE; if (!_cmsWriteUInt16Number(io, 2)) return FALSE; for (i=0; i < 3; i++) { for (j=0; j < 256; j++) { cmsFloat32Number v = cmsEvalToneCurveFloat(Curves[i], (cmsFloat32Number) (j / 255.0)); cmsUInt16Number n = _cmsQuickSaturateWord(v * 65535.0); if (!_cmsWriteUInt16Number(io, n)) return FALSE; } } } return TRUE; cmsUNUSED_PARAMETER(self); cmsUNUSED_PARAMETER(nItems); } Commit Message: Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug CWE ID: CWE-125
0
25,417
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: BrowserWindowGtk* BrowserWindowGtk::GetBrowserWindowForNativeWindow( gfx::NativeWindow window) { if (window) { return static_cast<BrowserWindowGtk*>( g_object_get_qdata(G_OBJECT(window), GetBrowserWindowQuarkKey())); } return NULL; } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
12,221
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void ext2_xattr_update_super_block(struct super_block *sb) { if (EXT2_HAS_COMPAT_FEATURE(sb, EXT2_FEATURE_COMPAT_EXT_ATTR)) return; spin_lock(&EXT2_SB(sb)->s_lock); EXT2_SET_COMPAT_FEATURE(sb, EXT2_FEATURE_COMPAT_EXT_ATTR); spin_unlock(&EXT2_SB(sb)->s_lock); mark_buffer_dirty(EXT2_SB(sb)->s_sbh); } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
0
29,623
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: RenderFrameHostImpl::~RenderFrameHostImpl() { ResetChildren(); ResetNavigationRequests(); ClearAllWebUI(); SetLastCommittedSiteUrl(GURL()); if (overlay_routing_token_) g_token_frame_map.Get().erase(*overlay_routing_token_); site_instance_->RemoveObserver(this); if (delegate_ && render_frame_created_) delegate_->RenderFrameDeleted(this); OnAudibleStateChanged(false); GetSiteInstance()->DecrementActiveFrameCount(); if (render_frame_created_ && render_view_host_->GetMainFrame() != this) CHECK(!is_active()); GetProcess()->RemoveRoute(routing_id_); g_routing_id_frame_map.Get().erase( RenderFrameHostID(GetProcess()->GetID(), routing_id_)); swapout_event_monitor_timeout_.reset(); for (auto& iter : visual_state_callbacks_) std::move(iter.second).Run(false); if (render_widget_host_ && render_widget_host_->owned_by_render_frame_host()) { render_widget_host_->ShutdownAndDestroyWidget(true); } frame_tree_->ReleaseRenderViewHostRef(render_view_host_); RenderFrameHostImpl* beforeunload_initiator = GetBeforeUnloadInitiator(); if (beforeunload_initiator && beforeunload_initiator != this) { base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_; beforeunload_initiator->ProcessBeforeUnloadACKFromFrame( true /* proceed */, false /* treat_as_final_ack */, this, true /* is_frame_being_destroyed */, approx_renderer_start_time, base::TimeTicks::Now()); } } Commit Message: Fix a crash on FileChooserImpl If a renderer process is compromised, and it calls both of FileChooserImpl::OpenFileChooser() and EnumerateChosenDirectory() via Mojo, the browser process could crash because ResetOwner() for the first FileChooserImpl::proxy_ instance was not called. We should check nullness of proxy_ before updating it. Bug: 941008 Change-Id: Ie0c1895ec46ce78d40594b543e49e43b420af675 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1520509 Reviewed-by: Avi Drissman <avi@chromium.org> Commit-Queue: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#640580} CWE ID: CWE-416
0
4,910
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: R_API int r_bin_file_object_add(RBinFile *binfile, RBinObject *o) { if (!o) { return false; } r_list_append (binfile->objs, o); r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, o); return true; } Commit Message: Fix #9902 - Fix oobread in RBin.string_scan_range CWE ID: CWE-125
0
26,946
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GF_Err sdp_Read(GF_Box *s, GF_BitStream *bs) { u32 length; GF_SDPBox *ptr = (GF_SDPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; length = (u32) (ptr->size); ptr->sdpText = (char*)gf_malloc(sizeof(char) * (length+1)); if (!ptr->sdpText) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->sdpText, length); ptr->sdpText[length] = 0; return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
0
2,831
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void xdelCommand(client *c) { robj *o; if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || checkType(c,o,OBJ_STREAM)) return; stream *s = o->ptr; /* We need to sanity check the IDs passed to start. Even if not * a big issue, it is not great that the command is only partially * executed becuase at some point an invalid ID is parsed. */ streamID id; for (int j = 2; j < c->argc; j++) { if (streamParseIDOrReply(c,c->argv[j],&id,0) != C_OK) return; } /* Actaully apply the command. */ int deleted = 0; for (int j = 2; j < c->argc; j++) { streamParseIDOrReply(c,c->argv[j],&id,0); /* Retval already checked. */ deleted += streamDeleteItem(s,&id); } signalModifiedKey(c->db,c->argv[1]); notifyKeyspaceEvent(NOTIFY_STREAM,"xdel",c->argv[1],c->db->id); server.dirty += deleted; addReplyLongLong(c,deleted); } Commit Message: Abort in XGROUP if the key is not a stream CWE ID: CWE-704
0
25,929
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gpc_lin(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilinear(in->r); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilinear(in->b); } else { out->g = ilinear(in->g); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilinear(in->b); } out->a = 65535; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
0
15,011
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct segment *new_init_section(struct playlist *pls, struct init_section_info *info, const char *url_base) { struct segment *sec; char *ptr; char tmp_str[MAX_URL_SIZE]; if (!info->uri[0]) return NULL; sec = av_mallocz(sizeof(*sec)); if (!sec) return NULL; ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri); sec->url = av_strdup(tmp_str); if (!sec->url) { av_free(sec); return NULL; } if (info->byterange[0]) { sec->size = strtoll(info->byterange, NULL, 10); ptr = strchr(info->byterange, '@'); if (ptr) sec->url_offset = strtoll(ptr+1, NULL, 10); } else { /* the entire file is the init section */ sec->size = -1; } dynarray_add(&pls->init_sections, &pls->n_init_sections, sec); return sec; } Commit Message: avformat/hls: Fix DoS due to infinite loop Fixes: loop.m3u The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome Found-by: Xiaohei and Wangchu from Alibaba Security Team Previous version reviewed-by: Steven Liu <lingjiujianke@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-835
0
2,595
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool SyncTest::WaitForTestServerToStart(int time_ms, int intervals) { for (int i = 0; i < intervals; ++i) { if (IsTestServerRunning()) return true; base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds( time_ms / intervals)); } return false; } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
0
811
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static size_t nfs4_xattr_list_nfs4_acl(struct dentry *dentry, char *list, size_t list_len, const char *name, size_t name_len, int type) { size_t len = sizeof(XATTR_NAME_NFSV4_ACL); if (!nfs4_server_supports_acls(NFS_SERVER(dentry->d_inode))) return 0; if (list && len <= list_len) memcpy(list, XATTR_NAME_NFSV4_ACL, len); return len; } Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached _copy_from_pages() used to copy data from the temporary buffer to the user passed buffer is passed the wrong size parameter when copying data. res.acl_len contains both the bitmap and acl lenghts while acl_len contains the acl length after adjusting for the bitmap size. Signed-off-by: Sachin Prabhu <sprabhu@redhat.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
0
4,039
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ZEND_GET_MODULE(radius) #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(radius) { le_radius = zend_register_list_destructors_ex(_radius_close, NULL, "rad_handle", module_number); #include "radius_init_const.h" REGISTER_LONG_CONSTANT("RADIUS_MPPE_KEY_LEN", MPPE_KEY_LEN, CONST_PERSISTENT); return SUCCESS; } /* }}} */ Commit Message: Fix a security issue in radius_get_vendor_attr(). The underlying rad_get_vendor_attr() function assumed that it would always be given valid VSA data. Indeed, the buffer length wasn't even passed in; the assumption was that the length field within the VSA structure would be valid. This could result in denial of service by providing a length that would be beyond the memory limit, or potential arbitrary memory access by providing a length greater than the actual data given. rad_get_vendor_attr() has been changed to require the raw data length be provided, and this is then used to check that the VSA is valid. Conflicts: radlib_vs.h CWE ID: CWE-119
0
20,385
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: scoped_ptr<AppCacheHost> AppCacheBackendImpl::TransferHostOut(int host_id) { HostMap::iterator found = hosts_.find(host_id); if (found == hosts_.end()) { NOTREACHED(); return scoped_ptr<AppCacheHost>(); } AppCacheHost* transferree = found->second; found->second = new AppCacheHost(host_id, frontend_, service_); transferree->PrepareForTransfer(); return scoped_ptr<AppCacheHost>(transferree); } 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:
0
22,796
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ExtensionService* TestExtensionSystem::CreateExtensionService( const CommandLine* command_line, const FilePath& install_directory, bool autoupdate_enabled) { bool extensions_disabled = command_line && command_line->HasSwitch(switches::kDisableExtensions); extension_prefs_ = ExtensionPrefs::Create( profile_->GetPrefs(), install_directory, ExtensionPrefValueMapFactory::GetForProfile(profile_), extensions_disabled); state_store_.reset(new StateStore(profile_, new TestingValueStore())); shell_window_geometry_cache_.reset( new ShellWindowGeometryCache(profile_, extension_prefs_.get())); blacklist_.reset(new Blacklist(extension_prefs_.get())); standard_management_policy_provider_.reset( new StandardManagementPolicyProvider(extension_prefs_.get())); management_policy_.reset(new ManagementPolicy()); management_policy_->RegisterProvider( standard_management_policy_provider_.get()); extension_service_.reset(new ExtensionService(profile_, command_line, install_directory, extension_prefs_.get(), blacklist_.get(), autoupdate_enabled, true)); extension_service_->ClearProvidersForTesting(); return extension_service_.get(); } Commit Message: Check prefs before allowing extension file access in the permissions API. R=mpcomplete@chromium.org BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
28,111
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void Process_ipfix_option_templates(exporter_ipfix_domain_t *exporter, void *option_template_flowset, FlowSource_t *fs) { uint8_t *DataPtr; uint32_t size_left, size_required, i; uint16_t id, field_count, scope_field_count, offset; uint16_t offset_std_sampler_interval, offset_std_sampler_algorithm, found_std_sampling; i = 0; // keep compiler happy size_left = GET_FLOWSET_LENGTH(option_template_flowset) - 4; // -4 for flowset header -> id and length if ( size_left < 6 ) { LogError("Process_ipfix: [%u] option template length error: size left %u too small for an options template", exporter->info.id, size_left); return; } DataPtr = option_template_flowset + 4; id = GET_OPTION_TEMPLATE_ID(DataPtr); field_count = GET_OPTION_TEMPLATE_FIELD_COUNT(DataPtr); scope_field_count = GET_OPTION_TEMPLATE_SCOPE_FIELD_COUNT(DataPtr); DataPtr += 6; size_left -= 6; dbg_printf("Decode Option Template. id: %u, field count: %u, scope field count: %u\n", id, field_count, scope_field_count); if ( scope_field_count == 0 ) { LogError("Process_ipfx: [%u] scope field count error: length must not be zero", exporter->info.id); dbg_printf("scope field count error: length must not be zero\n"); return; } size_required = 2 * field_count * sizeof(uint16_t); dbg_printf("Size left: %u, size required: %u\n", size_left, size_required); if ( size_left < size_required ) { LogError("Process_ipfix: [%u] option template length error: size left %u too small for %u scopes length and %u options length", exporter->info.id, size_left, field_count, scope_field_count); dbg_printf("option template length error: size left %u too small for field_count %u\n", size_left, field_count); return; } if ( scope_field_count == 0 ) { LogError("Process_ipfxi: [%u] scope field count error: length must not be zero", exporter->info.id); return; } offset_std_sampler_interval = 0; offset_std_sampler_algorithm = 0; found_std_sampling = 0; offset = 0; for ( i=0; i<scope_field_count; i++ ) { uint16_t id, length; int Enterprise; if ( size_left && size_left < 4 ) { LogError("Process_ipfix [%u] Template size error at %s line %u" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); return; } id = Get_val16(DataPtr); DataPtr += 2; length = Get_val16(DataPtr); DataPtr += 2; size_left -= 4; Enterprise = id & 0x8000 ? 1 : 0; if ( Enterprise ) { size_required += 4; if ( size_left < 4 ) { LogError("Process_ipfix: [%u] option template length error: size left %u too small", exporter->info.id, size_left); dbg_printf("option template length error: size left %u too small\n", size_left); return; } DataPtr += 4; size_left -= 4; dbg_printf(" [%i] Enterprise: 1, scope id: %u, scope length %u enterprise value: %u\n", i, id, length, Get_val32(DataPtr)); } else { dbg_printf(" [%i] Enterprise: 0, scope id: %u, scope length %u\n", i, id, length); } offset += length; } for ( ;i<field_count; i++ ) { uint32_t enterprise_value; uint16_t id, length; int Enterprise; UNUSED(enterprise_value); id = Get_val16(DataPtr); DataPtr += 2; length = Get_val16(DataPtr); DataPtr += 2; size_left -= 4; Enterprise = id & 0x8000 ? 1 : 0; if ( Enterprise ) { size_required += 4; if ( size_left < 4 ) { LogError("Process_ipfix: [%u] option template length error: size left %u too", exporter->info.id, size_left); dbg_printf("option template length error: size left %u too small\n", size_left); return; } enterprise_value = Get_val32(DataPtr); DataPtr += 4; size_left -= 4; dbg_printf(" [%i] Enterprise: 1, option id: %u, option length %u enterprise value: %u\n", i, id, length, enterprise_value); } else { dbg_printf(" [%i] Enterprise: 0, option id: %u, option length %u\n", i, id, length); } switch (id) { case IPFIX_samplingInterval: // legacy #34 case IPFIX_samplingPacketInterval: // #305 if ( length == 4 ) { offset_std_sampler_interval = offset; found_std_sampling++; dbg_printf(" 4 byte sampling interval option at offset: %u\n", offset); } else { LogError("Process_ipfix: [%u] option template error: sampling option lenth != 4 bytes: %u", exporter->info.id, length); } break; case IPFIX_samplingAlgorithm: // legacy #35 case IPFIX_selectorAlgorithm: // #304 if ( length == 1 ) { offset_std_sampler_algorithm = offset; dbg_printf(" 1 byte sampling algorithm option at offset: %u\n", offset); found_std_sampling++; } else { LogError("Process_ipfix: [%u] option template error: algorithm option lenth != 1 byte: %u", exporter->info.id, length); } break; } offset += length; } if ( offset_std_sampler_interval ) { dbg_printf("[%u] Std sampling interval found. offset: %u\n", exporter->info.id, offset_std_sampler_interval); if ( offset_std_sampler_algorithm ) dbg_printf("[%u] Std sampling algorithm found. offset: %u\n", exporter->info.id, offset_std_sampler_algorithm); InsertStdSamplerOffset(fs, id, offset_std_sampler_interval, offset_std_sampler_algorithm); dbg_printf("\n"); } processed_records++; } // End of Process_ipfix_option_templates Commit Message: Fix potential unsigned integer underflow CWE ID: CWE-190
0
28,362
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BrowserWindowGtk::Cut() { gtk_window_util::DoCut( window_, chrome::GetActiveWebContents(browser_.get())); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
22,724
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { if (p->flags & PKT_NOPACKET_INSPECTION) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } SCLogDebug("p->pcap %"PRIu64": no detection on packet, " "PKT_NOPACKET_INSPECTION is set", p->pcap_cnt); return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); } Commit Message: stream: fix false negative on bad RST If a bad RST was received the stream inspection would not happen for that packet, but it would still move the 'raw progress' tracker forward. Following good packets would then fail to detect anything before the 'raw progress' position. Bug #2770 Reported-by: Alexey Vishnyakov CWE ID: CWE-347
0
26,195
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
0
4,211
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct crypto_instance *crypto_gcm_base_alloc(struct rtattr **tb) { const char *ctr_name; const char *ghash_name; char full_name[CRYPTO_MAX_ALG_NAME]; ctr_name = crypto_attr_alg_name(tb[1]); if (IS_ERR(ctr_name)) return ERR_CAST(ctr_name); ghash_name = crypto_attr_alg_name(tb[2]); if (IS_ERR(ghash_name)) return ERR_CAST(ghash_name); if (snprintf(full_name, CRYPTO_MAX_ALG_NAME, "gcm_base(%s,%s)", ctr_name, ghash_name) >= CRYPTO_MAX_ALG_NAME) return ERR_PTR(-ENAMETOOLONG); return crypto_gcm_alloc_common(tb, full_name, ctr_name, ghash_name); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-264
0
28,156
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: iasecc_mi_match(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned char resp[0x100]; size_t resp_len; int rv = 0; LOG_FUNC_CALLED(ctx); resp_len = sizeof(resp); rv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len); LOG_TEST_RET(ctx, rv, "IASECC: failed to select MI IAS/ECC applet"); if (!card->ef_atr) card->ef_atr = calloc(1, sizeof(struct sc_ef_atr)); if (!card->ef_atr) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len); card->ef_atr->aid.len = MIIASECC_AID.len; LOG_FUNC_RETURN(ctx, 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
0
20,486
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad( blink::WebLocalFrame* frame) { DCHECK(!frame_ || frame_ == frame); render_view_->history_controller()->RemoveChildrenForRedirect(this); if (frame->parent()) return; WebDataSource* data_source = frame->provisionalDataSource(); if (!data_source) { NOTREACHED(); return; } std::vector<GURL> redirects; GetRedirectChain(data_source, &redirects); if (redirects.size() >= 2) { Send(new FrameHostMsg_DidRedirectProvisionalLoad( routing_id_, render_view_->page_id_, redirects[redirects.size() - 2], redirects.back())); } } Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame. BUG=369553 R=creis@chromium.org Review URL: https://codereview.chromium.org/263833020 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
13,580
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static size_t inet_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct ifaddrmsg)) + nla_total_size(4) /* IFA_ADDRESS */ + nla_total_size(4) /* IFA_LOCAL */ + nla_total_size(4) /* IFA_BROADCAST */ + nla_total_size(IFNAMSIZ) /* IFA_LABEL */ + nla_total_size(4) /* IFA_FLAGS */ + nla_total_size(sizeof(struct ifa_cacheinfo)); /* IFA_CACHEINFO */ } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <solar@openwall.com> Signed-off-by: David S. Miller <davem@davemloft.net> Tested-by: Cyrill Gorcunov <gorcunov@openvz.org> CWE ID: CWE-399
0
1,063
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void __exit pptp_exit_module(void) { unregister_pppox_proto(PX_PROTO_PPTP); proto_unregister(&pptp_sk_proto); gre_del_protocol(&gre_pptp_protocol, GREPROTO_PPTP); vfree(callid_sock); } Commit Message: pptp: verify sockaddr_len in pptp_bind() and pptp_connect() Reported-by: Dmitry Vyukov <dvyukov@gmail.com> Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
557
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: WebInputMethodController* WebLocalFrameImpl::GetInputMethodController() { return &input_method_controller_; } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
0
27,904
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct nfs4_exception exception = { }; ssize_t ret; do { ret = __nfs4_get_acl_uncached(inode, buf, buflen); if (ret >= 0) break; ret = nfs4_handle_exception(NFS_SERVER(inode), ret, &exception); } while (exception.retry); return ret; } Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached _copy_from_pages() used to copy data from the temporary buffer to the user passed buffer is passed the wrong size parameter when copying data. res.acl_len contains both the bitmap and acl lenghts while acl_len contains the acl length after adjusting for the bitmap size. Signed-off-by: Sachin Prabhu <sprabhu@redhat.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
0
25,729
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: const char *php_mb_regex_get_default_mbctype(TSRMLS_D) { return _php_mb_regex_mbctype2name(MBREX(default_mbctype)); } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
0
16,986
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebPage::setSpellCheckingEnabled(bool enabled) { static_cast<EditorClientBlackBerry*>(d->m_page->editorClient())->enableSpellChecking(enabled); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
10,228
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: rend_service_set_connection_addr_port(edge_connection_t *conn, origin_circuit_t *circ) { rend_service_t *service; char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; smartlist_t *matching_ports; rend_service_port_config_t *chosen_port; unsigned int warn_once = 0; const char *rend_pk_digest; tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED); tor_assert(circ->rend_data); log_debug(LD_REND,"beginning to hunt for addr/port"); /* XXX: This is version 2 specific (only one supported). */ rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL); base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1, rend_pk_digest, REND_SERVICE_ID_LEN); service = rend_service_get_by_pk_digest(rend_pk_digest); if (!service) { log_warn(LD_REND, "Couldn't find any service associated with pk %s on " "rendezvous circuit %u; closing.", serviceid, (unsigned)circ->base_.n_circ_id); return -2; } if (service->max_streams_per_circuit > 0) { /* Enforce the streams-per-circuit limit, and refuse to provide a * mapping if this circuit will exceed the limit. */ #define MAX_STREAM_WARN_INTERVAL 600 static struct ratelim_t stream_ratelim = RATELIM_INIT(MAX_STREAM_WARN_INTERVAL); if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) { log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND, "Maximum streams per circuit limit reached on rendezvous " "circuit %u; %s. Circuit has %d out of %d streams.", (unsigned)circ->base_.n_circ_id, service->max_streams_close_circuit ? "closing circuit" : "ignoring open stream request", circ->rend_data->nr_streams, service->max_streams_per_circuit); return service->max_streams_close_circuit ? -2 : -1; } } matching_ports = smartlist_new(); SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, { if (conn->base_.port != p->virtual_port) { continue; } if (!(p->is_unix_addr)) { smartlist_add(matching_ports, p); } else { if (add_unix_port(matching_ports, p)) { if (!warn_once) { /* Unix port not supported so warn only once. */ log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d on service " "%s, which is unsupported on this platform. Ignoring it.", conn->base_.port, serviceid); } warn_once++; } } }); chosen_port = smartlist_choose(matching_ports); smartlist_free(matching_ports); if (chosen_port) { if (!(chosen_port->is_unix_addr)) { /* Get a non-AF_UNIX connection ready for connection_exit_connect() */ tor_addr_copy(&conn->base_.addr, &chosen_port->real_addr); conn->base_.port = chosen_port->real_port; } else { if (set_unix_port(conn, chosen_port)) { /* Simply impossible to end up here else we were able to add a Unix * port without AF_UNIX support... ? */ tor_assert(0); } } return 0; } log_info(LD_REND, "No virtual port mapping exists for port %d on service %s", conn->base_.port, serviceid); if (service->allow_unknown_ports) return -1; else return -2; } Commit Message: Fix log-uninitialized-stack bug in rend_service_intro_established. Fixes bug 23490; bugfix on 0.2.7.2-alpha. TROVE-2017-008 CVE-2017-0380 CWE ID: CWE-532
0
6,566
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl) { return SSL3_RECORD_get_length(&rl->rrec[0]); } Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <levitte@openssl.org> CWE ID: CWE-20
0
1,782
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int fm10k_poll(struct napi_struct *napi, int budget) { struct fm10k_q_vector *q_vector = container_of(napi, struct fm10k_q_vector, napi); struct fm10k_ring *ring; int per_ring_budget, work_done = 0; bool clean_complete = true; fm10k_for_each_ring(ring, q_vector->tx) { if (!fm10k_clean_tx_irq(q_vector, ring, budget)) clean_complete = false; } /* Handle case where we are called by netpoll with a budget of 0 */ if (budget <= 0) return budget; /* attempt to distribute budget to each queue fairly, but don't * allow the budget to go below 1 because we'll exit polling */ if (q_vector->rx.count > 1) per_ring_budget = max(budget / q_vector->rx.count, 1); else per_ring_budget = budget; fm10k_for_each_ring(ring, q_vector->rx) { int work = fm10k_clean_rx_irq(q_vector, ring, per_ring_budget); work_done += work; if (work >= per_ring_budget) clean_complete = false; } /* If all work not completed, return budget and keep polling */ if (!clean_complete) return budget; /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (likely(napi_complete_done(napi, work_done))) fm10k_qv_enable(q_vector); return min(work_done, budget - 1); } Commit Message: fm10k: Fix a potential NULL pointer dereference Syzkaller report this: kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 0 PID: 4378 Comm: syz-executor.0 Tainted: G C 5.0.0+ #5 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:__lock_acquire+0x95b/0x3200 kernel/locking/lockdep.c:3573 Code: 00 0f 85 28 1e 00 00 48 81 c4 08 01 00 00 5b 5d 41 5c 41 5d 41 5e 41 5f c3 4c 89 ea 48 b8 00 00 00 00 00 fc ff df 48 c1 ea 03 <80> 3c 02 00 0f 85 cc 24 00 00 49 81 7d 00 e0 de 03 a6 41 bc 00 00 RSP: 0018:ffff8881e3c07a40 EFLAGS: 00010002 RAX: dffffc0000000000 RBX: 0000000000000000 RCX: 0000000000000000 RDX: 0000000000000010 RSI: 0000000000000000 RDI: 0000000000000080 RBP: 0000000000000000 R08: 0000000000000001 R09: 0000000000000000 R10: ffff8881e3c07d98 R11: ffff8881c7f21f80 R12: 0000000000000001 R13: 0000000000000080 R14: 0000000000000000 R15: 0000000000000001 FS: 00007fce2252e700(0000) GS:ffff8881f2400000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007fffc7eb0228 CR3: 00000001e5bea002 CR4: 00000000007606f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: lock_acquire+0xff/0x2c0 kernel/locking/lockdep.c:4211 __mutex_lock_common kernel/locking/mutex.c:925 [inline] __mutex_lock+0xdf/0x1050 kernel/locking/mutex.c:1072 drain_workqueue+0x24/0x3f0 kernel/workqueue.c:2934 destroy_workqueue+0x23/0x630 kernel/workqueue.c:4319 __do_sys_delete_module kernel/module.c:1018 [inline] __se_sys_delete_module kernel/module.c:961 [inline] __x64_sys_delete_module+0x30c/0x480 kernel/module.c:961 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fce2252dc58 EFLAGS: 00000246 ORIG_RAX: 00000000000000b0 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000020000140 RBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007fce2252e6bc R13: 00000000004bcca9 R14: 00000000006f6b48 R15: 00000000ffffffff If alloc_workqueue fails, it should return -ENOMEM, otherwise may trigger this NULL pointer dereference while unloading drivers. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: 0a38c17a21a0 ("fm10k: Remove create_workqueue") Signed-off-by: Yue Haibing <yuehaibing@huawei.com> Tested-by: Andrew Bowers <andrewx.bowers@intel.com> Signed-off-by: Jeff Kirsher <jeffrey.t.kirsher@intel.com> CWE ID: CWE-476
0
6,121
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = np->cork.opt; struct rt6_info *rt = (struct rt6_info *)inet->cork.base.dst; struct flowi6 *fl6 = &inet->cork.fl.u.ip6; unsigned char proto = fl6->flowi6_proto; int err = 0; if ((skb = __skb_dequeue(&sk->sk_write_queue)) == NULL) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ if (np->pmtudisc < IPV6_PMTUDISC_DO) skb->local_df = 1; *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, np->cork.tclass, fl6->flowlabel); hdr->hop_limit = np->cork.hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS_BH(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_OUTMSGS); } err = ip6_local_out(skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) goto error; } out: ip6_cork_release(inet, np); return err; error: IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); goto out; } Commit Message: ipv6: udp packets following an UFO enqueued packet need also be handled by UFO In the following scenario the socket is corked: If the first UDP packet is larger then the mtu we try to append it to the write queue via ip6_ufo_append_data. A following packet, which is smaller than the mtu would be appended to the already queued up gso-skb via plain ip6_append_data. This causes random memory corruptions. In ip6_ufo_append_data we also have to be careful to not queue up the same skb multiple times. So setup the gso frame only when no first skb is available. This also fixes a shortcoming where we add the current packet's length to cork->length but return early because of a packet > mtu with dontfrag set (instead of sutracting it again). Found with trinity. Cc: YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
0
20,019
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline __maybe_unused int h2_get_frame_hdr(struct buffer *b, struct h2_fh *h) { int ret; ret = h2_peek_frame_hdr(b, h); if (ret > 0) h2_skip_frame_hdr(b); return ret; } Commit Message: CWE ID: CWE-119
0
22,155
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid) { struct sock *sock; struct netlink_sock *nlk; sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid); if (!sock) return ERR_PTR(-ECONNREFUSED); /* Don't bother queuing skb if kernel socket has no input function */ nlk = nlk_sk(sock); if (sock->sk_state == NETLINK_CONNECTED && nlk->dst_portid != nlk_sk(ssk)->portid) { sock_put(sock); return ERR_PTR(-ECONNREFUSED); } return sock; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
20,667
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: std::unique_ptr<infobars::InfoBar> InfoBarService::CreateConfirmInfoBar( std::unique_ptr<ConfirmInfoBarDelegate> delegate) { #if defined(OS_MACOSX) if (views_mode_controller::IsViewsBrowserCocoa()) return InfoBarService::CreateConfirmInfoBarCocoa(std::move(delegate)); #endif return std::make_unique<ConfirmInfoBar>(std::move(delegate)); } Commit Message: Allow to specify elide behavior for confrim infobar message Used in "<extension name> is debugging this browser" infobar. Bug: 823194 Change-Id: Iff6627097c020cccca8f7cc3e21a803a41fd8f2c Reviewed-on: https://chromium-review.googlesource.com/1048064 Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#557245} CWE ID: CWE-254
0
24,683
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void vapic_register(void) { type_register_static(&vapic_type); } Commit Message: CWE ID: CWE-200
0
9,050
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v) { if (vcpu->arch.apic && !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, len, v)) return 0; return kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, len, v); } Commit Message: KVM: X86: Don't report L2 emulation failures to user-space This patch prevents that emulation failures which result from emulating an instruction for an L2-Guest results in being reported to userspace. Without this patch a malicious L2-Guest would be able to kill the L1 by triggering a race-condition between an vmexit and the instruction emulator. With this patch the L2 will most likely only kill itself in this situation. Signed-off-by: Joerg Roedel <joerg.roedel@amd.com> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID: CWE-362
0
14,970
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void HighEntropyAttributeWithMeasureAsAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); TestObject* impl = V8TestObject::ToImpl(holder); V8StringResource<> cpp_value = v8_value; if (!cpp_value.Prepare()) return; impl->setHighEntropyAttributeWithMeasureAs(cpp_value); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <peria@chromium.org> Commit-Queue: Yuki Shiino <yukishiino@chromium.org> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID:
0
18,643
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void inet_register_protosw(struct inet_protosw *p) { struct list_head *lh; struct inet_protosw *answer; int protocol = p->protocol; struct list_head *last_perm; spin_lock_bh(&inetsw_lock); if (p->type >= SOCK_MAX) goto out_illegal; /* If we are trying to override a permanent protocol, bail. */ answer = NULL; last_perm = &inetsw[p->type]; list_for_each(lh, &inetsw[p->type]) { answer = list_entry(lh, struct inet_protosw, list); /* Check only the non-wild match. */ if (INET_PROTOSW_PERMANENT & answer->flags) { if (protocol == answer->protocol) break; last_perm = lh; } answer = NULL; } if (answer) goto out_permanent; /* Add the new entry after the last permanent entry if any, so that * the new entry does not override a permanent entry when matched with * a wild-card protocol. But it is allowed to override any existing * non-permanent entry. This means that when we remove this entry, the * system automatically returns to the old behavior. */ list_add_rcu(&p->list, last_perm); out: spin_unlock_bh(&inetsw_lock); return; out_permanent: printk(KERN_ERR "Attempt to override permanent protocol %d.\n", protocol); goto out; out_illegal: printk(KERN_ERR "Ignoring attempt to register invalid socket type %d.\n", p->type); goto out; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
0
8,816
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void evict_inode_truncate_pages(struct inode *inode) { struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree; struct rb_node *node; ASSERT(inode->i_state & I_FREEING); truncate_inode_pages_final(&inode->i_data); write_lock(&map_tree->lock); while (!RB_EMPTY_ROOT(&map_tree->map)) { struct extent_map *em; node = rb_first(&map_tree->map); em = rb_entry(node, struct extent_map, rb_node); clear_bit(EXTENT_FLAG_PINNED, &em->flags); clear_bit(EXTENT_FLAG_LOGGING, &em->flags); remove_extent_mapping(map_tree, em); free_extent_map(em); if (need_resched()) { write_unlock(&map_tree->lock); cond_resched(); write_lock(&map_tree->lock); } } write_unlock(&map_tree->lock); /* * Keep looping until we have no more ranges in the io tree. * We can have ongoing bios started by readpages (called from readahead) * that have their endio callback (extent_io.c:end_bio_extent_readpage) * still in progress (unlocked the pages in the bio but did not yet * unlocked the ranges in the io tree). Therefore this means some * ranges can still be locked and eviction started because before * submitting those bios, which are executed by a separate task (work * queue kthread), inode references (inode->i_count) were not taken * (which would be dropped in the end io callback of each bio). * Therefore here we effectively end up waiting for those bios and * anyone else holding locked ranges without having bumped the inode's * reference count - if we don't do it, when they access the inode's * io_tree to unlock a range it may be too late, leading to an * use-after-free issue. */ spin_lock(&io_tree->lock); while (!RB_EMPTY_ROOT(&io_tree->state)) { struct extent_state *state; struct extent_state *cached_state = NULL; u64 start; u64 end; node = rb_first(&io_tree->state); state = rb_entry(node, struct extent_state, rb_node); start = state->start; end = state->end; spin_unlock(&io_tree->lock); lock_extent_bits(io_tree, start, end, 0, &cached_state); clear_extent_bit(io_tree, start, end, EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, &cached_state, GFP_NOFS); cond_resched(); spin_lock(&io_tree->lock); } spin_unlock(&io_tree->lock); } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: stable@vger.kernel.org Signed-off-by: Filipe Manana <fdmanana@suse.com> CWE ID: CWE-200
0
16,915
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client) : m_frame(frame) , m_client(client) , m_history(frame) , m_notifer(frame) , m_icon(adoptPtr(new IconController(frame))) , m_mixedContentChecker(frame) , m_state(FrameStateProvisional) , m_loadType(FrameLoadTypeStandard) , m_inStopAllLoaders(false) , m_isComplete(false) , m_containsPlugins(false) , m_checkTimer(this, &FrameLoader::checkTimerFired) , m_shouldCallCheckCompleted(false) , m_opener(0) , m_didAccessInitialDocument(false) , m_didAccessInitialDocumentTimer(this, &FrameLoader::didAccessInitialDocumentTimerFired) , m_suppressOpenerInNewFrame(false) , m_startingClientRedirect(false) , m_forcedSandboxFlags(SandboxNone) { } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
5,108
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void disk_flush_events(struct gendisk *disk, unsigned int mask) { struct disk_events *ev = disk->ev; if (!ev) return; spin_lock_irq(&ev->lock); ev->clearing |= mask; if (!ev->block) mod_delayed_work(system_freezable_power_efficient_wq, &ev->dwork, 0); spin_unlock_irq(&ev->lock); } Commit Message: block: fix use-after-free in seq file I got a KASAN report of use-after-free: ================================================================== BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508 Read of size 8 by task trinity-c1/315 ============================================================================= BUG kmalloc-32 (Not tainted): kasan: bad access detected ----------------------------------------------------------------------------- Disabling lock debugging due to kernel taint INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315 ___slab_alloc+0x4f1/0x520 __slab_alloc.isra.58+0x56/0x80 kmem_cache_alloc_trace+0x260/0x2a0 disk_seqf_start+0x66/0x110 traverse+0x176/0x860 seq_read+0x7e3/0x11a0 proc_reg_read+0xbc/0x180 do_loop_readv_writev+0x134/0x210 do_readv_writev+0x565/0x660 vfs_readv+0x67/0xa0 do_preadv+0x126/0x170 SyS_preadv+0xc/0x10 do_syscall_64+0x1a1/0x460 return_from_SYSCALL_64+0x0/0x6a INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315 __slab_free+0x17a/0x2c0 kfree+0x20a/0x220 disk_seqf_stop+0x42/0x50 traverse+0x3b5/0x860 seq_read+0x7e3/0x11a0 proc_reg_read+0xbc/0x180 do_loop_readv_writev+0x134/0x210 do_readv_writev+0x565/0x660 vfs_readv+0x67/0xa0 do_preadv+0x126/0x170 SyS_preadv+0xc/0x10 do_syscall_64+0x1a1/0x460 return_from_SYSCALL_64+0x0/0x6a CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480 ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480 ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970 Call Trace: [<ffffffff81d6ce81>] dump_stack+0x65/0x84 [<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0 [<ffffffff814704ff>] object_err+0x2f/0x40 [<ffffffff814754d1>] kasan_report_error+0x221/0x520 [<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40 [<ffffffff83888161>] klist_iter_exit+0x61/0x70 [<ffffffff82404389>] class_dev_iter_exit+0x9/0x10 [<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50 [<ffffffff8151f812>] seq_read+0x4b2/0x11a0 [<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180 [<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210 [<ffffffff814b4c45>] do_readv_writev+0x565/0x660 [<ffffffff814b8a17>] vfs_readv+0x67/0xa0 [<ffffffff814b8de6>] do_preadv+0x126/0x170 [<ffffffff814b92ec>] SyS_preadv+0xc/0x10 This problem can occur in the following situation: open() - pread() - .seq_start() - iter = kmalloc() // succeeds - seqf->private = iter - .seq_stop() - kfree(seqf->private) - pread() - .seq_start() - iter = kmalloc() // fails - .seq_stop() - class_dev_iter_exit(seqf->private) // boom! old pointer As the comment in disk_seqf_stop() says, stop is called even if start failed, so we need to reinitialise the private pointer to NULL when seq iteration stops. An alternative would be to set the private pointer to NULL when the kmalloc() in disk_seqf_start() fails. Cc: stable@vger.kernel.org Signed-off-by: Vegard Nossum <vegard.nossum@oracle.com> Acked-by: Tejun Heo <tj@kernel.org> Signed-off-by: Jens Axboe <axboe@fb.com> CWE ID: CWE-416
0
6,634
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static gboolean webkitWebViewBaseDraw(GtkWidget* widget, cairo_t* cr) { DrawingAreaProxy* drawingArea = WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy->drawingArea(); if (!drawingArea) return FALSE; GdkRectangle clipRect; if (!gdk_cairo_get_clip_rectangle(cr, &clipRect)) return FALSE; WebCore::Region unpaintedRegion; // This is simply unused. static_cast<DrawingAreaProxyImpl*>(drawingArea)->paint(cr, clipRect, unpaintedRegion); return FALSE; } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
13,177
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GraphicsLayer* FrameView::layerForHorizontalScrollbar() const { RenderView* renderView = this->renderView(); if (!renderView) return 0; return renderView->compositor()->layerForHorizontalScrollbar(); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 R=vollick@chromium.org Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
0
24,981
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: sample_scale(double sample_value, unsigned int scale) { sample_value = floor(sample_value * scale + .5); /* Return NaN as 0: */ if (!(sample_value > 0)) sample_value = 0; else if (sample_value > scale) sample_value = scale; return (unsigned int)sample_value; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
0
3,906
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t srpt_tpg_attrib_srp_max_rdma_size_store(struct config_item *item, const char *page, size_t count) { struct se_portal_group *se_tpg = attrib_to_tpg(item); struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1); unsigned long val; int ret; ret = kstrtoul(page, 0, &val); if (ret < 0) { pr_err("kstrtoul() failed with ret: %d\n", ret); return -EINVAL; } if (val > MAX_SRPT_RDMA_SIZE) { pr_err("val: %lu exceeds MAX_SRPT_RDMA_SIZE: %d\n", val, MAX_SRPT_RDMA_SIZE); return -EINVAL; } if (val < DEFAULT_MAX_RDMA_SIZE) { pr_err("val: %lu smaller than DEFAULT_MAX_RDMA_SIZE: %d\n", val, DEFAULT_MAX_RDMA_SIZE); return -EINVAL; } sport->port_attrib.srp_max_rdma_size = val; return count; } Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt() Let the target core check task existence instead of the SRP target driver. Additionally, let the target core check the validity of the task management request instead of the ib_srpt driver. This patch fixes the following kernel crash: BUG: unable to handle kernel NULL pointer dereference at 0000000000000001 IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt] Oops: 0002 [#1] SMP Call Trace: [<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt] [<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt] [<ffffffff8109726f>] kthread+0xcf/0xe0 [<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0 Signed-off-by: Bart Van Assche <bart.vanassche@sandisk.com> Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr") Tested-by: Alex Estrin <alex.estrin@intel.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Cc: Nicholas Bellinger <nab@linux-iscsi.org> Cc: Sagi Grimberg <sagig@mellanox.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Doug Ledford <dledford@redhat.com> CWE ID: CWE-476
0
2,785
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ Commit Message: * tools/tiffcrop.c: fix out-of-bound read of up to 3 bytes in readContigTilesIntoBuffer(). Reported as MSVR 35092 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-125
0
6,437
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void cliRefreshPrompt(void) { int len; if (config.eval_ldb) return; if (config.hostsocket != NULL) len = snprintf(config.prompt,sizeof(config.prompt),"redis %s", config.hostsocket); else len = anetFormatAddr(config.prompt, sizeof(config.prompt), config.hostip, config.hostport); /* Add [dbnum] if needed */ if (config.dbnum != 0) len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]", config.dbnum); snprintf(config.prompt+len,sizeof(config.prompt)-len,"> "); } Commit Message: Security: fix redis-cli buffer overflow. Thanks to Fakhri Zulkifli for reporting it. The fix switched to dynamic allocation, copying the final prompt in the static buffer only at the end. CWE ID: CWE-119
1
22,449
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void __devexit airo_pci_remove(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); airo_print_info(dev->name, "Unregistering..."); stop_airo_card(dev, 1); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-264
0
21,416
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } Commit Message: Avoid overflow in ljpeg_start(). CWE ID: CWE-189
0
3,782
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t generic_perform_write_2copy(struct file *file, struct iov_iter *i, loff_t pos) { struct address_space *mapping = file->f_mapping; const struct address_space_operations *a_ops = mapping->a_ops; struct inode *inode = mapping->host; long status = 0; ssize_t written = 0; do { struct page *src_page; struct page *page; pgoff_t index; /* Pagecache index for current page */ unsigned long offset; /* Offset into pagecache page */ unsigned long bytes; /* Bytes to write to page */ size_t copied; /* Bytes copied from user */ offset = (pos & (PAGE_CACHE_SIZE - 1)); index = pos >> PAGE_CACHE_SHIFT; bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_count(i)); /* * a non-NULL src_page indicates that we're doing the * copy via get_user_pages and kmap. */ src_page = NULL; /* * Bring in the user page that we will copy from _first_. * Otherwise there's a nasty deadlock on copying from the * same page as we're writing to, without it being marked * up-to-date. * * Not only is this an optimisation, but it is also required * to check that the address is actually valid, when atomic * usercopies are used, below. */ if (unlikely(iov_iter_fault_in_readable(i, bytes))) { status = -EFAULT; break; } page = __grab_cache_page(mapping, index); if (!page) { status = -ENOMEM; break; } /* * non-uptodate pages cannot cope with short copies, and we * cannot take a pagefault with the destination page locked. * So pin the source page to copy it. */ if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) { unlock_page(page); src_page = alloc_page(GFP_KERNEL); if (!src_page) { page_cache_release(page); status = -ENOMEM; break; } /* * Cannot get_user_pages with a page locked for the * same reason as we can't take a page fault with a * page locked (as explained below). */ copied = iov_iter_copy_from_user(src_page, i, offset, bytes); if (unlikely(copied == 0)) { status = -EFAULT; page_cache_release(page); page_cache_release(src_page); break; } bytes = copied; lock_page(page); /* * Can't handle the page going uptodate here, because * that means we would use non-atomic usercopies, which * zero out the tail of the page, which can cause * zeroes to become transiently visible. We could just * use a non-zeroing copy, but the APIs aren't too * consistent. */ if (unlikely(!page->mapping || PageUptodate(page))) { unlock_page(page); page_cache_release(page); page_cache_release(src_page); continue; } } status = a_ops->prepare_write(file, page, offset, offset+bytes); if (unlikely(status)) goto fs_write_aop_error; if (!src_page) { /* * Must not enter the pagefault handler here, because * we hold the page lock, so we might recursively * deadlock on the same lock, or get an ABBA deadlock * against a different lock, or against the mmap_sem * (which nests outside the page lock). So increment * preempt count, and use _atomic usercopies. * * The page is uptodate so we are OK to encounter a * short copy: if unmodified parts of the page are * marked dirty and written out to disk, it doesn't * really matter. */ pagefault_disable(); copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes); pagefault_enable(); } else { void *src, *dst; src = kmap_atomic(src_page, KM_USER0); dst = kmap_atomic(page, KM_USER1); memcpy(dst + offset, src + offset, bytes); kunmap_atomic(dst, KM_USER1); kunmap_atomic(src, KM_USER0); copied = bytes; } flush_dcache_page(page); status = a_ops->commit_write(file, page, offset, offset+bytes); if (unlikely(status < 0)) goto fs_write_aop_error; if (unlikely(status > 0)) /* filesystem did partial write */ copied = min_t(size_t, copied, status); unlock_page(page); mark_page_accessed(page); page_cache_release(page); if (src_page) page_cache_release(src_page); iov_iter_advance(i, copied); pos += copied; written += copied; balance_dirty_pages_ratelimited(mapping); cond_resched(); continue; fs_write_aop_error: unlock_page(page); page_cache_release(page); if (src_page) page_cache_release(src_page); /* * prepare_write() may have instantiated a few blocks * outside i_size. Trim these off again. Don't need * i_size_read because we hold i_mutex. */ if (pos + bytes > inode->i_size) vmtruncate(inode, inode->i_size); break; } while (iov_iter_count(i)); return written ? written : status; } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <npiggin@suse.de> Signed-off-by: Ingo Molnar <mingo@elte.hu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-20
0
27,670
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: box_intersect(PG_FUNCTION_ARGS) { BOX *box1 = PG_GETARG_BOX_P(0); BOX *box2 = PG_GETARG_BOX_P(1); BOX *result; if (!box_ov(box1, box2)) PG_RETURN_NULL(); result = (BOX *) palloc(sizeof(BOX)); result->high.x = Min(box1->high.x, box2->high.x); result->low.x = Max(box1->low.x, box2->low.x); result->high.y = Min(box1->high.y, box2->high.y); result->low.y = Max(box1->low.y, box2->low.y); PG_RETURN_BOX_P(result); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
0
16,014
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_BGRA; } Commit Message: Progressive JPEG outputScanlines() calls should handle failure outputScanlines() can fail and delete |this|, so any attempt to access members thereafter should be avoided. Copy the decoder pointer member, and use that copy to detect and handle the failure case. BUG=232763 R=pkasting@chromium.org Review URL: https://codereview.chromium.org/14844003 git-svn-id: svn://svn.chromium.org/blink/trunk@150545 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
16,176
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int edge_chars_in_buffer(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int chars = 0; unsigned long flags; if (edge_port == NULL) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); chars = kfifo_len(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, chars); return chars; } Commit Message: USB: serial: io_ti: fix information leak in completion handler Add missing sanity check to the bulk-in completion handler to avoid an integer underflow that can be triggered by a malicious device. This avoids leaking 128 kB of memory content from after the URB transfer buffer to user space. Fixes: 8c209e6782ca ("USB: make actual_length in struct urb field u32") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <stable@vger.kernel.org> # 2.6.30 Signed-off-by: Johan Hovold <johan@kernel.org> CWE ID: CWE-191
0
3,009
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int get_eff_addr_reg(struct insn *insn, struct pt_regs *regs, int *regoff, long *eff_addr) { insn_get_modrm(insn); if (!insn->modrm.nbytes) return -EINVAL; if (X86_MODRM_MOD(insn->modrm.value) != 3) return -EINVAL; *regoff = get_reg_offset(insn, regs, REG_TYPE_RM); if (*regoff < 0) return -EINVAL; /* Ignore bytes that are outside the address size. */ if (insn->addr_bytes == 2) *eff_addr = regs_get_register(regs, *regoff) & 0xffff; else if (insn->addr_bytes == 4) *eff_addr = regs_get_register(regs, *regoff) & 0xffffffff; else /* 64-bit address */ *eff_addr = regs_get_register(regs, *regoff); return 0; } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: stable@vger.kernel.org Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
0
21,929
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void si_conn_send_cb(struct connection *conn) { struct stream_interface *si = conn->owner; struct channel *chn = si->ob; if (conn->flags & CO_FL_ERROR) return; if (conn->flags & CO_FL_HANDSHAKE) /* a handshake was requested */ return; /* we might have been called just after an asynchronous shutw */ if (chn->flags & CF_SHUTW) return; /* OK there are data waiting to be sent */ si_conn_send(conn); /* OK all done */ return; } Commit Message: CWE ID: CWE-189
0
17,740
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: long Segment::ParseNext(const Cluster* pCurr, const Cluster*& pResult, long long& pos, long& len) { assert(pCurr); assert(!pCurr->EOS()); assert(m_clusters); pResult = 0; if (pCurr->m_index >= 0) { // loaded (not merely preloaded) assert(m_clusters[pCurr->m_index] == pCurr); const long next_idx = pCurr->m_index + 1; if (next_idx < m_clusterCount) { pResult = m_clusters[next_idx]; return 0; // success } const long result = LoadCluster(pos, len); if (result < 0) // error or underflow return result; if (result > 0) // no more clusters { return 1; } pResult = GetLast(); return 0; // success } assert(m_pos > 0); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; pos = pCurr->m_element_start; if (pCurr->m_element_size >= 0) pos += pCurr->m_element_size; else { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(m_pReader, pos, len); if (id != 0x0F43B675) // weird: not Cluster ID return -1; pos += len; // consume ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) // TODO: should never happen return E_FILE_FORMAT_INVALID; // TODO: resolve this if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; pos += size; // consume payload (that is, the current cluster) assert((segment_stop < 0) || (pos <= segment_stop)); } for (;;) { const long status = DoParseNext(pResult, pos, len); if (status <= 1) 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
1
4,386
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ChromeContentBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int child_process_id) { #if defined(OS_MACOSX) std::unique_ptr<metrics::ClientInfo> client_info = GoogleUpdateSettings::LoadMetricsClientInfo(); if (client_info) { command_line->AppendSwitchASCII(switches::kMetricsClientID, client_info->client_id); } #elif defined(OS_POSIX) #if defined(OS_ANDROID) bool enable_crash_reporter = true; #else bool enable_crash_reporter = breakpad::IsCrashReporterEnabled(); #endif if (enable_crash_reporter) { std::string switch_value; std::unique_ptr<metrics::ClientInfo> client_info = GoogleUpdateSettings::LoadMetricsClientInfo(); if (client_info) switch_value = client_info->client_id; switch_value.push_back(','); switch_value.append(chrome::GetChannelName()); command_line->AppendSwitchASCII(switches::kEnableCrashReporter, switch_value); } #endif if (logging::DialogsAreSuppressed()) command_line->AppendSwitch(switches::kNoErrorDialogs); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); const base::CommandLine& browser_command_line = *base::CommandLine::ForCurrentProcess(); static const char* const kCommonSwitchNames[] = { switches::kUserAgent, switches::kUserDataDir, // Make logs go to the right file. }; command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames, base::size(kCommonSwitchNames)); static const char* const kDinosaurEasterEggSwitches[] = { error_page::switches::kDisableDinosaurEasterEgg, }; command_line->CopySwitchesFrom(browser_command_line, kDinosaurEasterEggSwitches, base::size(kDinosaurEasterEggSwitches)); #if defined(OS_CHROMEOS) base::FilePath homedir; base::PathService::Get(base::DIR_HOME, &homedir); command_line->AppendSwitchASCII(chromeos::switches::kHomedir, homedir.value().c_str()); #endif if (process_type == switches::kRendererProcess) { content::RenderProcessHost* process = content::RenderProcessHost::FromID(child_process_id); Profile* profile = process ? Profile::FromBrowserContext(process->GetBrowserContext()) : NULL; for (size_t i = 0; i < extra_parts_.size(); ++i) { extra_parts_[i]->AppendExtraRendererCommandLineSwitches( command_line, process, profile); } #if defined(OS_CHROMEOS) const std::string& login_profile = browser_command_line.GetSwitchValueASCII( chromeos::switches::kLoginProfile); if (!login_profile.empty()) command_line->AppendSwitchASCII( chromeos::switches::kLoginProfile, login_profile); #endif MaybeCopyDisableWebRtcEncryptionSwitch(command_line, browser_command_line, chrome::GetChannel()); if (process) { PrefService* prefs = profile->GetPrefs(); if (prefs->HasPrefPath(prefs::kDisable3DAPIs) && prefs->GetBoolean(prefs::kDisable3DAPIs)) { command_line->AppendSwitch(switches::kDisable3DAPIs); } const base::ListValue* switches = prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures); if (switches) { for (auto it = switches->begin(); it != switches->end(); ++it) { std::string switch_to_enable; if (it->GetAsString(&switch_to_enable)) command_line->AppendSwitch(switch_to_enable); } } if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) || !g_browser_process->safe_browsing_detection_service()) { command_line->AppendSwitch( switches::kDisableClientSidePhishingDetection); } if (prefs->GetBoolean(prefs::kPrintPreviewDisabled)) command_line->AppendSwitch(switches::kDisablePrintPreview); #if !defined(OS_ANDROID) InstantService* instant_service = InstantServiceFactory::GetForProfile(profile); if (instant_service && instant_service->IsInstantProcess(process->GetID())) { command_line->AppendSwitch(switches::kInstantProcess); } #endif if (prefs->HasPrefPath(prefs::kAllowDinosaurEasterEgg) && !prefs->GetBoolean(prefs::kAllowDinosaurEasterEgg)) { command_line->AppendSwitch( error_page::switches::kDisableDinosaurEasterEgg); } if (prefs->HasPrefPath(prefs::kUnsafelyTreatInsecureOriginAsSecure)) { command_line->AppendSwitchASCII( network::switches::kUnsafelyTreatInsecureOriginAsSecure, prefs->GetString(prefs::kUnsafelyTreatInsecureOriginAsSecure)); } if (prefs->HasPrefPath(prefs::kAllowPopupsDuringPageUnload)) command_line->AppendSwitch(switches::kAllowPopupsDuringPageUnload); } if (IsAutoReloadEnabled()) command_line->AppendSwitch(switches::kEnableOfflineAutoReload); if (IsAutoReloadVisibleOnlyEnabled()) { command_line->AppendSwitch( switches::kEnableOfflineAutoReloadVisibleOnly); } MaybeAppendBlinkSettingsSwitchForFieldTrial( browser_command_line, command_line); #if defined(OS_ANDROID) command_line->AppendSwitch(switches::kEnableDistillabilityService); #endif static const char* const kSwitchNames[] = { autofill::switches::kIgnoreAutocompleteOffForAutofill, autofill::switches::kShowAutofillSignatures, #if defined(OS_CHROMEOS) switches::kShortMergeSessionTimeoutForTest, // For tests only. #endif #if BUILDFLAG(ENABLE_EXTENSIONS) extensions::switches::kAllowHTTPBackgroundPage, extensions::switches::kAllowLegacyExtensionManifests, extensions::switches::kDisableExtensionsHttpThrottling, extensions::switches::kEnableEmbeddedExtensionOptions, extensions::switches::kEnableExperimentalExtensionApis, extensions::switches::kExtensionsOnChromeURLs, extensions::switches::kSetExtensionThrottleTestParams, // For tests only. extensions::switches::kWhitelistedExtensionID, #endif switches::kAllowInsecureLocalhost, switches::kAppsGalleryURL, switches::kCloudPrintURL, switches::kCloudPrintXmppEndpoint, switches::kDisableBundledPpapiFlash, switches::kDisableJavaScriptHarmonyShipping, variations::switches::kEnableBenchmarking, switches::kEnableDistillabilityService, switches::kEnableNaCl, #if BUILDFLAG(ENABLE_NACL) switches::kEnableNaClDebug, switches::kEnableNaClNonSfiMode, #endif switches::kEnableNetBenchmarking, #if BUILDFLAG(ENABLE_NACL) switches::kForcePNaClSubzero, #endif switches::kForceUIDirection, switches::kJavaScriptHarmony, switches::kOriginTrialDisabledFeatures, switches::kOriginTrialDisabledTokens, switches::kOriginTrialPublicKey, switches::kPpapiFlashArgs, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, switches::kReaderModeHeuristics, translate::switches::kTranslateSecurityOrigin, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, base::size(kSwitchNames)); } else if (process_type == switches::kUtilityProcess) { #if BUILDFLAG(ENABLE_EXTENSIONS) static const char* const kSwitchNames[] = { extensions::switches::kAllowHTTPBackgroundPage, extensions::switches::kEnableExperimentalExtensionApis, extensions::switches::kExtensionsOnChromeURLs, extensions::switches::kWhitelistedExtensionID, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, base::size(kSwitchNames)); #endif } else if (process_type == service_manager::switches::kZygoteProcess) { static const char* const kSwitchNames[] = { switches::kDisableBundledPpapiFlash, #if BUILDFLAG(ENABLE_NACL) switches::kEnableNaClDebug, switches::kEnableNaClNonSfiMode, switches::kForcePNaClSubzero, switches::kNaClDangerousNoSandboxNonSfi, #endif switches::kPpapiFlashPath, switches::kPpapiFlashVersion, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, base::size(kSwitchNames)); } else if (process_type == switches::kGpuProcess) { if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) && !command_line->HasSwitch(switches::kDisableBreakpad)) command_line->AppendSwitch(switches::kDisableBreakpad); } StackSamplingConfiguration::Get()->AppendCommandLineSwitchForChildProcess( process_type, command_line); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
0
9,835
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void sp_free(struct sp_node *n) { mpol_put(n->policy); kmem_cache_free(sn_cache, n); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <salls@cs.ucsb.edu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-388
0
8,211
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline int ipv6_is_local_multicast(const struct in6_addr *addr) { if (ipv6_addr_is_multicast(addr) && IPV6_ADDR_MC_SCOPE(addr) <= IPV6_ADDR_SCOPE_LINKLOCAL) return 1; return 0; } Commit Message: bridge: Fix mglist corruption that leads to memory corruption The list mp->mglist is used to indicate whether a multicast group is active on the bridge interface itself as opposed to one of the constituent interfaces in the bridge. Unfortunately the operation that adds the mp->mglist node to the list neglected to check whether it has already been added. This leads to list corruption in the form of nodes pointing to itself. Normally this would be quite obvious as it would cause an infinite loop when walking the list. However, as this list is never actually walked (which means that we don't really need it, I'll get rid of it in a subsequent patch), this instead is hidden until we perform a delete operation on the affected nodes. As the same node may now be pointed to by more than one node, the delete operations can then cause modification of freed memory. This was observed in practice to cause corruption in 512-byte slabs, most commonly leading to crashes in jbd2. Thanks to Josef Bacik for pointing me in the right direction. Reported-by: Ian Page Hands <ihands@redhat.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
0
3,569
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: isdn_net_log_skb(struct sk_buff * skb, isdn_net_local * lp) { /* hopefully, this was set correctly */ const u_char *p = skb_network_header(skb); unsigned short proto = ntohs(skb->protocol); int data_ofs; ip_ports *ipp; char addinfo[100]; addinfo[0] = '\0'; /* This check stolen from 2.1.72 dev_queue_xmit_nit() */ if (p < skb->data || skb->network_header >= skb->tail) { /* fall back to old isdn_net_log_packet method() */ char * buf = skb->data; printk(KERN_DEBUG "isdn_net: protocol %04x is buggy, dev %s\n", skb->protocol, lp->netdev->dev->name); p = buf; proto = ETH_P_IP; switch (lp->p_encap) { case ISDN_NET_ENCAP_IPTYP: proto = ntohs(*(__be16 *)&buf[0]); p = &buf[2]; break; case ISDN_NET_ENCAP_ETHER: proto = ntohs(*(__be16 *)&buf[12]); p = &buf[14]; break; case ISDN_NET_ENCAP_CISCOHDLC: proto = ntohs(*(__be16 *)&buf[2]); p = &buf[4]; break; #ifdef CONFIG_ISDN_PPP case ISDN_NET_ENCAP_SYNCPPP: proto = ntohs(skb->protocol); p = &buf[IPPP_MAX_HEADER]; break; #endif } } data_ofs = ((p[0] & 15) * 4); switch (proto) { case ETH_P_IP: switch (p[9]) { case 1: strcpy(addinfo, " ICMP"); break; case 2: strcpy(addinfo, " IGMP"); break; case 4: strcpy(addinfo, " IPIP"); break; case 6: ipp = (ip_ports *) (&p[data_ofs]); sprintf(addinfo, " TCP, port: %d -> %d", ntohs(ipp->source), ntohs(ipp->dest)); break; case 8: strcpy(addinfo, " EGP"); break; case 12: strcpy(addinfo, " PUP"); break; case 17: ipp = (ip_ports *) (&p[data_ofs]); sprintf(addinfo, " UDP, port: %d -> %d", ntohs(ipp->source), ntohs(ipp->dest)); break; case 22: strcpy(addinfo, " IDP"); break; } printk(KERN_INFO "OPEN: %pI4 -> %pI4%s\n", p + 12, p + 16, addinfo); break; case ETH_P_ARP: printk(KERN_INFO "OPEN: ARP %pI4 -> *.*.*.* ?%pI4\n", p + 14, p + 24); break; } } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-264
0
19,601
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool jshGetPinStateIsManual(Pin pin) { return BITFIELD_GET(jshPinStateIsManual, pin); } Commit Message: Fix strncat/cpy bounding issues (fix #1425) CWE ID: CWE-119
0
22,412
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ResizeObserverController& Document::EnsureResizeObserverController() { if (!resize_observer_controller_) resize_observer_controller_ = new ResizeObserverController(); return *resize_observer_controller_; } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
0
19,485
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int f2fs_issue_flush(struct f2fs_sb_info *sbi) { struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info; struct flush_cmd cmd; int ret; if (test_opt(sbi, NOBARRIER)) return 0; if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); return ret; } if (!atomic_read(&fcc->issing_flush)) { atomic_inc(&fcc->issing_flush); ret = submit_flush_wait(sbi); atomic_dec(&fcc->issing_flush); atomic_inc(&fcc->issued_flush); return ret; } init_completion(&cmd.wait); atomic_inc(&fcc->issing_flush); llist_add(&cmd.llnode, &fcc->issue_list); if (!fcc->dispatch_list) wake_up(&fcc->flush_wait_queue); if (fcc->f2fs_issue_flush) { wait_for_completion(&cmd.wait); atomic_dec(&fcc->issing_flush); } else { llist_del_all(&fcc->issue_list); atomic_set(&fcc->issing_flush, 0); } return cmd.ret; } Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <heyunlei@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-476
0
12,827
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: R_API ut64 r_bin_java_bootstrap_method_calc_size(RBinJavaBootStrapMethod *bsm) { RListIter *iter, *iter_tmp; RBinJavaBootStrapArgument *bsm_arg = NULL; ut64 size = 0; if (bsm) { size += 6; size += 2; size += 2; r_list_foreach_safe (bsm->bootstrap_arguments, iter, iter_tmp, bsm_arg) { if (bsm_arg) { size += r_bin_java_bootstrap_arg_calc_size (bsm_arg); } else { } } } return size; } Commit Message: Fix #10498 - Crash in fuzzed java file CWE ID: CWE-125
0
11,541
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: initializeEncoding(XML_Parser parser) { const char *s; #ifdef XML_UNICODE char encodingBuf[128]; /* See comments abount `protoclEncodingName` in parserInit() */ if (! parser->m_protocolEncodingName) s = NULL; else { int i; for (i = 0; parser->m_protocolEncodingName[i]; i++) { if (i == sizeof(encodingBuf) - 1 || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) { encodingBuf[0] = '\0'; break; } encodingBuf[i] = (char)parser->m_protocolEncodingName[i]; } encodingBuf[i] = '\0'; s = encodingBuf; } #else s = parser->m_protocolEncodingName; #endif if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)( &parser->m_initEncoding, &parser->m_encoding, s)) return XML_ERROR_NONE; return handleUnknownEncoding(parser, parser->m_protocolEncodingName); } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
0
28,609