instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
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 foveon_camf_matrix (unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp (name, pos+sget4(pos+12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos+16); type = sget4(cp); if ((ndim = sget4(cp+4)) > 3) break; dp = pos + sget4(cp+8); for (i=ndim; i--; ) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break; mat = (unsigned *) malloc ((size = dsize) * 4); merror (mat, "foveon_camf_matrix()"); for (i=0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i*4); else mat[i] = sget4(dp + i*2) & 0xffff; return mat; } dcraw_message (DCRAW_WARNING,_("%s: \"%s\" matrix not found!\n"), ifname_display, name); return 0; } Commit Message: Avoid overflow in ljpeg_start(). CWE ID: CWE-189
0
43,266
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 asn1_decode_se_info(sc_context_t *ctx, const u8 *obj, size_t objlen, sc_pkcs15_sec_env_info_t ***se, size_t *num, int depth) { struct sc_pkcs15_sec_env_info **ses; const unsigned char *ptr = obj; size_t idx, ptrlen = objlen; int ret; ses = calloc(SC_MAX_SE_NUM, sizeof(sc_pkcs15_sec_env_info_t *)); if (ses == NULL) return SC_ERROR_OUT_OF_MEMORY; for (idx=0; idx < SC_MAX_SE_NUM && ptrlen; ) { struct sc_asn1_entry asn1_se[2]; struct sc_asn1_entry asn1_se_info[4]; struct sc_pkcs15_sec_env_info si; sc_copy_asn1_entry(c_asn1_se, asn1_se); sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info); si.aid.len = sizeof(si.aid.value); sc_format_asn1_entry(asn1_se_info + 0, &si.se, NULL, 0); sc_format_asn1_entry(asn1_se_info + 1, &si.owner, NULL, 0); sc_format_asn1_entry(asn1_se_info + 2, &si.aid.value, &si.aid.len, 0); sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 0); ret = asn1_decode(ctx, asn1_se, ptr, ptrlen, &ptr, &ptrlen, 0, depth+1); if (ret != SC_SUCCESS) goto err; if (!(asn1_se_info[1].flags & SC_ASN1_PRESENT)) sc_init_oid(&si.owner); ses[idx] = calloc(1, sizeof(sc_pkcs15_sec_env_info_t)); if (ses[idx] == NULL) { ret = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(ses[idx], &si, sizeof(struct sc_pkcs15_sec_env_info)); idx++; } *se = ses; *num = idx; ret = SC_SUCCESS; err: if (ret != SC_SUCCESS) { size_t i; for (i = 0; i < idx; i++) if (ses[i]) free(ses[i]); free(ses); } return ret; } 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
78,104
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: net::EmbeddedTestServer::Type GetTestServerType() { if (std::get<0>(GetParam()) == ProxyServer_ProxyScheme_HTTP) return net::EmbeddedTestServer::TYPE_HTTP; return net::EmbeddedTestServer::TYPE_HTTPS; } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
0
137,843
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 blk_cloned_rq_check_limits(struct request_queue *q, struct request *rq) { if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, req_op(rq))) { printk(KERN_ERR "%s: over max size limit.\n", __func__); return -EIO; } /* * queue's settings related to segment counting like q->bounce_pfn * may differ from that of other stacking queues. * Recalculate it to check the request correctly on this queue's * limitation. */ blk_recalc_rq_segments(rq); if (rq->nr_phys_segments > queue_max_segments(q)) { printk(KERN_ERR "%s: over max segments limit.\n", __func__); return -EIO; } return 0; } Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case We find the memory use-after-free issue in __blk_drain_queue() on the kernel 4.14. After read the latest kernel 4.18-rc6 we think it has the same problem. Memory is allocated for q->fq in the blk_init_allocated_queue(). If the elevator init function called with error return, it will run into the fail case to free the q->fq. Then the __blk_drain_queue() uses the same memory after the free of the q->fq, it will lead to the unpredictable event. The patch is to set q->fq as NULL in the fail case of blk_init_allocated_queue(). Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery") Cc: <stable@vger.kernel.org> Reviewed-by: Ming Lei <ming.lei@redhat.com> Reviewed-by: Bart Van Assche <bart.vanassche@wdc.com> Signed-off-by: xiao jin <jin.xiao@intel.com> Signed-off-by: Jens Axboe <axboe@kernel.dk> CWE ID: CWE-416
0
91,968
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 stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files CWE ID: CWE-119
0
75,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: base::i18n::TextDirection WebTextDirectionToChromeTextDirection( blink::WebTextDirection dir) { switch (dir) { case blink::kWebTextDirectionLeftToRight: return base::i18n::LEFT_TO_RIGHT; case blink::kWebTextDirectionRightToLeft: return base::i18n::RIGHT_TO_LEFT; default: NOTREACHED(); return base::i18n::UNKNOWN_DIRECTION; } } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
0
127,917
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 coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp, int32_t newdirfid, V9fsString *name) { char *end; int err = 0; V9fsPath new_path; V9fsFidState *tfidp; V9fsState *s = pdu->s; V9fsFidState *dirfidp = NULL; char *old_name, *new_name; v9fs_path_init(&new_path); if (newdirfid != -1) { dirfidp = get_fid(pdu, newdirfid); if (dirfidp == NULL) { err = -ENOENT; goto out_nofid; } if (fidp->fid_type != P9_FID_NONE) { err = -EINVAL; goto out; } v9fs_co_name_to_path(pdu, &dirfidp->path, name->data, &new_path); } else { old_name = fidp->path.data; end = strrchr(old_name, '/'); if (end) { end++; } else { end = old_name; } new_name = g_malloc0(end - old_name + name->size + 1); strncat(new_name, old_name, end - old_name); strncat(new_name + (end - old_name), name->data, name->size); v9fs_co_name_to_path(pdu, NULL, new_name, &new_path); g_free(new_name); } err = v9fs_co_rename(pdu, &fidp->path, &new_path); if (err < 0) { goto out; } /* * Fixup fid's pointing to the old name to * start pointing to the new name */ for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) { if (v9fs_path_is_ancestor(&fidp->path, &tfidp->path)) { /* replace the name */ v9fs_fix_path(&tfidp->path, &new_path, strlen(fidp->path.data)); } } out: if (dirfidp) { put_fid(pdu, dirfidp); } v9fs_path_free(&new_path); out_nofid: return err; } Commit Message: CWE ID: CWE-400
0
7,712
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: __u32 sctp_association_get_next_tsn(struct sctp_association *asoc) { /* From Section 1.6 Serial Number Arithmetic: * Transmission Sequence Numbers wrap around when they reach * 2**32 - 1. That is, the next TSN a DATA chunk MUST use * after transmitting TSN = 2*32 - 1 is TSN = 0. */ __u32 retval = asoc->next_tsn; asoc->next_tsn++; asoc->unack_data++; return retval; } Commit Message: net: sctp: inherit auth_capable on INIT collisions Jason reported an oops caused by SCTP on his ARM machine with SCTP authentication enabled: Internal error: Oops: 17 [#1] ARM CPU: 0 PID: 104 Comm: sctp-test Not tainted 3.13.0-68744-g3632f30c9b20-dirty #1 task: c6eefa40 ti: c6f52000 task.ti: c6f52000 PC is at sctp_auth_calculate_hmac+0xc4/0x10c LR is at sg_init_table+0x20/0x38 pc : [<c024bb80>] lr : [<c00f32dc>] psr: 40000013 sp : c6f538e8 ip : 00000000 fp : c6f53924 r10: c6f50d80 r9 : 00000000 r8 : 00010000 r7 : 00000000 r6 : c7be4000 r5 : 00000000 r4 : c6f56254 r3 : c00c8170 r2 : 00000001 r1 : 00000008 r0 : c6f1e660 Flags: nZcv IRQs on FIQs on Mode SVC_32 ISA ARM Segment user Control: 0005397f Table: 06f28000 DAC: 00000015 Process sctp-test (pid: 104, stack limit = 0xc6f521c0) Stack: (0xc6f538e8 to 0xc6f54000) [...] Backtrace: [<c024babc>] (sctp_auth_calculate_hmac+0x0/0x10c) from [<c0249af8>] (sctp_packet_transmit+0x33c/0x5c8) [<c02497bc>] (sctp_packet_transmit+0x0/0x5c8) from [<c023e96c>] (sctp_outq_flush+0x7fc/0x844) [<c023e170>] (sctp_outq_flush+0x0/0x844) from [<c023ef78>] (sctp_outq_uncork+0x24/0x28) [<c023ef54>] (sctp_outq_uncork+0x0/0x28) from [<c0234364>] (sctp_side_effects+0x1134/0x1220) [<c0233230>] (sctp_side_effects+0x0/0x1220) from [<c02330b0>] (sctp_do_sm+0xac/0xd4) [<c0233004>] (sctp_do_sm+0x0/0xd4) from [<c023675c>] (sctp_assoc_bh_rcv+0x118/0x160) [<c0236644>] (sctp_assoc_bh_rcv+0x0/0x160) from [<c023d5bc>] (sctp_inq_push+0x6c/0x74) [<c023d550>] (sctp_inq_push+0x0/0x74) from [<c024a6b0>] (sctp_rcv+0x7d8/0x888) While we already had various kind of bugs in that area ec0223ec48a9 ("net: sctp: fix sctp_sf_do_5_1D_ce to verify if we/peer is AUTH capable") and b14878ccb7fa ("net: sctp: cache auth_enable per endpoint"), this one is a bit of a different kind. Giving a bit more background on why SCTP authentication is needed can be found in RFC4895: SCTP uses 32-bit verification tags to protect itself against blind attackers. These values are not changed during the lifetime of an SCTP association. Looking at new SCTP extensions, there is the need to have a method of proving that an SCTP chunk(s) was really sent by the original peer that started the association and not by a malicious attacker. To cause this bug, we're triggering an INIT collision between peers; normal SCTP handshake where both sides intent to authenticate packets contains RANDOM; CHUNKS; HMAC-ALGO parameters that are being negotiated among peers: ---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------> <------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------- -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- RFC4895 says that each endpoint therefore knows its own random number and the peer's random number *after* the association has been established. The local and peer's random number along with the shared key are then part of the secret used for calculating the HMAC in the AUTH chunk. Now, in our scenario, we have 2 threads with 1 non-blocking SEQ_PACKET socket each, setting up common shared SCTP_AUTH_KEY and SCTP_AUTH_ACTIVE_KEY properly, and each of them calling sctp_bindx(3), listen(2) and connect(2) against each other, thus the handshake looks similar to this, e.g.: ---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------> <------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------- <--------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------- -------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------> ... Since such collisions can also happen with verification tags, the RFC4895 for AUTH rather vaguely says under section 6.1: In case of INIT collision, the rules governing the handling of this Random Number follow the same pattern as those for the Verification Tag, as explained in Section 5.2.4 of RFC 2960 [5]. Therefore, each endpoint knows its own Random Number and the peer's Random Number after the association has been established. In RFC2960, section 5.2.4, we're eventually hitting Action B: B) In this case, both sides may be attempting to start an association at about the same time but the peer endpoint started its INIT after responding to the local endpoint's INIT. Thus it may have picked a new Verification Tag not being aware of the previous Tag it had sent this endpoint. The endpoint should stay in or enter the ESTABLISHED state but it MUST update its peer's Verification Tag from the State Cookie, stop any init or cookie timers that may running and send a COOKIE ACK. In other words, the handling of the Random parameter is the same as behavior for the Verification Tag as described in Action B of section 5.2.4. Looking at the code, we exactly hit the sctp_sf_do_dupcook_b() case which triggers an SCTP_CMD_UPDATE_ASSOC command to the side effect interpreter, and in fact it properly copies over peer_{random, hmacs, chunks} parameters from the newly created association to update the existing one. Also, the old asoc_shared_key is being released and based on the new params, sctp_auth_asoc_init_active_key() updated. However, the issue observed in this case is that the previous asoc->peer.auth_capable was 0, and has *not* been updated, so that instead of creating a new secret, we're doing an early return from the function sctp_auth_asoc_init_active_key() leaving asoc->asoc_shared_key as NULL. However, we now have to authenticate chunks from the updated chunk list (e.g. COOKIE-ACK). That in fact causes the server side when responding with ... <------------------ AUTH; COOKIE-ACK ----------------- ... to trigger a NULL pointer dereference, since in sctp_packet_transmit(), it discovers that an AUTH chunk is being queued for xmit, and thus it calls sctp_auth_calculate_hmac(). Since the asoc->active_key_id is still inherited from the endpoint, and the same as encoded into the chunk, it uses asoc->asoc_shared_key, which is still NULL, as an asoc_key and dereferences it in ... crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len) ... causing an oops. All this happens because sctp_make_cookie_ack() called with the *new* association has the peer.auth_capable=1 and therefore marks the chunk with auth=1 after checking sctp_auth_send_cid(), but it is *actually* sent later on over the then *updated* association's transport that didn't initialize its shared key due to peer.auth_capable=0. Since control chunks in that case are not sent by the temporary association which are scheduled for deletion, they are issued for xmit via SCTP_CMD_REPLY in the interpreter with the context of the *updated* association. peer.auth_capable was 0 in the updated association (which went from COOKIE_WAIT into ESTABLISHED state), since all previous processing that performed sctp_process_init() was being done on temporary associations, that we eventually throw away each time. The correct fix is to update to the new peer.auth_capable value as well in the collision case via sctp_assoc_update(), so that in case the collision migrated from 0 -> 1, sctp_auth_asoc_init_active_key() can properly recalculate the secret. This therefore fixes the observed server panic. Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing") Reported-by: Jason Gunthorpe <jgunthorpe@obsidianresearch.com> Signed-off-by: Daniel Borkmann <dborkman@redhat.com> Tested-by: Jason Gunthorpe <jgunthorpe@obsidianresearch.com> Cc: Vlad Yasevich <vyasevich@gmail.com> Acked-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
36,264
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: MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); (void) InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClutImage) #endif proceed=SetImageProgress(image,ClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/663 https://github.com/ImageMagick/ImageMagick/issues/655 CWE ID: CWE-119
0
62,627
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: person_get_offset(const person_t* person) { return mk_point2(person->x_offset, person->y_offset); } Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268) * Fix integer overflow in layer_resize in map_engine.c There's a buffer overflow bug in the function layer_resize. It allocates a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`. But it didn't check for integer overflow, so if x_size and y_size are very large, it's possible that the buffer size is smaller than needed, causing a buffer overflow later. PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);` * move malloc to a separate line CWE ID: CWE-190
0
75,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: size_t utf8_to_utf32_length(const char *src, size_t src_len) { if (src == NULL || src_len == 0) { return 0; } size_t ret = 0; const char* cur; const char* end; size_t num_to_skip; for (cur = src, end = src + src_len, num_to_skip = 1; cur < end; cur += num_to_skip, ret++) { const char first_char = *cur; num_to_skip = 1; if ((first_char & 0x80) == 0) { // ASCII continue; } int32_t mask; for (mask = 0x40; (first_char & mask); num_to_skip++, mask >>= 1) { } } return ret; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
0
158,448
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: Document::~Document() { ASSERT(!layoutView()); ASSERT(!parentTreeScope()); ASSERT(!m_axObjectCache); #if !ENABLE(OILPAN) ASSERT(m_ranges.isEmpty()); ASSERT(!hasGuardRefCount()); ASSERT(!m_importsController); ASSERT(m_visibilityObservers.isEmpty()); if (m_templateDocument) m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument(). m_scriptRunner.clear(); removeAllEventListenersRecursively(); ASSERT(!m_parser || m_parser->refCount() == 1); detachParser(); if (m_styleSheetList) m_styleSheetList->detachFromDocument(); m_timeline->detachFromDocument(); m_styleEngine->detachFromDocument(); if (m_elemSheet) m_elemSheet->clearOwnerNode(); if (hasRareData()) clearRareData(); ASSERT(m_listsInvalidatedAtDocument.isEmpty()); for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i) ASSERT(!m_nodeListCounts[i]); liveDocumentSet().remove(this); #endif InstanceCounters::decrementCounter(InstanceCounters::DocumentCounter); } Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642} CWE ID: CWE-264
0
124,582
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 ossl_statem_set_in_handshake(SSL *s, int inhand) { if (inhand) s->statem.in_handshake++; else s->statem.in_handshake--; } Commit Message: CWE ID: CWE-416
0
9,361
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 bmpmask32toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask, OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; OPJ_BOOL hasAlpha; OPJ_UINT32 redShift, redPrec; OPJ_UINT32 greenShift, greenPrec; OPJ_UINT32 blueShift, bluePrec; OPJ_UINT32 alphaShift, alphaPrec; width = image->comps[0].w; height = image->comps[0].h; hasAlpha = image->numcomps > 3U; bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec); bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec); bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec); bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec); image->comps[0].bpp = redPrec; image->comps[0].prec = redPrec; image->comps[1].bpp = greenPrec; image->comps[1].prec = greenPrec; image->comps[2].bpp = bluePrec; image->comps[2].prec = bluePrec; if (hasAlpha) { image->comps[3].bpp = alphaPrec; image->comps[3].prec = alphaPrec; } index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { OPJ_UINT32 value = 0U; value |= ((OPJ_UINT32)pSrc[4*x+0]) << 0; value |= ((OPJ_UINT32)pSrc[4*x+1]) << 8; value |= ((OPJ_UINT32)pSrc[4*x+2]) << 16; value |= ((OPJ_UINT32)pSrc[4*x+3]) << 24; image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >> redShift); /* R */ image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >> greenShift); /* G */ image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >> blueShift); /* B */ if (hasAlpha) { image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >> alphaShift); /* A */ } index++; } pSrc -= stride; } } Commit Message: Merge pull request #834 from trylab/issue833 Fix issue 833. CWE ID: CWE-190
0
70,089
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 HTMLFormElement::shouldAutocomplete() const { return !equalIgnoringCase(fastGetAttribute(autocompleteAttr), "off"); } Commit Message: Fix a crash in HTMLFormElement::prepareForSubmission. BUG=297478 TEST=automated with ASAN. Review URL: https://chromiumcodereview.appspot.com/24910003 git-svn-id: svn://svn.chromium.org/blink/trunk@158428 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
111,017
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 RenderWidgetHostViewAndroid::StartContentIntent( const GURL& content_url) { if (content_view_core_) content_view_core_->StartContentIntent(content_url); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
114,789
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: pdf14_copy_planes(gx_device * dev, const byte * data, int data_x, int raster, gx_bitmap_id id, int x, int y, int w, int h, int plane_height) { pdf14_device *pdev = (pdf14_device *)dev; #if RAW_DUMP pdf14_ctx *ctx = pdev->ctx; #endif pdf14_buf *buf = pdev->ctx->stack; uchar num_planes = dev->color_info.num_components; byte *dptr = (byte *)data + data_x; int yinc, xinc; uchar pi; gx_drawing_color dcolor; int code = 0; fit_fill_xywh(dev, x, y, w, h); if (w <= 0 || h <= 0) return 0; dcolor.type = gx_dc_type_devn; /* Because of the complexity of the blending and my desire to finish this planar sep device work, I am going to make this a series of rect fills. ToDo: optimize this for more efficient planar operation. It would be interesting to use the put_image procedure. */ for (yinc = 0; yinc < h; yinc++) { for (xinc = 0; xinc < w; xinc++) { for (pi = 0; pi < num_planes; pi++) { dcolor.colors.devn.values[pi] = *(dptr + plane_height * raster * pi) << 8; } if (buf->knockout) code = pdf14_mark_fill_rectangle_ko_simple(dev, x + xinc, y + yinc, 1, 1, 0, &dcolor, true); else code = pdf14_mark_fill_rectangle(dev, x + xinc, y + yinc, 1, 1, 0, &dcolor, true); if (code < 0) return code; dptr++; } dptr = (byte *)data + raster * yinc + data_x; } return code; } Commit Message: CWE ID: CWE-476
0
13,300
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 unsigned long emulator_get_cached_segment_base(int seg, struct kvm_vcpu *vcpu) { return get_segment_base(vcpu, seg); } 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
41,327
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: HB_Error HB_GPOS_Select_Script( HB_GPOSHeader* gpos, HB_UInt script_tag, HB_UShort* script_index ) { HB_UShort n; HB_ScriptList* sl; HB_ScriptRecord* sr; if ( !gpos || !script_index ) return ERR(HB_Err_Invalid_Argument); sl = &gpos->ScriptList; sr = sl->ScriptRecord; for ( n = 0; n < sl->ScriptCount; n++ ) if ( script_tag == sr[n].ScriptTag ) { *script_index = n; return HB_Err_Ok; } return HB_Err_Not_Covered; } Commit Message: CWE ID: CWE-119
0
13,565
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: WebResourceTimingInfo Performance::GenerateResourceTiming( const SecurityOrigin& destination_origin, const ResourceTimingInfo& info, ExecutionContext& context_for_use_counter) { const ResourceResponse& final_response = info.FinalResponse(); WebResourceTimingInfo result; result.name = info.InitialURL().GetString(); result.start_time = info.InitialTime(); result.alpn_negotiated_protocol = final_response.AlpnNegotiatedProtocol(); result.connection_info = final_response.ConnectionInfoString(); result.timing = final_response.GetResourceLoadTiming(); result.finish_time = info.LoadFinishTime(); result.allow_timing_details = PassesTimingAllowCheck( final_response, destination_origin, info.OriginalTimingAllowOrigin(), &context_for_use_counter); const Vector<ResourceResponse>& redirect_chain = info.RedirectChain(); if (!redirect_chain.IsEmpty()) { result.allow_redirect_details = AllowsTimingRedirect(redirect_chain, final_response, destination_origin, &context_for_use_counter); if (ResourceLoadTiming* last_chained_timing = redirect_chain.back().GetResourceLoadTiming()) { result.last_redirect_end_time = TimeTicksInSeconds(last_chained_timing->ReceiveHeadersEnd()); } else { result.allow_redirect_details = false; result.last_redirect_end_time = 0.0; } if (!result.allow_redirect_details) { if (ResourceLoadTiming* final_timing = final_response.GetResourceLoadTiming()) { result.start_time = TimeTicksInSeconds(final_timing->RequestTime()); } } } else { result.allow_redirect_details = false; result.last_redirect_end_time = 0.0; } result.transfer_size = info.TransferSize(); result.encoded_body_size = final_response.EncodedBodyLength(); result.decoded_body_size = final_response.DecodedBodyLength(); result.did_reuse_connection = final_response.ConnectionReused(); result.allow_negative_values = info.NegativeAllowed(); if (result.allow_timing_details) { result.server_timing = PerformanceServerTiming::ParseServerTiming(info); } if (!result.server_timing.empty()) { UseCounter::Count(&context_for_use_counter, WebFeature::kPerformanceServerTiming); } return result; } Commit Message: Fix timing allow check algorithm for service workers This CL uses the OriginalURLViaServiceWorker() in the timing allow check algorithm if the response WasFetchedViaServiceWorker(). This way, if a service worker changes a same origin request to become cross origin, then the timing allow check algorithm will still fail. resource-timing-worker.js is changed so it avoids an empty Response, which is an odd case in terms of same origin checks. Bug: 837275 Change-Id: I7e497a6fcc2ee14244121b915ca5f5cceded417a Reviewed-on: https://chromium-review.googlesource.com/1038229 Commit-Queue: Nicolás Peña Moreno <npm@chromium.org> Reviewed-by: Yoav Weiss <yoav@yoav.ws> Reviewed-by: Timothy Dresser <tdresser@chromium.org> Cr-Commit-Position: refs/heads/master@{#555476} CWE ID: CWE-200
0
153,856
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 BrowserView::CanActivate() const { app_modal::AppModalDialogQueue* queue = app_modal::AppModalDialogQueue::GetInstance(); if (!queue->active_dialog() || !queue->active_dialog()->native_dialog() || !queue->active_dialog()->native_dialog()->IsShowing()) { return true; } #if defined(USE_AURA) && defined(OS_CHROMEOS) queue->ActivateModalDialog(); #else base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&BrowserView::ActivateAppModalDialog, activate_modal_dialog_factory_.GetWeakPtr())); #endif return false; } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <sdy@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20
0
155,143
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 wvlan_set_porttype(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra) { struct wl_private *lp = wl_priv(dev); unsigned long flags; int ret = 0; hcf_16 portType; /*------------------------------------------------------------------------*/ DBG_FUNC("wvlan_set_porttype"); DBG_ENTER(DbgInfo); wl_lock(lp, &flags); /* Validate the new value */ portType = *((__u32 *)extra); if (!((portType == 1) || (portType == 3))) { ret = -EINVAL; goto out_unlock; } lp->PortType = portType; /* Commit the adapter parameters */ wl_apply(lp); out_unlock: wl_unlock(lp, &flags); /* out: */ DBG_LEAVE(DbgInfo); return ret; } Commit Message: staging: wlags49_h2: buffer overflow setting station name We need to check the length parameter before doing the memcpy(). I've actually changed it to strlcpy() as well so that it's NUL terminated. You need CAP_NET_ADMIN to trigger these so it's not the end of the world. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
0
29,472
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 WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) { RemoveDestructionObserver(web_contents); for (auto iter = pending_contents_.begin(); iter != pending_contents_.end(); ++iter) { if (iter->second != web_contents) continue; pending_contents_.erase(iter); return; } NOTREACHED(); } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
0
135,836
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: ExportTIFF_ArrayASCII ( const SXMPMeta & xmp, const char * xmpNS, const char * xmpProp, TIFF_Manager * tiff, XMP_Uns8 ifd, XMP_Uns16 id ) { try { // Don't let errors with one stop the others. std::string itemValue, fullValue; XMP_OptionBits xmpFlags; bool foundXMP = xmp.GetProperty ( xmpNS, xmpProp, 0, &xmpFlags ); if ( ! foundXMP ) { tiff->DeleteTag ( ifd, id ); return; } if ( ! XMP_PropIsArray ( xmpFlags ) ) return; // ? Complain? Delete the tag? if ( id == kTIFF_Artist ) { SXMPUtils::CatenateArrayItems ( xmp, xmpNS, xmpProp, 0, 0, (kXMP_PropArrayIsOrdered | kXMPUtil_AllowCommas), &fullValue ); fullValue += '\x0'; // ! Need explicit final nul for SetTag below. } else { size_t count = xmp.CountArrayItems ( xmpNS, xmpProp ); for ( size_t i = 1; i <= count; ++i ) { // ! XMP arrays are indexed from 1. (void) xmp.GetArrayItem ( xmpNS, xmpProp, (XMP_Index)i, &itemValue, &xmpFlags ); if ( ! XMP_PropIsSimple ( xmpFlags ) ) continue; // ? Complain? fullValue.append ( itemValue ); fullValue.append ( 1, '\x0' ); } } tiff->SetTag ( ifd, id, kTIFF_ASCIIType, (XMP_Uns32)fullValue.size(), fullValue.c_str() ); // ! Already have trailing nul. } catch ( ... ) { } } // ExportTIFF_ArrayASCII Commit Message: CWE ID: CWE-416
0
15,945
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 socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); percpu_add(sockets_in_use, 1); return sock; } Commit Message: sendmmsg/sendmsg: fix unsafe user pointer access Dereferencing a user pointer directly from kernel-space without going through the copy_from_user family of functions is a bad idea. Two of such usages can be found in the sendmsg code path called from sendmmsg, added by commit c71d8ebe7a4496fb7231151cb70a6baa0cb56f9a upstream. commit 5b47b8038f183b44d2d8ff1c7d11a5c1be706b34 in the 3.0-stable tree. Usages are performed through memcmp() and memcpy() directly. Fix those by using the already copied msg_sys structure instead of the __user *msg structure. Note that msg_sys can be set to NULL by verify_compat_iovec() or verify_iovec(), which requires additional NULL pointer checks. Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Signed-off-by: David Goulet <dgoulet@ev0ke.net> CC: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> CC: Anton Blanchard <anton@samba.org> CC: David S. Miller <davem@davemloft.net> CC: stable <stable@kernel.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
22,731
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 RenderMessageFilter::OnGetCookies(const GURL& url, const GURL& first_party_for_cookies, IPC::Message* reply_msg) { ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (!policy->CanAccessCookiesForOrigin(render_process_id_, url)) { SendGetCookiesResponse(reply_msg, std::string()); return; } char url_buf[128]; base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf)); base::debug::Alias(url_buf); net::URLRequestContext* context = GetRequestContextForURL(url); net::CookieMonster* cookie_monster = context->cookie_store()->GetCookieMonster(); cookie_monster->GetAllCookiesForURLAsync( url, base::Bind(&RenderMessageFilter::CheckPolicyForCookies, this, url, first_party_for_cookies, reply_msg)); } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
0
116,860
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: u64 snmp_get_cpu_field(void __percpu *mib, int cpu, int offt) { return *(((unsigned long *)per_cpu_ptr(mib, cpu)) + offt); } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <cwang@twopensource.com> Reported-by: 郭永刚 <guoyonggang@360.cn> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
41,553
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 dn_socket_seq_open(struct inode *inode, struct file *file) { return seq_open_private(file, &dn_socket_seq_ops, sizeof(struct dn_iter_state)); } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <cwang@twopensource.com> Reported-by: 郭永刚 <guoyonggang@360.cn> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
41,509
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: xfs_buf_vmap_len( struct xfs_buf *bp) { return (bp->b_page_count * PAGE_SIZE) - bp->b_offset; } Commit Message: xfs: fix _xfs_buf_find oops on blocks beyond the filesystem end When _xfs_buf_find is passed an out of range address, it will fail to find a relevant struct xfs_perag and oops with a null dereference. This can happen when trying to walk a filesystem with a metadata inode that has a partially corrupted extent map (i.e. the block number returned is corrupt, but is otherwise intact) and we try to read from the corrupted block address. In this case, just fail the lookup. If it is readahead being issued, it will simply not be done, but if it is real read that fails we will get an error being reported. Ideally this case should result in an EFSCORRUPTED error being reported, but we cannot return an error through xfs_buf_read() or xfs_buf_get() so this lookup failure may result in ENOMEM or EIO errors being reported instead. Signed-off-by: Dave Chinner <dchinner@redhat.com> Reviewed-by: Brian Foster <bfoster@redhat.com> Reviewed-by: Ben Myers <bpm@sgi.com> Signed-off-by: Ben Myers <bpm@sgi.com> CWE ID: CWE-20
0
33,236
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: connection_edge_update_circuit_isolation(const entry_connection_t *conn, origin_circuit_t *circ, int dry_run) { const socks_request_t *sr = conn->socks_request; if (! conn->original_dest_address) { log_warn(LD_BUG, "Reached connection_update_circuit_isolation without " "having set conn->original_dest_address"); ((entry_connection_t*)conn)->original_dest_address = tor_strdup(conn->socks_request->address); } if (!circ->isolation_values_set) { if (dry_run) return -1; circ->associated_isolated_stream_global_id = ENTRY_TO_CONN(conn)->global_identifier; circ->dest_port = conn->socks_request->port; circ->dest_address = tor_strdup(conn->original_dest_address); circ->client_proto_type = conn->socks_request->listener_type; circ->client_proto_socksver = conn->socks_request->socks_version; tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr); circ->session_group = conn->entry_cfg.session_group; circ->nym_epoch = conn->nym_epoch; circ->socks_username = sr->username ? tor_memdup(sr->username, sr->usernamelen) : NULL; circ->socks_password = sr->password ? tor_memdup(sr->password, sr->passwordlen) : NULL; circ->socks_username_len = sr->usernamelen; circ->socks_password_len = sr->passwordlen; circ->isolation_values_set = 1; return 0; } else { uint8_t mixed = 0; if (conn->socks_request->port != circ->dest_port) mixed |= ISO_DESTPORT; if (strcasecmp(conn->original_dest_address, circ->dest_address)) mixed |= ISO_DESTADDR; if (!memeq_opt(sr->username, sr->usernamelen, circ->socks_username, circ->socks_username_len) || !memeq_opt(sr->password, sr->passwordlen, circ->socks_password, circ->socks_password_len)) mixed |= ISO_SOCKSAUTH; if ((conn->socks_request->listener_type != circ->client_proto_type || conn->socks_request->socks_version != circ->client_proto_socksver)) mixed |= ISO_CLIENTPROTO; if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr)) mixed |= ISO_CLIENTADDR; if (conn->entry_cfg.session_group != circ->session_group) mixed |= ISO_SESSIONGRP; if (conn->nym_epoch != circ->nym_epoch) mixed |= ISO_NYM_EPOCH; if (dry_run) return mixed; if ((mixed & conn->entry_cfg.isolation_flags) != 0) { log_warn(LD_BUG, "Updating a circuit with seemingly incompatible " "isolation flags."); } circ->isolation_flags_mixed |= mixed; return 0; } } Commit Message: TROVE-2017-004: Fix assertion failure in relay_send_end_cell_from_edge_ This fixes an assertion failure in relay_send_end_cell_from_edge_() when an origin circuit and a cpath_layer = NULL were passed. A service rendezvous circuit could do such a thing when a malformed BEGIN cell is received but shouldn't in the first place because the service needs to send an END cell on the circuit for which it can not do without a cpath_layer. Fixes #22493 Reported-by: Roger Dingledine <arma@torproject.org> Signed-off-by: David Goulet <dgoulet@torproject.org> CWE ID: CWE-617
0
69,920
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 nl80211_connect(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct cfg80211_connect_params connect; struct wiphy *wiphy; struct cfg80211_cached_keys *connkeys = NULL; int err; memset(&connect, 0, sizeof(connect)); if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE])) return -EINVAL; if (!info->attrs[NL80211_ATTR_SSID] || !nla_len(info->attrs[NL80211_ATTR_SSID])) return -EINVAL; if (info->attrs[NL80211_ATTR_AUTH_TYPE]) { connect.auth_type = nla_get_u32(info->attrs[NL80211_ATTR_AUTH_TYPE]); if (!nl80211_valid_auth_type(connect.auth_type)) return -EINVAL; } else connect.auth_type = NL80211_AUTHTYPE_AUTOMATIC; connect.privacy = info->attrs[NL80211_ATTR_PRIVACY]; err = nl80211_crypto_settings(rdev, info, &connect.crypto, NL80211_MAX_NR_CIPHER_SUITES); if (err) return err; if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION && dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT) return -EOPNOTSUPP; wiphy = &rdev->wiphy; if (info->attrs[NL80211_ATTR_MAC]) connect.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]); connect.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]); connect.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]); if (info->attrs[NL80211_ATTR_IE]) { connect.ie = nla_data(info->attrs[NL80211_ATTR_IE]); connect.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); } if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) { connect.channel = ieee80211_get_channel(wiphy, nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ])); if (!connect.channel || connect.channel->flags & IEEE80211_CHAN_DISABLED) return -EINVAL; } if (connect.privacy && info->attrs[NL80211_ATTR_KEYS]) { connkeys = nl80211_parse_connkeys(rdev, info->attrs[NL80211_ATTR_KEYS]); if (IS_ERR(connkeys)) return PTR_ERR(connkeys); } err = cfg80211_connect(rdev, dev, &connect, connkeys); if (err) kfree(connkeys); return err; } Commit Message: nl80211: fix check for valid SSID size in scan operations In both trigger_scan and sched_scan operations, we were checking for the SSID length before assigning the value correctly. Since the memory was just kzalloc'ed, the check was always failing and SSID with over 32 characters were allowed to go through. This was causing a buffer overflow when copying the actual SSID to the proper place. This bug has been there since 2.6.29-rc4. Cc: stable@kernel.org Signed-off-by: Luciano Coelho <coelho@ti.com> Signed-off-by: John W. Linville <linville@tuxdriver.com> CWE ID: CWE-119
0
26,668
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::GrantPermissionsAndEnableExtension( const Extension* extension) { CHECK(extension); RecordPermissionMessagesHistogram( extension, "Extensions.Permissions_ReEnable"); GrantPermissions(extension); extension_prefs_->SetDidExtensionEscalatePermissions(extension, false); EnableExtension(extension->id()); } 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
98,592
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 ShellSurface::SetPinned(bool pinned) { TRACE_EVENT1("exo", "ShellSurface::SetPinned", "pinned", pinned); if (!widget_) CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL); ScopedConfigure scoped_configure(this, true); if (pinned) { ash::wm::PinWindow(widget_->GetNativeWindow()); } else { if (ash::wm::GetWindowState(widget_->GetNativeWindow())->IsPinned()) widget_->Restore(); } } Commit Message: exo: Reduce side-effects of dynamic activation code. This code exists for clients that need to managed their own system modal dialogs. Since the addition of the remote surface API we can limit the impact of this to surfaces created for system modal container. BUG=29528396 Review-Url: https://codereview.chromium.org/2084023003 Cr-Commit-Position: refs/heads/master@{#401115} CWE ID: CWE-416
0
120,098
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 ParamTraits<gfx::Rect>::Write(Message* m, const gfx::Rect& p) { m->WriteInt(p.x()); m->WriteInt(p.y()); m->WriteInt(p.width()); m->WriteInt(p.height()); } Commit Message: Beware of print-read inconsistency when serializing GURLs. BUG=165622 Review URL: https://chromiumcodereview.appspot.com/11576038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173583 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
117,477
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: choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server) { char *name = match_list(client, server, NULL); if (name == NULL) return SSH_ERR_NO_MAC_ALG_MATCH; if (mac_setup(mac, name) < 0) return SSH_ERR_INTERNAL_ERROR; /* truncate the key */ if (ssh->compat & SSH_BUG_HMAC) mac->key_len = 16; mac->name = name; mac->key = NULL; mac->enabled = 0; return 0; } Commit Message: CWE ID: CWE-476
0
17,944
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 queue_file(char *pathname, int file_fd, struct inode *inode) { struct squashfs_file *file = malloc(sizeof(struct squashfs_file)); if(file == NULL) EXIT_UNSQUASH("queue_file: unable to malloc file\n"); file->fd = file_fd; file->file_size = inode->data; file->mode = inode->mode; file->gid = inode->gid; file->uid = inode->uid; file->time = inode->time; file->pathname = strdup(pathname); file->blocks = inode->blocks + (inode->frag_bytes > 0); file->sparse = inode->sparse; file->xattr = inode->xattr; queue_put(to_writer, file); } Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6 Add more filesystem table sanity checks to Unsquashfs-4 and also properly fix CVE-2015-4645 and CVE-2015-4646. The CVEs were raised due to Unsquashfs having variable oveflow and stack overflow in a number of vulnerable functions. The suggested patch only "fixed" one such function and fixed it badly, and so it was buggy and introduced extra bugs! The suggested patch was not only buggy, but, it used the essentially wrong approach too. It was "fixing" the symptom but not the cause. The symptom is wrong values causing overflow, the cause is filesystem corruption. This corruption should be detected and the filesystem rejected *before* trying to allocate memory. This patch applies the following fixes: 1. The filesystem super-block tables are checked, and the values must match across the filesystem. This will trap corrupted filesystems created by Mksquashfs. 2. The maximum (theorectical) size the filesystem tables could grow to, were analysed, and some variables were increased from int to long long. This analysis has been added as comments. 3. Stack allocation was removed, and a shared buffer (which is checked and increased as necessary) is used to read the table indexes. Signed-off-by: Phillip Lougher <phillip@squashfs.org.uk> CWE ID: CWE-190
0
74,291
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: INST_HANDLER (bld) { // BLD Rd, b if (len < 2) { return; } int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf); int b = buf[0] & 0x7; ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0 ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b } Commit Message: Fix #9943 - Invalid free on RAnal.avr CWE ID: CWE-416
0
82,703
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: acpi_status acpi_os_delete_cache(acpi_cache_t * cache) { kmem_cache_destroy(cache); return (AE_OK); } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <linn@hpe.com> CWE ID: CWE-264
0
53,836
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 long BlockGroup::GetPrevTimeCode() const { return m_prev; } 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
0
160,793
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 PluginServiceImpl::GetPluginInfoByPath(const FilePath& plugin_path, webkit::WebPluginInfo* info) { std::vector<webkit::WebPluginInfo> plugins; plugin_list_->GetPluginsNoRefresh(&plugins); for (std::vector<webkit::WebPluginInfo>::iterator it = plugins.begin(); it != plugins.end(); ++it) { if (it->path == plugin_path) { *info = *it; return true; } } return false; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
0
116,781
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 WebGL2RenderingContextBase::beginQuery(GLenum target, WebGLQuery* query) { bool deleted; DCHECK(query); if (!CheckObjectToBeBound("beginQuery", query, deleted)) return; if (deleted) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "attempted to begin a deleted query object"); return; } if (query->GetTarget() && query->GetTarget() != target) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "query type does not match target"); return; } switch (target) { case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: { if (current_boolean_occlusion_query_) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "a query is already active for target"); return; } current_boolean_occlusion_query_ = query; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: { if (current_transform_feedback_primitives_written_query_) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "a query is already active for target"); return; } current_transform_feedback_primitives_written_query_ = query; } break; case GL_TIME_ELAPSED_EXT: { if (!ExtensionEnabled(kEXTDisjointTimerQueryWebGL2Name)) { SynthesizeGLError(GL_INVALID_ENUM, "beginQuery", "invalid target"); return; } if (current_elapsed_query_) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "a query is already active for target"); return; } current_elapsed_query_ = query; } break; default: SynthesizeGLError(GL_INVALID_ENUM, "beginQuery", "invalid target"); return; } if (!query->GetTarget()) query->SetTarget(target); ContextGL()->BeginQueryEXT(target, query->Object()); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
0
133,365
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 WebMediaPlayerImpl::OnOverlayInfoRequested( bool decoder_requires_restart_for_overlay, const ProvideOverlayInfoCB& provide_overlay_info_cb) { DCHECK(main_task_runner_->BelongsToCurrentThread()); if (!provide_overlay_info_cb) { decoder_requires_restart_for_overlay_ = false; provide_overlay_info_cb_.Reset(); return; } decoder_requires_restart_for_overlay_ = (overlay_mode_ == OverlayMode::kUseAndroidOverlay && is_encrypted_) ? false : decoder_requires_restart_for_overlay; provide_overlay_info_cb_ = provide_overlay_info_cb; if (overlay_mode_ == OverlayMode::kUseAndroidOverlay && !decoder_requires_restart_for_overlay_) { always_enable_overlays_ = true; if (!overlay_enabled_) EnableOverlay(); } MaybeSendOverlayInfoToDecoder(); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <hubbe@chromium.org> Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Reviewed-by: Raymond Toy <rtoy@chromium.org> Commit-Queue: Yutaka Hirano <yhirano@chromium.org> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
0
144,456
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 rewriteClientCommandVector(client *c, int argc, ...) { va_list ap; int j; robj **argv; /* The new argument vector */ argv = zmalloc(sizeof(robj*)*argc); va_start(ap,argc); for (j = 0; j < argc; j++) { robj *a; a = va_arg(ap, robj*); argv[j] = a; incrRefCount(a); } /* We free the objects in the original vector at the end, so we are * sure that if the same objects are reused in the new vector the * refcount gets incremented before it gets decremented. */ for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); zfree(c->argv); /* Replace argv and argc with our new versions. */ c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); va_end(ap); } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. CWE ID: CWE-254
0
69,984
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 bool __follow_mount_rcu(struct nameidata *nd, struct path *path, struct inode **inode, unsigned *seqp) { for (;;) { struct mount *mounted; /* * Don't forget we might have a non-mountpoint managed dentry * that wants to block transit. */ switch (managed_dentry_rcu(path)) { case -ECHILD: default: return false; case -EISDIR: return true; case 0: break; } if (!d_mountpoint(path->dentry)) return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT); mounted = __lookup_mnt(path->mnt, path->dentry); if (!mounted) break; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |= LOOKUP_JUMPED; *seqp = read_seqcount_begin(&path->dentry->d_seq); /* * Update the inode too. We don't need to re-check the * dentry sequence number here after this d_inode read, * because a mount-point is always pinned. */ *inode = path->dentry->d_inode; } return !read_seqretry(&mount_lock, nd->m_seq) && !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT); } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-362
0
67,409
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 acct_update_position(QEMUFile *f, size_t size, bool zero) { uint64_t pages = size / TARGET_PAGE_SIZE; if (zero) { acct_info.dup_pages += pages; } else { acct_info.norm_pages += pages; bytes_transferred += size; qemu_update_position(f, size); } } Commit Message: CWE ID: CWE-20
0
7,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: int pm_get_counters(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) { fm_mgr_config_errno_t res; fm_msg_ret_code_t ret_code; uint8_t data[BUF_SZ]; time_t timeNow; if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_PM_GET_COUNTERS, mgr, BUF_SZ, data, &ret_code)) != FM_CONF_OK) { fprintf(stderr, "pm_get_counters: Failed to retrieve data: \n" "\tError:(%d) %s \n\tRet code:(%d) %s\n", res, fm_mgr_get_error_str(res),ret_code, fm_mgr_get_resp_error_str(ret_code)); } else { time(&timeNow); data[BUF_SZ-1]=0; printf("PM Counters as of %s%s", ctime(&timeNow), (char*) data); } return 0; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362
0
96,193
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: init_stringbuf (struct stringbuf *sb, int initiallen) { sb->len = 0; sb->size = initiallen; sb->out_of_core = 0; /* allocate one more, so that get_stringbuf can append a nul */ sb->buf = xtrymalloc (initiallen+1); if (!sb->buf) sb->out_of_core = 1; } Commit Message: CWE ID: CWE-119
0
11,015
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 cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) { if ((input_buffer == NULL) || (input_buffer->content == NULL)) { return false; /* no input */ } /* parse the different types of values */ /* null */ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) { item->type = cJSON_NULL; input_buffer->offset += 4; return true; } /* false */ if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) { item->type = cJSON_False; input_buffer->offset += 5; return true; } /* true */ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) { item->type = cJSON_True; item->valueint = 1; input_buffer->offset += 4; return true; } /* string */ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) { return parse_string(item, input_buffer); } /* number */ if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) { return parse_number(item, input_buffer); } /* array */ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) { return parse_array(item, input_buffer); } /* object */ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) { return parse_object(item, input_buffer); } return false; } /* Render a value to text. */ static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) { unsigned char *output = NULL; if ((item == NULL) || (output_buffer == NULL)) { return false; } switch ((item->type) & 0xFF) { case cJSON_NULL: output = ensure(output_buffer, 5); if (output == NULL) { return false; } strcpy((char*)output, "null"); return true; case cJSON_False: output = ensure(output_buffer, 6); if (output == NULL) { return false; } strcpy((char*)output, "false"); return true; case cJSON_True: output = ensure(output_buffer, 5); if (output == NULL) { return false; } strcpy((char*)output, "true"); return true; case cJSON_Number: return print_number(item, output_buffer); case cJSON_Raw: { size_t raw_length = 0; if (item->valuestring == NULL) { return false; } raw_length = strlen(item->valuestring) + sizeof(""); output = ensure(output_buffer, raw_length); if (output == NULL) { return false; } memcpy(output, item->valuestring, raw_length); return true; } case cJSON_String: return print_string(item, output_buffer); case cJSON_Array: return print_array(item, output_buffer); case cJSON_Object: return print_object(item, output_buffer); default: return false; } } /* Build an array from input text. */ static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) { cJSON *head = NULL; /* head of the linked list */ cJSON *current_item = NULL; if (input_buffer->depth >= CJSON_NESTING_LIMIT) { return false; /* to deeply nested */ } input_buffer->depth++; if (buffer_at_offset(input_buffer)[0] != '[') { /* not an array */ goto fail; } input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) { /* empty array */ goto success; } /* check if we skipped to the end of the buffer */ if (cannot_access_at_index(input_buffer, 0)) { input_buffer->offset--; goto fail; } /* step back to character in front of the first element */ input_buffer->offset--; /* loop through the comma separated array elements */ do { /* allocate next item */ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); if (new_item == NULL) { goto fail; /* allocation failure */ } /* attach next item to list */ if (head == NULL) { /* start the linked list */ current_item = head = new_item; } else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; current_item = new_item; } /* parse next value */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (!parse_value(current_item, input_buffer)) { goto fail; /* failed to parse value */ } buffer_skip_whitespace(input_buffer); } while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') { goto fail; /* expected end of array */ } success: input_buffer->depth--; item->type = cJSON_Array; item->child = head; input_buffer->offset++; return true; fail: if (head != NULL) { cJSON_Delete(head); } return false; } /* Render an array to text */ static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) { unsigned char *output_pointer = NULL; size_t length = 0; cJSON *current_element = item->child; if (output_buffer == NULL) { return false; } /* Compose the output array. */ /* opening square bracket */ output_pointer = ensure(output_buffer, 1); if (output_pointer == NULL) { return false; } *output_pointer = '['; output_buffer->offset++; output_buffer->depth++; while (current_element != NULL) { if (!print_value(current_element, output_buffer)) { return false; } update_offset(output_buffer); if (current_element->next) { length = (size_t) (output_buffer->format ? 2 : 1); output_pointer = ensure(output_buffer, length + 1); if (output_pointer == NULL) { return false; } *output_pointer++ = ','; if(output_buffer->format) { *output_pointer++ = ' '; } *output_pointer = '\0'; output_buffer->offset += length; } current_element = current_element->next; } output_pointer = ensure(output_buffer, 2); if (output_pointer == NULL) { return false; } *output_pointer++ = ']'; *output_pointer = '\0'; output_buffer->depth--; return true; } /* Build an object from the text. */ static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) { cJSON *head = NULL; /* linked list head */ cJSON *current_item = NULL; if (input_buffer->depth >= CJSON_NESTING_LIMIT) { return false; /* to deeply nested */ } input_buffer->depth++; if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) { goto fail; /* not an object */ } input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) { goto success; /* empty object */ } /* check if we skipped to the end of the buffer */ if (cannot_access_at_index(input_buffer, 0)) { input_buffer->offset--; goto fail; } /* step back to character in front of the first element */ input_buffer->offset--; /* loop through the comma separated array elements */ do { /* allocate next item */ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); if (new_item == NULL) { goto fail; /* allocation failure */ } /* attach next item to list */ if (head == NULL) { /* start the linked list */ current_item = head = new_item; } else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; current_item = new_item; } /* parse the name of the child */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (!parse_string(current_item, input_buffer)) { goto fail; /* faile to parse name */ } buffer_skip_whitespace(input_buffer); /* swap valuestring and string, because we parsed the name */ current_item->string = current_item->valuestring; current_item->valuestring = NULL; if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) { goto fail; /* invalid object */ } /* parse the value */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (!parse_value(current_item, input_buffer)) { goto fail; /* failed to parse value */ } buffer_skip_whitespace(input_buffer); } while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) { goto fail; /* expected end of object */ } success: input_buffer->depth--; item->type = cJSON_Object; item->child = head; input_buffer->offset++; return true; fail: if (head != NULL) { cJSON_Delete(head); } return false; } Commit Message: Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays CWE ID: CWE-754
0
87,161
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 sane_signal_32_frame(unsigned int sp) { struct signal_frame_32 __user *sf; unsigned int regs; sf = (struct signal_frame_32 __user *) (unsigned long) sp; if (read_user_stack_32((unsigned int __user *) &sf->sctx.regs, &regs)) return 0; return regs == (unsigned long) &sf->mctx; } Commit Message: powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH We cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH (currently 127), but we forgot to do the same for 64bit backtraces. Cc: stable@vger.kernel.org Signed-off-by: Anton Blanchard <anton@samba.org> Signed-off-by: Michael Ellerman <mpe@ellerman.id.au> CWE ID: CWE-399
0
42,187
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: nfsd4_encode_security_label(struct xdr_stream *xdr, struct svc_rqst *rqstp, void *context, int len) { __be32 *p; p = xdr_reserve_space(xdr, len + 4 + 4 + 4); if (!p) return nfserr_resource; /* * For now we use a 0 here to indicate the null translation; in * the future we may place a call to translation code here. */ *p++ = cpu_to_be32(0); /* lfs */ *p++ = cpu_to_be32(0); /* pi */ p = xdr_encode_opaque(p, context, len); return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
0
65,832
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 WebContext::setSessionCookieMode(SessionCookieMode mode) { DCHECK(!IsInitialized()); construct_props_->session_cookie_mode = static_cast<content::CookieStoreConfig::SessionCookieMode>(mode); } Commit Message: CWE ID: CWE-20
0
17,013
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: argnum_error(mrb_state *mrb, mrb_int num) { mrb_value exc; mrb_value str; mrb_int argc = mrb->c->ci->argc; if (argc < 0) { mrb_value args = mrb->c->stack[1]; if (mrb_array_p(args)) { argc = RARRAY_LEN(args); } } if (mrb->c->ci->mid) { str = mrb_format(mrb, "'%S': wrong number of arguments (%S for %S)", mrb_sym2str(mrb, mrb->c->ci->mid), mrb_fixnum_value(argc), mrb_fixnum_value(num)); } else { str = mrb_format(mrb, "wrong number of arguments (%S for %S)", mrb_fixnum_value(argc), mrb_fixnum_value(num)); } exc = mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str); mrb_exc_set(mrb, exc); } Commit Message: Check length of env stack before accessing upvar; fix #3995 CWE ID: CWE-190
0
83,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: static void put_mspel8_mc10_c(uint8_t *dst, uint8_t *src, ptrdiff_t stride) { uint8_t half[64]; wmv2_mspel8_h_lowpass(half, src, 8, stride, 8); put_pixels8_l2_8(dst, src, half, stride, stride, 8, 8); } Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-189
0
28,158
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 CALLBACK WinMain(HINSTANCE instance, HINSTANCE previous_instance, LPSTR command_line, int show_command) { #ifdef OFFICIAL_BUILD if (remoting::IsUsageStatsAllowed()) { remoting::InitializeCrashReporting(); } #endif // OFFICIAL_BUILD g_hModule = instance; INITCOMMONCONTROLSEX info; info.dwSize = sizeof(info); info.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&info); if (base::win::GetVersion() >= base::win::VERSION_VISTA) { FilePath path(base::GetNativeLibraryName(UTF8ToUTF16("user32"))); base::ScopedNativeLibrary user32(path); CHECK(user32.is_valid()); typedef BOOL (WINAPI * SetProcessDPIAwareFn)(); SetProcessDPIAwareFn set_process_dpi_aware = static_cast<SetProcessDPIAwareFn>( user32.GetFunctionPointer("SetProcessDPIAware")); set_process_dpi_aware(); } return main(0, NULL); } Commit Message: Fix crash in CreateAuthenticatorFactory(). CreateAuthenticatorFactory() is called asynchronously, but it didn't handle the case when it's called after host object is destroyed. BUG=150644 Review URL: https://codereview.chromium.org/11090036 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161077 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
113,696
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 WebGL2RenderingContextBase::uniformMatrix2x4fv( const WebGLUniformLocation* location, GLboolean transpose, Vector<GLfloat>& value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix2x4fv", location, transpose, value.data(), value.size(), 8, src_offset, src_length)) return; ContextGL()->UniformMatrix2x4fv( location->Location(), (src_length ? src_length : (value.size() - src_offset)) >> 3, transpose, value.data() + src_offset); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
0
133,542
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 do_fetch(pdo_stmt_t *stmt, int do_bind, zval *return_value, enum pdo_fetch_type how, enum pdo_fetch_orientation ori, long offset, zval *return_all TSRMLS_DC) /* {{{ */ { int flags, idx, old_arg_count = 0; zend_class_entry *ce = NULL, *old_ce = NULL; zval grp_val, *grp, **pgrp, *retval, *old_ctor_args = NULL; int colno; if (how == PDO_FETCH_USE_DEFAULT) { how = stmt->default_fetch_type; } flags = how & PDO_FETCH_FLAGS; how = how & ~PDO_FETCH_FLAGS; if (!do_fetch_common(stmt, ori, offset, do_bind TSRMLS_CC)) { return 0; } if (how == PDO_FETCH_BOUND) { RETVAL_TRUE; return 1; } if (flags & PDO_FETCH_GROUP && stmt->fetch.column == -1) { colno = 1; } else { colno = stmt->fetch.column; } if (return_value) { int i = 0; if (how == PDO_FETCH_LAZY) { get_lazy_object(stmt, return_value TSRMLS_CC); return 1; } RETVAL_FALSE; switch (how) { case PDO_FETCH_USE_DEFAULT: case PDO_FETCH_ASSOC: case PDO_FETCH_BOTH: case PDO_FETCH_NUM: case PDO_FETCH_NAMED: if (!return_all) { ALLOC_HASHTABLE(return_value->value.ht); zend_hash_init(return_value->value.ht, stmt->column_count, NULL, ZVAL_PTR_DTOR, 0); Z_TYPE_P(return_value) = IS_ARRAY; } else { array_init(return_value); } break; case PDO_FETCH_KEY_PAIR: if (stmt->column_count != 2) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO::FETCH_KEY_PAIR fetch mode requires the result set to contain extactly 2 columns." TSRMLS_CC); return 0; } if (!return_all) { array_init(return_value); } break; case PDO_FETCH_COLUMN: if (colno >= 0 && colno < stmt->column_count) { if (flags == PDO_FETCH_GROUP && stmt->fetch.column == -1) { fetch_value(stmt, return_value, 1, NULL TSRMLS_CC); } else if (flags == PDO_FETCH_GROUP && colno) { fetch_value(stmt, return_value, 0, NULL TSRMLS_CC); } else { fetch_value(stmt, return_value, colno, NULL TSRMLS_CC); } if (!return_all) { return 1; } else { break; } } else { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "Invalid column index" TSRMLS_CC); } return 0; case PDO_FETCH_OBJ: object_init_ex(return_value, ZEND_STANDARD_CLASS_DEF_PTR); break; case PDO_FETCH_CLASS: if (flags & PDO_FETCH_CLASSTYPE) { zval val; zend_class_entry **cep; old_ce = stmt->fetch.cls.ce; old_ctor_args = stmt->fetch.cls.ctor_args; old_arg_count = stmt->fetch.cls.fci.param_count; do_fetch_opt_finish(stmt, 0 TSRMLS_CC); INIT_PZVAL(&val); fetch_value(stmt, &val, i++, NULL TSRMLS_CC); if (Z_TYPE(val) != IS_NULL) { convert_to_string(&val); if (zend_lookup_class(Z_STRVAL(val), Z_STRLEN(val), &cep TSRMLS_CC) == FAILURE) { stmt->fetch.cls.ce = ZEND_STANDARD_CLASS_DEF_PTR; } else { stmt->fetch.cls.ce = *cep; } } do_fetch_class_prepare(stmt TSRMLS_CC); zval_dtor(&val); } ce = stmt->fetch.cls.ce; if (!ce) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "No fetch class specified" TSRMLS_CC); return 0; } if ((flags & PDO_FETCH_SERIALIZE) == 0) { object_init_ex(return_value, ce); if (!stmt->fetch.cls.fci.size) { if (!do_fetch_class_prepare(stmt TSRMLS_CC)) { return 0; } } if (ce->constructor && (flags & PDO_FETCH_PROPS_LATE)) { stmt->fetch.cls.fci.object_ptr = return_value; stmt->fetch.cls.fcc.object_ptr = return_value; if (zend_call_function(&stmt->fetch.cls.fci, &stmt->fetch.cls.fcc TSRMLS_CC) == FAILURE) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not call class constructor" TSRMLS_CC); return 0; } else { if (stmt->fetch.cls.retval_ptr) { zval_ptr_dtor(&stmt->fetch.cls.retval_ptr); } } } } break; case PDO_FETCH_INTO: if (!stmt->fetch.into) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "No fetch-into object specified." TSRMLS_CC); return 0; break; } Z_TYPE_P(return_value) = IS_OBJECT; Z_OBJ_HANDLE_P(return_value) = Z_OBJ_HANDLE_P(stmt->fetch.into); Z_OBJ_HT_P(return_value) = Z_OBJ_HT_P(stmt->fetch.into); zend_objects_store_add_ref(stmt->fetch.into TSRMLS_CC); if (zend_get_class_entry(return_value TSRMLS_CC) == ZEND_STANDARD_CLASS_DEF_PTR) { how = PDO_FETCH_OBJ; } break; case PDO_FETCH_FUNC: if (!stmt->fetch.func.function) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "No fetch function specified" TSRMLS_CC); return 0; } if (!stmt->fetch.func.fci.size) { if (!do_fetch_func_prepare(stmt TSRMLS_CC)) { return 0; } } break; default: /* shouldn't happen */ return 0; } if (return_all && how != PDO_FETCH_KEY_PAIR) { INIT_PZVAL(&grp_val); if (flags == PDO_FETCH_GROUP && how == PDO_FETCH_COLUMN && stmt->fetch.column > 0) { fetch_value(stmt, &grp_val, colno, NULL TSRMLS_CC); } else { fetch_value(stmt, &grp_val, i, NULL TSRMLS_CC); } convert_to_string(&grp_val); if (how == PDO_FETCH_COLUMN) { i = stmt->column_count; /* no more data to fetch */ } else { i++; } } for (idx = 0; i < stmt->column_count; i++, idx++) { zval *val; MAKE_STD_ZVAL(val); fetch_value(stmt, val, i, NULL TSRMLS_CC); switch (how) { case PDO_FETCH_ASSOC: add_assoc_zval(return_value, stmt->columns[i].name, val); break; case PDO_FETCH_KEY_PAIR: { zval *tmp; MAKE_STD_ZVAL(tmp); fetch_value(stmt, tmp, ++i, NULL TSRMLS_CC); if (Z_TYPE_P(val) == IS_LONG) { zend_hash_index_update((return_all ? Z_ARRVAL_P(return_all) : Z_ARRVAL_P(return_value)), Z_LVAL_P(val), &tmp, sizeof(zval *), NULL); } else { convert_to_string(val); zend_symtable_update((return_all ? Z_ARRVAL_P(return_all) : Z_ARRVAL_P(return_value)), Z_STRVAL_P(val), Z_STRLEN_P(val) + 1, &tmp, sizeof(zval *), NULL); } zval_ptr_dtor(&val); return 1; } break; case PDO_FETCH_USE_DEFAULT: case PDO_FETCH_BOTH: add_assoc_zval(return_value, stmt->columns[i].name, val); Z_ADDREF_P(val); add_next_index_zval(return_value, val); break; case PDO_FETCH_NAMED: /* already have an item with this name? */ { zval **curr_val = NULL; if (zend_hash_find(Z_ARRVAL_P(return_value), stmt->columns[i].name, strlen(stmt->columns[i].name)+1, (void**)&curr_val) == SUCCESS) { zval *arr; if (Z_TYPE_PP(curr_val) != IS_ARRAY) { /* a little bit of black magic here: * we're creating a new array and swapping it for the * zval that's already stored in the hash under the name * we want. We then add that zval to the array. * This is effectively the same thing as: * if (!is_array($hash[$name])) { * $hash[$name] = array($hash[$name]); * } * */ zval *cur; MAKE_STD_ZVAL(arr); array_init(arr); cur = *curr_val; *curr_val = arr; add_next_index_zval(arr, cur); } else { arr = *curr_val; } add_next_index_zval(arr, val); } else { add_assoc_zval(return_value, stmt->columns[i].name, val); } } break; case PDO_FETCH_NUM: add_next_index_zval(return_value, val); break; case PDO_FETCH_OBJ: case PDO_FETCH_INTO: zend_update_property(NULL, return_value, stmt->columns[i].name, stmt->columns[i].namelen, val TSRMLS_CC); zval_ptr_dtor(&val); break; case PDO_FETCH_CLASS: if ((flags & PDO_FETCH_SERIALIZE) == 0 || idx) { zend_update_property(ce, return_value, stmt->columns[i].name, stmt->columns[i].namelen, val TSRMLS_CC); zval_ptr_dtor(&val); } else { #ifdef MBO_0 php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (php_var_unserialize(&return_value, (const unsigned char**)&Z_STRVAL_P(val), Z_STRVAL_P(val)+Z_STRLEN_P(val), NULL TSRMLS_CC) == FAILURE) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "cannot unserialize data" TSRMLS_CC); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return 0; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); #endif if (!ce->unserialize) { zval_ptr_dtor(&val); pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "cannot unserialize class" TSRMLS_CC); return 0; } else if (ce->unserialize(&return_value, ce, (unsigned char *)(Z_TYPE_P(val) == IS_STRING ? Z_STRVAL_P(val) : ""), Z_TYPE_P(val) == IS_STRING ? Z_STRLEN_P(val) : 0, NULL TSRMLS_CC) == FAILURE) { zval_ptr_dtor(&val); pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "cannot unserialize class" TSRMLS_CC); zval_dtor(return_value); ZVAL_NULL(return_value); return 0; } else { zval_ptr_dtor(&val); } } break; case PDO_FETCH_FUNC: stmt->fetch.func.values[idx] = val; stmt->fetch.cls.fci.params[idx] = &stmt->fetch.func.values[idx]; break; default: zval_ptr_dtor(&val); pdo_raise_impl_error(stmt->dbh, stmt, "22003", "mode is out of range" TSRMLS_CC); return 0; break; } } switch (how) { case PDO_FETCH_CLASS: if (ce->constructor && !(flags & (PDO_FETCH_PROPS_LATE | PDO_FETCH_SERIALIZE))) { stmt->fetch.cls.fci.object_ptr = return_value; stmt->fetch.cls.fcc.object_ptr = return_value; if (zend_call_function(&stmt->fetch.cls.fci, &stmt->fetch.cls.fcc TSRMLS_CC) == FAILURE) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not call class constructor" TSRMLS_CC); return 0; } else { if (stmt->fetch.cls.retval_ptr) { zval_ptr_dtor(&stmt->fetch.cls.retval_ptr); } } } if (flags & PDO_FETCH_CLASSTYPE) { do_fetch_opt_finish(stmt, 0 TSRMLS_CC); stmt->fetch.cls.ce = old_ce; stmt->fetch.cls.ctor_args = old_ctor_args; stmt->fetch.cls.fci.param_count = old_arg_count; } break; case PDO_FETCH_FUNC: stmt->fetch.func.fci.param_count = idx; stmt->fetch.func.fci.retval_ptr_ptr = &retval; if (zend_call_function(&stmt->fetch.func.fci, &stmt->fetch.func.fcc TSRMLS_CC) == FAILURE) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "could not call user-supplied function" TSRMLS_CC); return 0; } else { if (return_all) { zval_ptr_dtor(&return_value); /* we don't need that */ return_value = retval; } else if (retval) { MAKE_COPY_ZVAL(&retval, return_value); zval_ptr_dtor(&retval); } } while(idx--) { zval_ptr_dtor(&stmt->fetch.func.values[idx]); } break; default: break; } if (return_all) { if ((flags & PDO_FETCH_UNIQUE) == PDO_FETCH_UNIQUE) { add_assoc_zval(return_all, Z_STRVAL(grp_val), return_value); } else { if (zend_symtable_find(Z_ARRVAL_P(return_all), Z_STRVAL(grp_val), Z_STRLEN(grp_val)+1, (void**)&pgrp) == FAILURE) { MAKE_STD_ZVAL(grp); array_init(grp); add_assoc_zval(return_all, Z_STRVAL(grp_val), grp); } else { grp = *pgrp; } add_next_index_zval(grp, return_value); } zval_dtor(&grp_val); } } return 1; } /* }}} */ Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle Proper soltion would be to call serialize/unserialize and deal with the result, but this requires more work that should be done by wddx maintainer (not me). CWE ID: CWE-476
0
72,413
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 RenderFrameHostImpl::DidCommitSameDocumentNavigation( std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> validated_params) { ScopedActiveURL scoped_active_url( validated_params->url, frame_tree_node()->frame_tree()->root()->current_origin()); ScopedCommitStateResetter commit_state_resetter(this); if (!is_active()) return; TRACE_EVENT2("navigation", "RenderFrameHostImpl::DidCommitSameDocumentNavigation", "frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url", validated_params->url.possibly_invalid_spec()); bool is_browser_initiated = same_document_navigation_request_ && (same_document_navigation_request_->commit_params().navigation_token == validated_params->navigation_token); if (!DidCommitNavigationInternal( is_browser_initiated ? std::move(same_document_navigation_request_) : nullptr, validated_params.get(), true /* is_same_document_navigation*/)) { return; } commit_state_resetter.disable(); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
0
139,245
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 WriteMenu(IPC::Message* m, const PP_Flash_Menu* menu) { m->WriteUInt32(menu->count); for (uint32_t i = 0; i < menu->count; ++i) WriteMenuItem(m, menu->items + i); } Commit Message: IPC: defend against excessive number of submenu entries in PPAPI message. BUG=168710 Review URL: https://codereview.chromium.org/11794037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175576 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
115,227
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 hnti_Write(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_write_header(s, bs); } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
0
80,178
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 i2d_X509_fp(FILE *fp, X509 *x509) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509), fp, x509); } Commit Message: Fix various certificate fingerprint issues. By using non-DER or invalid encodings outside the signed portion of a certificate the fingerprint can be changed without breaking the signature. Although no details of the signed portion of the certificate can be changed this can cause problems with some applications: e.g. those using the certificate fingerprint for blacklists. 1. Reject signatures with non zero unused bits. If the BIT STRING containing the signature has non zero unused bits reject the signature. All current signature algorithms require zero unused bits. 2. Check certificate algorithm consistency. Check the AlgorithmIdentifier inside TBS matches the one in the certificate signature. NB: this will result in signature failure errors for some broken certificates. 3. Check DSA/ECDSA signatures use DER. Reencode DSA/ECDSA signatures and compare with the original received signature. Return an error if there is a mismatch. This will reject various cases including garbage after signature (thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS program for discovering this case) and use of BER or invalid ASN.1 INTEGERs (negative or with leading zeroes). CVE-2014-8275 Reviewed-by: Emilia Käsper <emilia@openssl.org> CWE ID: CWE-310
0
94,695
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: struct snd_kcontrol *snd_ctl_new1(const struct snd_kcontrol_new *ncontrol, void *private_data) { struct snd_kcontrol kctl; unsigned int access; if (snd_BUG_ON(!ncontrol || !ncontrol->info)) return NULL; memset(&kctl, 0, sizeof(kctl)); kctl.id.iface = ncontrol->iface; kctl.id.device = ncontrol->device; kctl.id.subdevice = ncontrol->subdevice; if (ncontrol->name) { strlcpy(kctl.id.name, ncontrol->name, sizeof(kctl.id.name)); if (strcmp(ncontrol->name, kctl.id.name) != 0) pr_warn("ALSA: Control name '%s' truncated to '%s'\n", ncontrol->name, kctl.id.name); } kctl.id.index = ncontrol->index; kctl.count = ncontrol->count ? ncontrol->count : 1; access = ncontrol->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE : (ncontrol->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE| SNDRV_CTL_ELEM_ACCESS_VOLATILE| SNDRV_CTL_ELEM_ACCESS_INACTIVE| SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE| SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND| SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK)); kctl.info = ncontrol->info; kctl.get = ncontrol->get; kctl.put = ncontrol->put; kctl.tlv.p = ncontrol->tlv.p; kctl.private_value = ncontrol->private_value; kctl.private_data = private_data; return snd_ctl_new(&kctl, access); } Commit Message: ALSA: control: Handle numid overflow Each control gets automatically assigned its numids when the control is created. The allocation is done by incrementing the numid by the amount of allocated numids per allocation. This means that excessive creation and destruction of controls (e.g. via SNDRV_CTL_IOCTL_ELEM_ADD/REMOVE) can cause the id to eventually overflow. Currently when this happens for the control that caused the overflow kctl->id.numid + kctl->count will also over flow causing it to be smaller than kctl->id.numid. Most of the code assumes that this is something that can not happen, so we need to make sure that it won't happen Signed-off-by: Lars-Peter Clausen <lars@metafoo.de> Acked-by: Jaroslav Kysela <perex@perex.cz> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-189
0
36,480
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 rpc_free(void *buffer) { size_t size; struct rpc_buffer *buf; if (!buffer) return; buf = container_of(buffer, struct rpc_buffer, data); size = buf->len; dprintk("RPC: freeing buffer of size %zu at %p\n", size, buf); if (size <= RPC_BUFFER_MAXSIZE) mempool_free(buf, rpc_buffer_mempool); else kfree(buf); } Commit Message: NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <vvs@sw.ru> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> Cc: stable@kernel.org CWE ID: CWE-399
0
34,959
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 MockWebRTCPeerConnectionHandler::addStream(const WebMediaStreamDescriptor& stream, const WebMediaConstraints&) { m_client->didAddRemoteStream(stream); return true; } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
0
99,425
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: WebFrameLoadType NavigationTypeToLoadType( FrameMsg_Navigate_Type::Value navigation_type, bool should_replace_current_entry, bool has_valid_page_state) { switch (navigation_type) { case FrameMsg_Navigate_Type::RELOAD: case FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL: return WebFrameLoadType::kReload; case FrameMsg_Navigate_Type::RELOAD_BYPASSING_CACHE: return WebFrameLoadType::kReloadBypassingCache; case FrameMsg_Navigate_Type::HISTORY_SAME_DOCUMENT: case FrameMsg_Navigate_Type::HISTORY_DIFFERENT_DOCUMENT: return WebFrameLoadType::kBackForward; case FrameMsg_Navigate_Type::RESTORE: case FrameMsg_Navigate_Type::RESTORE_WITH_POST: if (has_valid_page_state) return WebFrameLoadType::kBackForward; FALLTHROUGH; case FrameMsg_Navigate_Type::SAME_DOCUMENT: case FrameMsg_Navigate_Type::DIFFERENT_DOCUMENT: return should_replace_current_entry ? WebFrameLoadType::kReplaceCurrentItem : WebFrameLoadType::kStandard; default: NOTREACHED(); return WebFrameLoadType::kStandard; } } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
0
139,734
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: PHP_FUNCTION(snmpwalk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_1); } Commit Message: CWE ID: CWE-20
0
11,197
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 OnSyntheticGestureSent() { gesture_run_loop_ = std::make_unique<base::RunLoop>(); gesture_run_loop_->Run(); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <creis@chromium.org> Reviewed-by: Nate Chapin <japhet@chromium.org> Commit-Queue: Alex Moshchuk <alexmos@chromium.org> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732
0
143,871
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 sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg) { int ret = sock->ops->sendmsg(sock, msg, msg_data_left(msg)); BUG_ON(ret == -EIOCBQUEUED); return ret; } Commit Message: net: Fix use after free in the recvmmsg exit path The syzkaller fuzzer hit the following use-after-free: Call Trace: [<ffffffff8175ea0e>] __asan_report_load8_noabort+0x3e/0x40 mm/kasan/report.c:295 [<ffffffff851cc31a>] __sys_recvmmsg+0x6fa/0x7f0 net/socket.c:2261 [< inline >] SYSC_recvmmsg net/socket.c:2281 [<ffffffff851cc57f>] SyS_recvmmsg+0x16f/0x180 net/socket.c:2270 [<ffffffff86332bb6>] entry_SYSCALL_64_fastpath+0x16/0x7a arch/x86/entry/entry_64.S:185 And, as Dmitry rightly assessed, that is because we can drop the reference and then touch it when the underlying recvmsg calls return some packets and then hit an error, which will make recvmmsg to set sock->sk->sk_err, oops, fix it. Reported-and-Tested-by: Dmitry Vyukov <dvyukov@google.com> Cc: Alexander Potapenko <glider@google.com> Cc: Eric Dumazet <edumazet@google.com> Cc: Kostya Serebryany <kcc@google.com> Cc: Sasha Levin <sasha.levin@oracle.com> Fixes: a2e2725541fa ("net: Introduce recvmmsg socket syscall") http://lkml.kernel.org/r/20160122211644.GC2470@redhat.com Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-19
0
50,277
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 nl80211_new_interface(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct vif_params params; struct net_device *dev; int err; enum nl80211_iftype type = NL80211_IFTYPE_UNSPECIFIED; u32 flags; memset(&params, 0, sizeof(params)); if (!info->attrs[NL80211_ATTR_IFNAME]) return -EINVAL; if (info->attrs[NL80211_ATTR_IFTYPE]) { type = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]); if (type > NL80211_IFTYPE_MAX) return -EINVAL; } if (!rdev->ops->add_virtual_intf || !(rdev->wiphy.interface_modes & (1 << type))) return -EOPNOTSUPP; if (info->attrs[NL80211_ATTR_4ADDR]) { params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]); err = nl80211_valid_4addr(rdev, NULL, params.use_4addr, type); if (err) return err; } err = parse_monitor_flags(type == NL80211_IFTYPE_MONITOR ? info->attrs[NL80211_ATTR_MNTR_FLAGS] : NULL, &flags); dev = rdev->ops->add_virtual_intf(&rdev->wiphy, nla_data(info->attrs[NL80211_ATTR_IFNAME]), type, err ? NULL : &flags, &params); if (IS_ERR(dev)) return PTR_ERR(dev); if (type == NL80211_IFTYPE_MESH_POINT && info->attrs[NL80211_ATTR_MESH_ID]) { struct wireless_dev *wdev = dev->ieee80211_ptr; wdev_lock(wdev); BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN != IEEE80211_MAX_MESH_ID_LEN); wdev->mesh_id_up_len = nla_len(info->attrs[NL80211_ATTR_MESH_ID]); memcpy(wdev->ssid, nla_data(info->attrs[NL80211_ATTR_MESH_ID]), wdev->mesh_id_up_len); wdev_unlock(wdev); } return 0; } Commit Message: nl80211: fix check for valid SSID size in scan operations In both trigger_scan and sched_scan operations, we were checking for the SSID length before assigning the value correctly. Since the memory was just kzalloc'ed, the check was always failing and SSID with over 32 characters were allowed to go through. This was causing a buffer overflow when copying the actual SSID to the proper place. This bug has been there since 2.6.29-rc4. Cc: stable@kernel.org Signed-off-by: Luciano Coelho <coelho@ti.com> Signed-off-by: John W. Linville <linville@tuxdriver.com> CWE ID: CWE-119
0
26,704
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_close(struct tty_struct *tty) { struct hci_uart *hu = tty->disc_data; struct hci_dev *hdev; BT_DBG("tty %p", tty); /* Detach from the tty */ tty->disc_data = NULL; if (!hu) return; hdev = hu->hdev; if (hdev) hci_uart_close(hdev); if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) { percpu_down_write(&hu->proto_lock); clear_bit(HCI_UART_PROTO_READY, &hu->flags); percpu_up_write(&hu->proto_lock); cancel_work_sync(&hu->write_work); if (hdev) { if (test_bit(HCI_UART_REGISTERED, &hu->flags)) hci_unregister_dev(hdev); hci_free_dev(hdev); } hu->proto->close(hu); } clear_bit(HCI_UART_PROTO_SET, &hu->flags); percpu_free_rwsem(&hu->proto_lock); kfree(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
88,165
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 __unqueue_futex(struct futex_q *q) { struct futex_hash_bucket *hb; if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr)) || WARN_ON(plist_node_empty(&q->list))) return; hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock); plist_del(&q->list, &hb->chain); } Commit Message: futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi() If uaddr == uaddr2, then we have broken the rule of only requeueing from a non-pi futex to a pi futex with this call. If we attempt this, as the trinity test suite manages to do, we miss early wakeups as q.key is equal to key2 (because they are the same uaddr). We will then attempt to dereference the pi_mutex (which would exist had the futex_q been properly requeued to a pi futex) and trigger a NULL pointer dereference. Signed-off-by: Darren Hart <dvhart@linux.intel.com> Cc: Dave Jones <davej@redhat.com> Cc: stable@vger.kernel.org Link: http://lkml.kernel.org/r/ad82bfe7f7d130247fbe2b5b4275654807774227.1342809673.git.dvhart@linux.intel.com Signed-off-by: Thomas Gleixner <tglx@linutronix.de> CWE ID: CWE-20
0
41,080
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: char *bin2hex(const unsigned char *p, size_t len) { ssize_t slen; char *s; slen = len * 2 + 1; if (slen % 4) slen += 4 - (slen % 4); s = calloc(slen, 1); if (unlikely(!s)) quithere(1, "Failed to calloc"); __bin2hex(s, p, len); return s; } Commit Message: Do some random sanity checking for stratum message parsing CWE ID: CWE-119
0
36,658
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 RenderBox::hasUnsplittableScrollingOverflow() const { bool isHorizontal = isHorizontalWritingMode(); if ((isHorizontal && !scrollsOverflowY()) || (!isHorizontal && !scrollsOverflowX())) return false; return !style()->logicalHeight().isIntrinsicOrAuto() || (!style()->logicalMaxHeight().isIntrinsicOrAuto() && !style()->logicalMaxHeight().isUndefined() && (!style()->logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this))) || (!style()->logicalMinHeight().isIntrinsicOrAuto() && style()->logicalMinHeight().isPositive() && (!style()->logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this))); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. 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
116,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: static int __sched_setscheduler(struct task_struct *p, const struct sched_attr *attr, bool user, bool pi) { int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 : MAX_RT_PRIO - 1 - attr->sched_priority; int retval, oldprio, oldpolicy = -1, queued, running; int new_effective_prio, policy = attr->sched_policy; const struct sched_class *prev_class; struct rq_flags rf; int reset_on_fork; int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE; struct rq *rq; /* may grab non-irq protected spin_locks */ BUG_ON(in_interrupt()); recheck: /* double check policy once rq lock held */ if (policy < 0) { reset_on_fork = p->sched_reset_on_fork; policy = oldpolicy = p->policy; } else { reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK); if (!valid_policy(policy)) return -EINVAL; } if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK)) return -EINVAL; /* * Valid priorities for SCHED_FIFO and SCHED_RR are * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, * SCHED_BATCH and SCHED_IDLE is 0. */ if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) || (!p->mm && attr->sched_priority > MAX_RT_PRIO-1)) return -EINVAL; if ((dl_policy(policy) && !__checkparam_dl(attr)) || (rt_policy(policy) != (attr->sched_priority != 0))) return -EINVAL; /* * Allow unprivileged RT tasks to decrease priority: */ if (user && !capable(CAP_SYS_NICE)) { if (fair_policy(policy)) { if (attr->sched_nice < task_nice(p) && !can_nice(p, attr->sched_nice)) return -EPERM; } if (rt_policy(policy)) { unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO); /* can't set/change the rt policy */ if (policy != p->policy && !rlim_rtprio) return -EPERM; /* can't increase priority */ if (attr->sched_priority > p->rt_priority && attr->sched_priority > rlim_rtprio) return -EPERM; } /* * Can't set/change SCHED_DEADLINE policy at all for now * (safest behavior); in the future we would like to allow * unprivileged DL tasks to increase their relative deadline * or reduce their runtime (both ways reducing utilization) */ if (dl_policy(policy)) return -EPERM; /* * Treat SCHED_IDLE as nice 20. Only allow a switch to * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. */ if (idle_policy(p->policy) && !idle_policy(policy)) { if (!can_nice(p, task_nice(p))) return -EPERM; } /* can't change other user's priorities */ if (!check_same_owner(p)) return -EPERM; /* Normal users shall not reset the sched_reset_on_fork flag */ if (p->sched_reset_on_fork && !reset_on_fork) return -EPERM; } if (user) { retval = security_task_setscheduler(p); if (retval) return retval; } /* * make sure no PI-waiters arrive (or leave) while we are * changing the priority of the task: * * To be able to change p->policy safely, the appropriate * runqueue lock must be held. */ rq = task_rq_lock(p, &rf); /* * Changing the policy of the stop threads its a very bad idea */ if (p == rq->stop) { task_rq_unlock(rq, p, &rf); return -EINVAL; } /* * If not changing anything there's no need to proceed further, * but store a possible modification of reset_on_fork. */ if (unlikely(policy == p->policy)) { if (fair_policy(policy) && attr->sched_nice != task_nice(p)) goto change; if (rt_policy(policy) && attr->sched_priority != p->rt_priority) goto change; if (dl_policy(policy) && dl_param_changed(p, attr)) goto change; p->sched_reset_on_fork = reset_on_fork; task_rq_unlock(rq, p, &rf); return 0; } change: if (user) { #ifdef CONFIG_RT_GROUP_SCHED /* * Do not allow realtime tasks into groups that have no runtime * assigned. */ if (rt_bandwidth_enabled() && rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0 && !task_group_is_autogroup(task_group(p))) { task_rq_unlock(rq, p, &rf); return -EPERM; } #endif #ifdef CONFIG_SMP if (dl_bandwidth_enabled() && dl_policy(policy)) { cpumask_t *span = rq->rd->span; /* * Don't allow tasks with an affinity mask smaller than * the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ if (!cpumask_subset(span, &p->cpus_allowed) || rq->rd->dl_bw.bw == 0) { task_rq_unlock(rq, p, &rf); return -EPERM; } } #endif } /* recheck policy now with rq lock held */ if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &rf); goto recheck; } /* * If setscheduling to SCHED_DEADLINE (or changing the parameters * of a SCHED_DEADLINE task) we need to check if enough bandwidth * is available. */ if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) { task_rq_unlock(rq, p, &rf); return -EBUSY; } p->sched_reset_on_fork = reset_on_fork; oldprio = p->prio; if (pi) { /* * Take priority boosted tasks into account. If the new * effective priority is unchanged, we just store the new * normal parameters and do not touch the scheduler class and * the runqueue. This will be done when the task deboost * itself. */ new_effective_prio = rt_mutex_get_effective_prio(p, newprio); if (new_effective_prio == oldprio) queue_flags &= ~DEQUEUE_MOVE; } queued = task_on_rq_queued(p); running = task_current(rq, p); if (queued) dequeue_task(rq, p, queue_flags); if (running) put_prev_task(rq, p); prev_class = p->sched_class; __setscheduler(rq, p, attr, pi); if (running) p->sched_class->set_curr_task(rq); if (queued) { /* * We enqueue to tail when the priority of a task is * increased (user space view). */ if (oldprio < p->prio) queue_flags |= ENQUEUE_HEAD; enqueue_task(rq, p, queue_flags); } check_class_changed(rq, p, prev_class, oldprio); preempt_disable(); /* avoid rq from going away on us */ task_rq_unlock(rq, p, &rf); if (pi) rt_mutex_adjust_pi(p); /* * Run balance callbacks after we've adjusted the PI chain. */ balance_callback(rq); preempt_enable(); return 0; } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <jannh@google.com>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119
0
55,471
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: ServiceManagerConnectionImpl::ServiceManagerConnectionImpl( service_manager::mojom::ServiceRequest request, scoped_refptr<base::SequencedTaskRunner> io_task_runner) : weak_factory_(this) { service_manager::mojom::ConnectorRequest connector_request; connector_ = service_manager::Connector::Create(&connector_request); std::unique_ptr<service_manager::Connector> io_thread_connector = connector_->Clone(); context_ = new IOThreadContext( std::move(request), io_task_runner, std::move(io_thread_connector), std::move(connector_request)); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <xhwang@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: John Abd-El-Malek <jam@chromium.org> Reviewed-by: Dan Sanders <sandersd@chromium.org> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
0
127,476
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 Browser::ShowExtensionsTab() { UserMetrics::RecordAction(UserMetricsAction("ShowExtensions"), profile_); ShowSingletonTab(GURL(chrome::kChromeUIExtensionsURL)); } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
98,322
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 pdf_run_W(fz_context *ctx, pdf_processor *proc) { pdf_run_processor *pr = (pdf_run_processor *)proc; pr->clip = 1; pr->clip_even_odd = 0; } Commit Message: CWE ID: CWE-416
0
508
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 u8 ip6_frag_ecn(const struct ipv6hdr *ipv6h) { return 1 << (ipv6_get_dsfield(ipv6h) & INET_ECN_MASK); } Commit Message: netfilter: ipv6: nf_defrag: drop mangled skb on ream error Dmitry Vyukov reported GPF in network stack that Andrey traced down to negative nh offset in nf_ct_frag6_queue(). Problem is that all network headers before fragment header are pulled. Normal ipv6 reassembly will drop the skb when errors occur further down the line. netfilter doesn't do this, and instead passed the original fragment along. That was also fine back when netfilter ipv6 defrag worked with cloned fragments, as the original, pristine fragment was passed on. So we either have to undo the pull op, or discard such fragments. Since they're malformed after all (e.g. overlapping fragment) it seems preferrable to just drop them. Same for temporary errors -- it doesn't make sense to accept (and perhaps forward!) only some fragments of same datagram. Fixes: 029f7f3b8701cc7ac ("netfilter: ipv6: nf_defrag: avoid/free clone operations") Reported-by: Dmitry Vyukov <dvyukov@google.com> Debugged-by: Andrey Konovalov <andreyknvl@google.com> Diagnosed-by: Eric Dumazet <Eric Dumazet <edumazet@google.com> Signed-off-by: Florian Westphal <fw@strlen.de> Acked-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-787
0
47,984
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: MYSQLND_METHOD(mysqlnd_conn_data, reap_query)(MYSQLND_CONN_DATA * conn TSRMLS_DC) { size_t this_func = STRUCT_OFFSET(struct st_mysqlnd_conn_data_methods, reap_query); enum_mysqlnd_connection_state state = CONN_GET_STATE(conn); enum_func_status ret = FAIL; DBG_ENTER("mysqlnd_conn_data::reap_query"); DBG_INF_FMT("conn=%llu", conn->thread_id); DBG_INF_FMT("conn->server_status=%u", conn->upsert_status->server_status); if (PASS == conn->m->local_tx_start(conn, this_func TSRMLS_CC)) { if (state <= CONN_READY || state == CONN_QUIT_SENT) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Connection not opened, clear or has been closed"); DBG_ERR_FMT("Connection not opened, clear or has been closed. State=%u", state); DBG_RETURN(ret); } ret = conn->m->query_read_result_set_header(conn, NULL TSRMLS_CC); conn->m->local_tx_end(conn, this_func, ret TSRMLS_CC); } DBG_INF_FMT("conn->server_status=%u", conn->upsert_status->server_status); DBG_RETURN(ret); } Commit Message: CWE ID: CWE-284
0
14,275
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 br_ip4_multicast_add_group(struct net_bridge *br, struct net_bridge_port *port, __be32 group, __u16 vid) { struct br_ip br_group; if (ipv4_is_local_multicast(group)) return 0; br_group.u.ip4 = group; br_group.proto = htons(ETH_P_IP); br_group.vid = vid; return br_multicast_add_group(br, port, &br_group); } Commit Message: bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <pomidorabelisima@gmail.com> Reported-by: LiYonghua <809674045@qq.com> Reported-by: Robert Hancock <hancockrwd@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Cc: Stephen Hemminger <stephen@networkplumber.org> Cc: "David S. Miller" <davem@davemloft.net> Signed-off-by: Cong Wang <amwang@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
29,989
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 uvesafb_helper_start(void) { char *envp[] = { "HOME=/", "PATH=/sbin:/bin", NULL, }; char *argv[] = { v86d_path, NULL, }; return call_usermodehelper(v86d_path, argv, envp, UMH_WAIT_PROC); } Commit Message: video: uvesafb: Fix integer overflow in allocation cmap->len can get close to INT_MAX/2, allowing for an integer overflow in allocation. This uses kmalloc_array() instead to catch the condition. Reported-by: Dr Silvio Cesare of InfoSect <silvio.cesare@gmail.com> Fixes: 8bdb3a2d7df48 ("uvesafb: the driver core") Cc: stable@vger.kernel.org Signed-off-by: Kees Cook <keescook@chromium.org> CWE ID: CWE-190
0
79,775
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 em_sysenter(struct x86_emulate_ctxt *ctxt) { struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; ops->get_msr(ctxt, MSR_EFER, &efer); /* inject #GP if in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL) return emulate_gp(ctxt, 0); /* XXX sysenter/sysexit have not been tested in 64bit mode. * Therefore, we inject an #UD. */ if (ctxt->mode == X86EMUL_MODE_PROT64) return emulate_ud(ctxt); setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (ctxt->mode) { case X86EMUL_MODE_PROT32: if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); break; case X86EMUL_MODE_PROT64: if (msr_data == 0x0) return emulate_gp(ctxt, 0); break; } ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF); cs_sel = (u16)msr_data; cs_sel &= ~SELECTOR_RPL_MASK; ss_sel = cs_sel + 8; ss_sel &= ~SELECTOR_RPL_MASK; if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data); ctxt->regs[VCPU_REGS_RSP] = msr_data; return X86EMUL_CONTINUE; } Commit Message: KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <stephan.baerwolf@tu-ilmenau.de> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID:
0
21,790
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 nfs4_xdr_dec_readlink(struct rpc_rqst *rqstp, struct xdr_stream *xdr, struct nfs4_readlink_res *res) { struct compound_hdr hdr; int status; status = decode_compound_hdr(xdr, &hdr); if (status) goto out; status = decode_sequence(xdr, &res->seq_res, rqstp); if (status) goto out; status = decode_putfh(xdr); if (status) goto out; status = decode_readlink(xdr, rqstp); out: return status; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: stable@kernel.org Signed-off-by: Andy Adamson <andros@netapp.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
0
23,435
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: getPluginDescription() { static const char* desc = NULL; if (!desc) { desc = std::getenv("GNASH_PLUGIN_DESCRIPTION"); if (desc == NULL) desc = PLUGIN_DESCRIPTION; } return desc; } Commit Message: CWE ID: CWE-264
0
13,219
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 Document::SetFocusedElement(Element* new_focused_element, const FocusParams& params) { DCHECK(!lifecycle_.InDetach()); clear_focused_element_timer_.Stop(); if (new_focused_element && (new_focused_element->GetDocument() != this)) return true; if (NodeChildRemovalTracker::IsBeingRemoved(new_focused_element)) return true; if (focused_element_ == new_focused_element) return true; bool focus_change_blocked = false; Element* old_focused_element = focused_element_; focused_element_ = nullptr; UpdateDistributionForFlatTreeTraversal(); Node* ancestor = (old_focused_element && old_focused_element->isConnected() && new_focused_element) ? FlatTreeTraversal::CommonAncestor(*old_focused_element, *new_focused_element) : nullptr; if (old_focused_element) { old_focused_element->SetFocused(false, params.type); old_focused_element->SetHasFocusWithinUpToAncestor(false, ancestor); if (GetPage() && (GetPage()->GetFocusController().IsFocused())) { old_focused_element->DispatchBlurEvent(new_focused_element, params.type, params.source_capabilities); if (focused_element_) { focus_change_blocked = true; new_focused_element = nullptr; } old_focused_element->DispatchFocusOutEvent(EventTypeNames::focusout, new_focused_element, params.source_capabilities); old_focused_element->DispatchFocusOutEvent(EventTypeNames::DOMFocusOut, new_focused_element, params.source_capabilities); if (focused_element_) { focus_change_blocked = true; new_focused_element = nullptr; } } } if (new_focused_element) UpdateStyleAndLayoutTreeForNode(new_focused_element); if (new_focused_element && new_focused_element->IsFocusable()) { if (IsRootEditableElement(*new_focused_element) && !AcceptsEditingFocus(*new_focused_element)) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_ = new_focused_element; SetSequentialFocusNavigationStartingPoint(focused_element_.Get()); if (params.type != kWebFocusTypeNone) last_focus_type_ = params.type; focused_element_->SetFocused(true, params.type); focused_element_->SetHasFocusWithinUpToAncestor(true, ancestor); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } CancelFocusAppearanceUpdate(); EnsurePaintLocationDataValidForNode(focused_element_); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_->UpdateFocusAppearanceWithOptions( params.selection_behavior, params.options); if (GetPage() && (GetPage()->GetFocusController().IsFocused())) { focused_element_->DispatchFocusEvent(old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_->DispatchFocusInEvent(EventTypeNames::focusin, old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_->DispatchFocusInEvent(EventTypeNames::DOMFocusIn, old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } } } if (!focus_change_blocked && focused_element_) { if (AXObjectCache* cache = ExistingAXObjectCache()) { cache->HandleFocusedUIElementChanged(old_focused_element, new_focused_element); } } if (!focus_change_blocked && GetPage()) { GetPage()->GetChromeClient().FocusedNodeChanged(old_focused_element, focused_element_.Get()); } SetFocusedElementDone: UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return !focus_change_blocked; } Commit Message: Inherit CSP when self-navigating to local-scheme URL As the linked bug example shows, we should inherit CSP when we navigate to a local-scheme URL (even if we are in a main browsing context). Bug: 799747 Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02 Reviewed-on: https://chromium-review.googlesource.com/c/1234337 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#597889} CWE ID:
0
144,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: bool CloudPolicyCacheBase::DecodePolicyResponse( const em::PolicyFetchResponse& policy_response, PolicyMap* mandatory, PolicyMap* recommended, base::Time* timestamp, PublicKeyVersion* public_key_version) { std::string data = policy_response.policy_data(); em::PolicyData policy_data; if (!policy_data.ParseFromString(data)) { LOG(WARNING) << "Failed to parse PolicyData protobuf."; return false; } if (timestamp) { *timestamp = base::Time::UnixEpoch() + base::TimeDelta::FromMilliseconds(policy_data.timestamp()); } if (public_key_version) { public_key_version->valid = policy_data.has_public_key_version(); if (public_key_version->valid) public_key_version->version = policy_data.public_key_version(); } return DecodePolicyData(policy_data, mandatory, recommended); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
97,746
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 purple_transfer_request_cb(gpointer data, gint fd, b_input_condition cond) { file_transfer_t *ft = data; struct prpl_xfer_data *px = ft->data; px->timeout = 0; if (ft->write == NULL) { ft->write = prpl_xfer_write; imcb_file_recv_start(px->ic, ft); } ft->write_request(ft); return FALSE; } Commit Message: purple: Fix crash on ft requests from unknown contacts Followup to 701ab81 (included in 3.5) which was a partial fix which only improved things for non-libpurple file transfers (that is, just jabber) CWE ID: CWE-476
0
68,615
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: LayoutPoint RenderFlexibleBox::flowAwareLocationForChild(RenderBox* child) const { return isHorizontalFlow() ? child->location() : child->location().transposedPoint(); } 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
116,665
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 regulator_notifier_call_chain(struct regulator_dev *rdev, unsigned long event, void *data) { _notifier_call_chain(rdev, event, data); return NOTIFY_DONE; } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <sw0312.kim@samsung.com> Signed-off-by: Mark Brown <broonie@kernel.org> CWE ID: CWE-416
0
74,526
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: CIFSSMBRead(const int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *pbuf_type) { int rc = -EACCES; READ_REQ *pSMB = NULL; READ_RSP *pSMBr = NULL; char *pReadData = NULL; int wct; int resp_buf_type = 0; struct kvec iov[1]; __u32 pid = io_parms->pid; __u16 netfid = io_parms->netfid; __u64 offset = io_parms->offset; struct cifs_tcon *tcon = io_parms->tcon; unsigned int count = io_parms->length; cFYI(1, "Reading %d bytes on fid %d", count, netfid); if (tcon->ses->capabilities & CAP_LARGE_FILES) wct = 12; else { wct = 10; /* old style read */ if ((offset >> 32) > 0) { /* can not handle this big offset for old */ return -EIO; } } *nbytes = 0; rc = small_smb_init(SMB_COM_READ_ANDX, wct, tcon, (void **) &pSMB); if (rc) return rc; pSMB->hdr.Pid = cpu_to_le16((__u16)pid); pSMB->hdr.PidHigh = cpu_to_le16((__u16)(pid >> 16)); /* tcon and ses pointer are checked in smb_init */ if (tcon->ses->server == NULL) return -ECONNABORTED; pSMB->AndXCommand = 0xFF; /* none */ pSMB->Fid = netfid; pSMB->OffsetLow = cpu_to_le32(offset & 0xFFFFFFFF); if (wct == 12) pSMB->OffsetHigh = cpu_to_le32(offset >> 32); pSMB->Remaining = 0; pSMB->MaxCount = cpu_to_le16(count & 0xFFFF); pSMB->MaxCountHigh = cpu_to_le32(count >> 16); if (wct == 12) pSMB->ByteCount = 0; /* no need to do le conversion since 0 */ else { /* old style read */ struct smb_com_readx_req *pSMBW = (struct smb_com_readx_req *)pSMB; pSMBW->ByteCount = 0; } iov[0].iov_base = (char *)pSMB; iov[0].iov_len = be32_to_cpu(pSMB->hdr.smb_buf_length) + 4; rc = SendReceive2(xid, tcon->ses, iov, 1 /* num iovecs */, &resp_buf_type, CIFS_LOG_ERROR); cifs_stats_inc(&tcon->num_reads); pSMBr = (READ_RSP *)iov[0].iov_base; if (rc) { cERROR(1, "Send error in read = %d", rc); } else { int data_length = le16_to_cpu(pSMBr->DataLengthHigh); data_length = data_length << 16; data_length += le16_to_cpu(pSMBr->DataLength); *nbytes = data_length; /*check that DataLength would not go beyond end of SMB */ if ((data_length > CIFSMaxBufSize) || (data_length > count)) { cFYI(1, "bad length %d for count %d", data_length, count); rc = -EIO; *nbytes = 0; } else { pReadData = (char *) (&pSMBr->hdr.Protocol) + le16_to_cpu(pSMBr->DataOffset); /* if (rc = copy_to_user(buf, pReadData, data_length)) { cERROR(1, "Faulting on read rc = %d",rc); rc = -EFAULT; }*/ /* can not use copy_to_user when using page cache*/ if (*buf) memcpy(*buf, pReadData, data_length); } } /* cifs_small_buf_release(pSMB); */ /* Freed earlier now in SendReceive2 */ if (*buf) { if (resp_buf_type == CIFS_SMALL_BUFFER) cifs_small_buf_release(iov[0].iov_base); else if (resp_buf_type == CIFS_LARGE_BUFFER) cifs_buf_release(iov[0].iov_base); } else if (resp_buf_type != CIFS_NO_BUFFER) { /* return buffer to caller to free */ *buf = iov[0].iov_base; if (resp_buf_type == CIFS_SMALL_BUFFER) *pbuf_type = CIFS_SMALL_BUFFER; else if (resp_buf_type == CIFS_LARGE_BUFFER) *pbuf_type = CIFS_LARGE_BUFFER; } /* else no valid buffer on return - leave as null */ /* Note: On -EAGAIN error only caller can retry on handle based calls since file handle passed in no longer valid */ return rc; } Commit Message: cifs: fix possible memory corruption in CIFSFindNext The name_len variable in CIFSFindNext is a signed int that gets set to the resume_name_len in the cifs_search_info. The resume_name_len however is unsigned and for some infolevels is populated directly from a 32 bit value sent by the server. If the server sends a very large value for this, then that value could look negative when converted to a signed int. That would make that value pass the PATH_MAX check later in CIFSFindNext. The name_len would then be used as a length value for a memcpy. It would then be treated as unsigned again, and the memcpy scribbles over a ton of memory. Fix this by making the name_len an unsigned value in CIFSFindNext. Cc: <stable@kernel.org> Reported-by: Darren Lavender <dcl@hppine99.gbr.hp.com> Signed-off-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Steve French <sfrench@us.ibm.com> CWE ID: CWE-189
0
24,979
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 DoResolveRelativePath(const char* base_url, const url_parse::Parsed& base_parsed, bool base_is_file, const CHAR* relative_url, const url_parse::Component& relative_component, CharsetConverter* query_converter, CanonOutput* output, url_parse::Parsed* out_parsed) { bool success = true; url_parse::Component path, query, ref; url_parse::ParsePathInternal(relative_url, relative_component, &path, &query, &ref); output->Append(base_url, base_parsed.path.begin); if (path.len > 0) { int true_path_begin = output->length(); int base_path_begin = base_parsed.path.begin; #ifdef WIN32 if (base_is_file) { base_path_begin = CopyBaseDriveSpecIfNecessary( base_url, base_parsed.path.begin, base_parsed.path.end(), relative_url, relative_component.begin, relative_component.end(), output); } #endif // WIN32 if (url_parse::IsURLSlash(relative_url[path.begin])) { success &= CanonicalizePath(relative_url, path, output, &out_parsed->path); } else { int path_begin = output->length(); CopyToLastSlash(base_url, base_path_begin, base_parsed.path.end(), output); success &= CanonicalizePartialPath(relative_url, path, path_begin, output); out_parsed->path = url_parse::MakeRange(path_begin, output->length()); } CanonicalizeQuery(relative_url, query, query_converter, output, &out_parsed->query); CanonicalizeRef(relative_url, ref, output, &out_parsed->ref); out_parsed->path = url_parse::MakeRange(true_path_begin, out_parsed->path.end()); return success; } CopyOneComponent(base_url, base_parsed.path, output, &out_parsed->path); if (query.is_valid()) { CanonicalizeQuery(relative_url, query, query_converter, output, &out_parsed->query); CanonicalizeRef(relative_url, ref, output, &out_parsed->ref); return success; } if (base_parsed.query.is_valid()) output->push_back('?'); CopyOneComponent(base_url, base_parsed.query, output, &out_parsed->query); if (ref.is_valid()) { CanonicalizeRef(relative_url, ref, output, &out_parsed->ref); return success; } DCHECK(false) << "Not reached"; return success; } Commit Message: Fix OOB read when parsing protocol-relative URLs BUG=285742 Review URL: https://chromiumcodereview.appspot.com/23902014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@223735 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
111,704
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: AffineTransform& AffineTransform::flipX() { return scale(-1, 1); } Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950} CWE ID:
0
121,181
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: LastEventTime(int deviceid) { return lastDeviceEventTime[deviceid].time; } Commit Message: CWE ID: CWE-119
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: static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } Commit Message: Set pixel cache to undefined if any resource limit is exceeded CWE ID: CWE-119
0
94,812
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: PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Id$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ Commit Message: CWE ID: CWE-125
0
4,445
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 setkey_unaligned(struct crypto_aead *tfm, const u8 *key, unsigned int keylen) { struct aead_alg *aead = crypto_aead_alg(tfm); unsigned long alignmask = crypto_aead_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = aead->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-310
0
31,230
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 btrfs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { u64 delalloc_bytes; struct inode *inode = d_inode(dentry); u32 blocksize = inode->i_sb->s_blocksize; generic_fillattr(inode, stat); stat->dev = BTRFS_I(inode)->root->anon_dev; stat->blksize = PAGE_CACHE_SIZE; spin_lock(&BTRFS_I(inode)->lock); delalloc_bytes = BTRFS_I(inode)->delalloc_bytes; spin_unlock(&BTRFS_I(inode)->lock); stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) + ALIGN(delalloc_bytes, blocksize)) >> 9; return 0; } 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
41,640
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 locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
1
171,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 amd_gpio_irq_handler(struct irq_desc *desc) { u32 i; u32 off; u32 reg; u32 pin_reg; u64 reg64; int handled = 0; unsigned int irq; unsigned long flags; struct irq_chip *chip = irq_desc_get_chip(desc); struct gpio_chip *gc = irq_desc_get_handler_data(desc); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); chained_irq_enter(chip, desc); /*enable GPIO interrupt again*/ spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_STATUS_REG1); reg64 = reg; reg64 = reg64 << 32; reg = readl(gpio_dev->base + WAKE_INT_STATUS_REG0); reg64 |= reg; spin_unlock_irqrestore(&gpio_dev->lock, flags); /* * first 46 bits indicates interrupt status. * one bit represents four interrupt sources. */ for (off = 0; off < 46 ; off++) { if (reg64 & BIT(off)) { for (i = 0; i < 4; i++) { pin_reg = readl(gpio_dev->base + (off * 4 + i) * 4); if ((pin_reg & BIT(INTERRUPT_STS_OFF)) || (pin_reg & BIT(WAKE_STS_OFF))) { irq = irq_find_mapping(gc->irqdomain, off * 4 + i); generic_handle_irq(irq); writel(pin_reg, gpio_dev->base + (off * 4 + i) * 4); handled++; } } } } if (handled == 0) handle_bad_irq(desc); spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_MASTER_REG); reg |= EOI_MASK; writel(reg, gpio_dev->base + WAKE_INT_MASTER_REG); spin_unlock_irqrestore(&gpio_dev->lock, flags); chained_irq_exit(chip, desc); } Commit Message: pinctrl/amd: Drop pinctrl_unregister for devm_ registered device It's not necessary to unregister pin controller device registered with devm_pinctrl_register() and using pinctrl_unregister() leads to a double free. Fixes: 3bfd44306c65 ("pinctrl: amd: Add support for additional GPIO") Signed-off-by: Wei Yongjun <weiyongjun1@huawei.com> Signed-off-by: Linus Walleij <linus.walleij@linaro.org> CWE ID: CWE-415
0
86,163
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 OutOfProcessInstance::OnGeometryChanged(double old_zoom, float old_device_scale) { if (zoom_ != old_zoom || device_scale_ != old_device_scale) engine_->ZoomUpdated(zoom_ * device_scale_); available_area_ = pp::Rect(plugin_size_); int doc_width = GetDocumentPixelWidth(); if (doc_width < available_area_.width()) { available_area_.Offset((available_area_.width() - doc_width) / 2, 0); available_area_.set_width(doc_width); } int bottom_of_document = GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_); if (bottom_of_document < available_area_.height()) available_area_.set_height(bottom_of_document); CalculateBackgroundParts(); engine_->PageOffsetUpdated(available_area_.point()); engine_->PluginSizeUpdated(available_area_.size()); if (!document_size_.GetArea()) return; paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_)); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20
0
129,450
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 exit_dns_resolver(void) { key_revoke(dns_resolver_cache->thread_keyring); unregister_key_type(&key_type_dns_resolver); put_cred(dns_resolver_cache); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: stable@vger.kernel.org # v4.4+ Reported-by: Eric Biggers <ebiggers@google.com> Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Eric Biggers <ebiggers@google.com> CWE ID: CWE-20
0
60,198