instruction
stringclasses 1
value | input
stringlengths 306
235k
| output
stringclasses 4
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 impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: explicit CancelAndIgnoreNavigationForPluginFrameThrottle(
NavigationHandle* handle)
: NavigationThrottle(handle) {}
Vulnerability Type:
CWE ID: CWE-362
Summary: Data race in extensions guest view in Google Chrome prior to 73.0.3683.75 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
TBR=avi@chromium.org,lazyboy@chromium.org
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <ekaramad@chromium.org>
Reviewed-by: James MacLean <wjmaclean@chromium.org>
Reviewed-by: Ehsan Karamad <ekaramad@chromium.org>
Cr-Commit-Position: refs/heads/master@{#621155}
|
High
| 173,036
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy(RTCPeerConnectionHandlerClient* client)
: m_client(client)
{
ASSERT_UNUSED(m_client, m_client);
}
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
|
Low
| 170,346
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int SpdyProxyClientSocket::DoReadReplyComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
switch (response_.headers->response_code()) {
case 200: // OK
next_state_ = STATE_OPEN;
return OK;
case 302: // Found / Moved Temporarily
if (SanitizeProxyRedirect(&response_, request_.url)) {
redirect_has_load_timing_info_ =
spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_);
spdy_stream_->DetachDelegate();
next_state_ = STATE_DISCONNECTED;
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
} else {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
case 407: // Proxy Authentication Required
next_state_ = STATE_OPEN;
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
Vulnerability Type:
CWE ID: CWE-19
Summary: net/http/proxy_client_socket.cc in Google Chrome before 41.0.2272.76 does not properly handle a 407 (aka Proxy Authentication Required) HTTP status code accompanied by a Set-Cookie header, which allows remote proxy servers to conduct cookie-injection attacks via a crafted response.
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
|
Low
| 172,041
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp,
tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) {
tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT;
uint8_t u8, pdu, *p;
uint16_t u16;
tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor;
pdu = *(p_vendor->p_vendor_data);
p_rc_rsp->pdu = pdu;
*p_ctype = AVRC_RSP_REJ;
/* Check to ansure a valid minimum meta data length */
if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) {
/* reject it */
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
APPL_TRACE_ERROR("%s: Invalid meta-command length: %d", __func__,
p_vendor->vendor_len);
return 0;
}
/* Metadata messages only use PANEL sub-unit type */
if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) {
APPL_TRACE_DEBUG("%s: SUBUNIT must be PANEL", __func__);
/* reject it */
evt = 0;
p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL;
p_vendor->vendor_len = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
} else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) {
APPL_TRACE_DEBUG("%s: Invalid pdu/ctype: 0x%x, %d", __func__, pdu,
p_vendor->hdr.ctype);
/* reject invalid message without reporting to app */
evt = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD;
} else {
switch (pdu) {
case AVRC_PDU_GET_CAPABILITIES:
/* process GetCapabilities command without reporting the event to app */
evt = 0;
u8 = *(p_vendor->p_vendor_data + 4);
p = p_vendor->p_vendor_data + 2;
p_rc_rsp->get_caps.capability_id = u8;
BE_STREAM_TO_UINT16(u16, p);
if ((u16 != 1) || (p_vendor->vendor_len != 5)) {
p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
} else {
p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR;
if (u8 == AVRC_CAP_COMPANY_ID) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids;
memcpy(p_rc_rsp->get_caps.param.company_id,
p_bta_av_cfg->p_meta_co_ids,
(p_bta_av_cfg->num_co_ids << 2));
} else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids;
memcpy(p_rc_rsp->get_caps.param.event_id,
p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids);
} else {
APPL_TRACE_DEBUG("%s: Invalid capability ID: 0x%x", __func__, u8);
/* reject - unknown capability ID */
p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM;
}
}
break;
case AVRC_PDU_REGISTER_NOTIFICATION:
/* make sure the event_id is implemented */
p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor);
if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0;
break;
}
}
return evt;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: In bta_av_proc_meta_cmd of bta_av_act.cc, there is a possible out of bounds read due to an incorrect bounds check. This could lead to remote information disclosure over Bluetooth with no additional execution privileges needed. User interaction is not needed for exploitation. Product: Android Versions: Android-7.0 Android-7.1.1 Android-7.1.2 Android-8.0 Android-8.1 Android-9.0 Android ID: A-111893951
Commit Message: Check packet length in bta_av_proc_meta_cmd
Bug: 111893951
Test: manual - connect A2DP
Change-Id: Ibbf347863dfd29ea3385312e9dde1082bc90d2f3
(cherry picked from commit ed51887f921263219bcd2fbf6650ead5ec8d334e)
|
Low
| 174,078
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: bool IDNToUnicodeOneComponent(const base::char16* comp,
size_t comp_len,
bool is_tld_ascii,
bool enable_spoof_checks,
base::string16* out,
bool* has_idn_component) {
DCHECK(out);
DCHECK(has_idn_component);
*has_idn_component = false;
if (comp_len == 0)
return false;
static const base::char16 kIdnPrefix[] = {'x', 'n', '-', '-'};
if (comp_len <= base::size(kIdnPrefix) ||
memcmp(comp, kIdnPrefix, sizeof(kIdnPrefix)) != 0) {
out->append(comp, comp_len);
return false;
}
UIDNA* uidna = g_uidna.Get().value;
DCHECK(uidna != nullptr);
size_t original_length = out->length();
int32_t output_length = 64;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
UErrorCode status;
do {
out->resize(original_length + output_length);
status = U_ZERO_ERROR;
output_length = uidna_labelToUnicode(
uidna, comp, static_cast<int32_t>(comp_len), &(*out)[original_length],
output_length, &info, &status);
} while ((status == U_BUFFER_OVERFLOW_ERROR && info.errors == 0));
if (U_SUCCESS(status) && info.errors == 0) {
*has_idn_component = true;
out->resize(original_length + output_length);
if (!enable_spoof_checks) {
return true;
}
if (IsIDNComponentSafe(
base::StringPiece16(out->data() + original_length,
base::checked_cast<size_t>(output_length)),
is_tld_ascii)) {
return true;
}
}
out->resize(original_length);
out->append(comp, comp_len);
return false;
}
Vulnerability Type:
CWE ID:
Summary: Incorrect handling of confusable characters in URL Formatter in Google Chrome prior to 66.0.3359.117 allowed a remote attacker to perform domain spoofing via IDN homographs via a crafted domain name.
Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains
This character (þ) can be confused with both b and p when used in a domain
name. IDN spoof checker doesn't have a good way of flagging a character as
confusable with multiple characters, so it can't catch spoofs containing
this character. As a practical fix, this CL restricts this character to
domains under Iceland's ccTLD (.is). With this change, a domain name containing
"þ" with a non-.is TLD will be displayed in punycode in the UI.
This change affects less than 10 real world domains with limited popularity.
Bug: 798892, 843352, 904327, 1017707
Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992
Commit-Queue: Mustafa Emre Acer <meacer@chromium.org>
Reviewed-by: Christopher Thompson <cthomp@chromium.org>
Cr-Commit-Position: refs/heads/master@{#709309}
|
Medium
| 172,728
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
const String& source,
Document* owner_document) {
Document* document = frame_->GetDocument();
if (!document_loader_ ||
document->PageDismissalEventBeingDispatched() != Document::kNoDismissal)
return;
UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL);
const KURL& url = document->Url();
WebGlobalObjectReusePolicy global_object_reuse_policy =
frame_->ShouldReuseDefaultView(url)
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew;
StopAllLoaders();
SubframeLoadingDisabler disabler(document);
frame_->DetachChildren();
if (!frame_->IsAttached() || document != frame_->GetDocument())
return;
frame_->GetDocument()->Shutdown();
Client()->TransitionToCommittedForNewPage();
document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL(
url, owner_document, global_object_reuse_policy, source);
}
Vulnerability Type: Bypass
CWE ID: CWE-285
Summary: Object lifecycle issue in Blink in Google Chrome prior to 69.0.3497.81 allowed a remote attacker to bypass content security policy via a crafted HTML page.
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#567663}
|
Medium
| 173,198
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int DetectEngineContentInspection(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
const Signature *s, const SigMatchData *smd,
Flow *f,
uint8_t *buffer, uint32_t buffer_len,
uint32_t stream_start_offset,
uint8_t inspection_mode, void *data)
{
SCEnter();
KEYWORD_PROFILING_START;
det_ctx->inspection_recursion_counter++;
if (det_ctx->inspection_recursion_counter == de_ctx->inspection_recursion_limit) {
det_ctx->discontinue_matching = 1;
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCReturnInt(0);
}
if (smd == NULL || buffer_len == 0) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCReturnInt(0);
}
/* \todo unify this which is phase 2 of payload inspection unification */
if (smd->type == DETECT_CONTENT) {
DetectContentData *cd = (DetectContentData *)smd->ctx;
SCLogDebug("inspecting content %"PRIu32" buffer_len %"PRIu32, cd->id, buffer_len);
/* we might have already have this content matched by the mpm.
* (if there is any other reason why we'd want to avoid checking
* it here, please fill it in) */
/* rule parsers should take care of this */
#ifdef DEBUG
BUG_ON(cd->depth != 0 && cd->depth <= cd->offset);
#endif
/* search for our pattern, checking the matches recursively.
* if we match we look for the next SigMatch as well */
uint8_t *found = NULL;
uint32_t offset = 0;
uint32_t depth = buffer_len;
uint32_t prev_offset = 0; /**< used in recursive searching */
uint32_t prev_buffer_offset = det_ctx->buffer_offset;
do {
if ((cd->flags & DETECT_CONTENT_DISTANCE) ||
(cd->flags & DETECT_CONTENT_WITHIN)) {
SCLogDebug("det_ctx->buffer_offset %"PRIu32, det_ctx->buffer_offset);
offset = prev_buffer_offset;
depth = buffer_len;
int distance = cd->distance;
if (cd->flags & DETECT_CONTENT_DISTANCE) {
if (cd->flags & DETECT_CONTENT_DISTANCE_BE) {
distance = det_ctx->bj_values[cd->distance];
}
if (distance < 0 && (uint32_t)(abs(distance)) > offset)
offset = 0;
else
offset += distance;
SCLogDebug("cd->distance %"PRIi32", offset %"PRIu32", depth %"PRIu32,
distance, offset, depth);
}
if (cd->flags & DETECT_CONTENT_WITHIN) {
if (cd->flags & DETECT_CONTENT_WITHIN_BE) {
if ((int32_t)depth > (int32_t)(prev_buffer_offset + det_ctx->bj_values[cd->within] + distance)) {
depth = prev_buffer_offset + det_ctx->bj_values[cd->within] + distance;
}
} else {
if ((int32_t)depth > (int32_t)(prev_buffer_offset + cd->within + distance)) {
depth = prev_buffer_offset + cd->within + distance;
}
SCLogDebug("cd->within %"PRIi32", det_ctx->buffer_offset %"PRIu32", depth %"PRIu32,
cd->within, prev_buffer_offset, depth);
}
if (stream_start_offset != 0 && prev_buffer_offset == 0) {
if (depth <= stream_start_offset) {
goto no_match;
} else if (depth >= (stream_start_offset + buffer_len)) {
;
} else {
depth = depth - stream_start_offset;
}
}
}
if (cd->flags & DETECT_CONTENT_DEPTH_BE) {
if ((det_ctx->bj_values[cd->depth] + prev_buffer_offset) < depth) {
depth = prev_buffer_offset + det_ctx->bj_values[cd->depth];
}
} else {
if (cd->depth != 0) {
if ((cd->depth + prev_buffer_offset) < depth) {
depth = prev_buffer_offset + cd->depth;
}
SCLogDebug("cd->depth %"PRIu32", depth %"PRIu32, cd->depth, depth);
}
}
if (cd->flags & DETECT_CONTENT_OFFSET_BE) {
if (det_ctx->bj_values[cd->offset] > offset)
offset = det_ctx->bj_values[cd->offset];
} else {
if (cd->offset > offset) {
offset = cd->offset;
SCLogDebug("setting offset %"PRIu32, offset);
}
}
} else { /* implied no relative matches */
/* set depth */
if (cd->flags & DETECT_CONTENT_DEPTH_BE) {
depth = det_ctx->bj_values[cd->depth];
} else {
if (cd->depth != 0) {
depth = cd->depth;
}
}
if (stream_start_offset != 0 && cd->flags & DETECT_CONTENT_DEPTH) {
if (depth <= stream_start_offset) {
goto no_match;
} else if (depth >= (stream_start_offset + buffer_len)) {
;
} else {
depth = depth - stream_start_offset;
}
}
/* set offset */
if (cd->flags & DETECT_CONTENT_OFFSET_BE)
offset = det_ctx->bj_values[cd->offset];
else
offset = cd->offset;
prev_buffer_offset = 0;
}
/* update offset with prev_offset if we're searching for
* matches after the first occurence. */
SCLogDebug("offset %"PRIu32", prev_offset %"PRIu32, offset, prev_offset);
if (prev_offset != 0)
offset = prev_offset;
SCLogDebug("offset %"PRIu32", depth %"PRIu32, offset, depth);
if (depth > buffer_len)
depth = buffer_len;
/* if offset is bigger than depth we can never match on a pattern.
* We can however, "match" on a negated pattern. */
if (offset > depth || depth == 0) {
if (cd->flags & DETECT_CONTENT_NEGATED) {
goto match;
} else {
goto no_match;
}
}
uint8_t *sbuffer = buffer + offset;
uint32_t sbuffer_len = depth - offset;
uint32_t match_offset = 0;
SCLogDebug("sbuffer_len %"PRIu32, sbuffer_len);
#ifdef DEBUG
BUG_ON(sbuffer_len > buffer_len);
#endif
/* \todo Add another optimization here. If cd->content_len is
* greater than sbuffer_len found is anyways NULL */
/* do the actual search */
found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer,
sbuffer_len);
/* next we evaluate the result in combination with the
* negation flag. */
SCLogDebug("found %p cd negated %s", found, cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false");
if (found == NULL && !(cd->flags & DETECT_CONTENT_NEGATED)) {
goto no_match;
} else if (found == NULL && (cd->flags & DETECT_CONTENT_NEGATED)) {
goto match;
} else if (found != NULL && (cd->flags & DETECT_CONTENT_NEGATED)) {
SCLogDebug("content %"PRIu32" matched at offset %"PRIu32", but negated so no match", cd->id, match_offset);
/* don't bother carrying recursive matches now, for preceding
* relative keywords */
if (DETECT_CONTENT_IS_SINGLE(cd))
det_ctx->discontinue_matching = 1;
goto no_match;
} else {
match_offset = (uint32_t)((found - buffer) + cd->content_len);
SCLogDebug("content %"PRIu32" matched at offset %"PRIu32"", cd->id, match_offset);
det_ctx->buffer_offset = match_offset;
/* Match branch, add replace to the list if needed */
if (cd->flags & DETECT_CONTENT_REPLACE) {
if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) {
/* we will need to replace content if match is confirmed */
det_ctx->replist = DetectReplaceAddToList(det_ctx->replist, found, cd);
} else {
SCLogWarning(SC_ERR_INVALID_VALUE, "Can't modify payload without packet");
}
}
if (!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT)) {
SCLogDebug("no relative match coming up, so this is a match");
goto match;
}
/* bail out if we have no next match. Technically this is an
* error, as the current cd has the DETECT_CONTENT_RELATIVE_NEXT
* flag set. */
if (smd->is_last) {
goto no_match;
}
SCLogDebug("content %"PRIu32, cd->id);
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
/* see if the next buffer keywords match. If not, we will
* search for another occurence of this content and see
* if the others match then until we run out of matches */
int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1,
f, buffer, buffer_len, stream_start_offset, inspection_mode, data);
if (r == 1) {
SCReturnInt(1);
}
if (det_ctx->discontinue_matching)
goto no_match;
/* set the previous match offset to the start of this match + 1 */
prev_offset = (match_offset - (cd->content_len - 1));
SCLogDebug("trying to see if there is another match after prev_offset %"PRIu32, prev_offset);
}
} while(1);
} else if (smd->type == DETECT_ISDATAAT) {
SCLogDebug("inspecting isdataat");
DetectIsdataatData *id = (DetectIsdataatData *)smd->ctx;
if (id->flags & ISDATAAT_RELATIVE) {
if (det_ctx->buffer_offset + id->dataat > buffer_len) {
SCLogDebug("det_ctx->buffer_offset + id->dataat %"PRIu32" > %"PRIu32, det_ctx->buffer_offset + id->dataat, buffer_len);
if (id->flags & ISDATAAT_NEGATED)
goto match;
goto no_match;
} else {
SCLogDebug("relative isdataat match");
if (id->flags & ISDATAAT_NEGATED)
goto no_match;
goto match;
}
} else {
if (id->dataat < buffer_len) {
SCLogDebug("absolute isdataat match");
if (id->flags & ISDATAAT_NEGATED)
goto no_match;
goto match;
} else {
SCLogDebug("absolute isdataat mismatch, id->isdataat %"PRIu32", buffer_len %"PRIu32"", id->dataat, buffer_len);
if (id->flags & ISDATAAT_NEGATED)
goto match;
goto no_match;
}
}
} else if (smd->type == DETECT_PCRE) {
SCLogDebug("inspecting pcre");
DetectPcreData *pe = (DetectPcreData *)smd->ctx;
uint32_t prev_buffer_offset = det_ctx->buffer_offset;
uint32_t prev_offset = 0;
int r = 0;
det_ctx->pcre_match_start_offset = 0;
do {
Packet *p = NULL;
if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD)
p = (Packet *)data;
r = DetectPcrePayloadMatch(det_ctx, s, smd, p, f,
buffer, buffer_len);
if (r == 0) {
goto no_match;
}
if (!(pe->flags & DETECT_PCRE_RELATIVE_NEXT)) {
SCLogDebug("no relative match coming up, so this is a match");
goto match;
}
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
/* save it, in case we need to do a pcre match once again */
prev_offset = det_ctx->pcre_match_start_offset;
/* see if the next payload keywords match. If not, we will
* search for another occurence of this pcre and see
* if the others match, until we run out of matches */
r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1,
f, buffer, buffer_len, stream_start_offset, inspection_mode, data);
if (r == 1) {
SCReturnInt(1);
}
if (det_ctx->discontinue_matching)
goto no_match;
det_ctx->buffer_offset = prev_buffer_offset;
det_ctx->pcre_match_start_offset = prev_offset;
} while (1);
} else if (smd->type == DETECT_BYTETEST) {
DetectBytetestData *btd = (DetectBytetestData *)smd->ctx;
uint8_t flags = btd->flags;
int32_t offset = btd->offset;
uint64_t value = btd->value;
if (flags & DETECT_BYTETEST_OFFSET_BE) {
offset = det_ctx->bj_values[offset];
}
if (flags & DETECT_BYTETEST_VALUE_BE) {
value = det_ctx->bj_values[value];
}
/* if we have dce enabled we will have to use the endianness
* specified by the dce header */
if (flags & DETECT_BYTETEST_DCE && data != NULL) {
DCERPCState *dcerpc_state = (DCERPCState *)data;
/* enable the endianness flag temporarily. once we are done
* processing we reset the flags to the original value*/
flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ?
DETECT_BYTETEST_LITTLE: 0);
}
if (DetectBytetestDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags,
offset, value) != 1) {
goto no_match;
}
goto match;
} else if (smd->type == DETECT_BYTEJUMP) {
DetectBytejumpData *bjd = (DetectBytejumpData *)smd->ctx;
uint8_t flags = bjd->flags;
int32_t offset = bjd->offset;
if (flags & DETECT_BYTEJUMP_OFFSET_BE) {
offset = det_ctx->bj_values[offset];
}
/* if we have dce enabled we will have to use the endianness
* specified by the dce header */
if (flags & DETECT_BYTEJUMP_DCE && data != NULL) {
DCERPCState *dcerpc_state = (DCERPCState *)data;
/* enable the endianness flag temporarily. once we are done
* processing we reset the flags to the original value*/
flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ?
DETECT_BYTEJUMP_LITTLE: 0);
}
if (DetectBytejumpDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len,
flags, offset) != 1) {
goto no_match;
}
goto match;
} else if (smd->type == DETECT_BYTE_EXTRACT) {
DetectByteExtractData *bed = (DetectByteExtractData *)smd->ctx;
uint8_t endian = bed->endian;
/* if we have dce enabled we will have to use the endianness
* specified by the dce header */
if ((bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) &&
endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && data != NULL) {
DCERPCState *dcerpc_state = (DCERPCState *)data;
/* enable the endianness flag temporarily. once we are done
* processing we reset the flags to the original value*/
endian |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] == 0x10) ?
DETECT_BYTE_EXTRACT_ENDIAN_LITTLE : DETECT_BYTE_EXTRACT_ENDIAN_BIG);
}
if (DetectByteExtractDoMatch(det_ctx, smd, s, buffer,
buffer_len,
&det_ctx->bj_values[bed->local_id],
endian) != 1) {
goto no_match;
}
goto match;
/* we should never get here, but bail out just in case */
} else if (smd->type == DETECT_AL_URILEN) {
SCLogDebug("inspecting uri len");
int r = 0;
DetectUrilenData *urilend = (DetectUrilenData *) smd->ctx;
switch (urilend->mode) {
case DETECT_URILEN_EQ:
if (buffer_len == urilend->urilen1)
r = 1;
break;
case DETECT_URILEN_LT:
if (buffer_len < urilend->urilen1)
r = 1;
break;
case DETECT_URILEN_GT:
if (buffer_len > urilend->urilen1)
r = 1;
break;
case DETECT_URILEN_RA:
if (buffer_len > urilend->urilen1 &&
buffer_len < urilend->urilen2) {
r = 1;
}
break;
}
if (r == 1) {
goto match;
}
det_ctx->discontinue_matching = 0;
goto no_match;
#ifdef HAVE_LUA
}
else if (smd->type == DETECT_LUA) {
SCLogDebug("lua starting");
if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len,
det_ctx->buffer_offset, f) != 1)
{
SCLogDebug("lua no_match");
goto no_match;
}
SCLogDebug("lua match");
goto match;
#endif /* HAVE_LUA */
} else if (smd->type == DETECT_BASE64_DECODE) {
if (DetectBase64DecodeDoMatch(det_ctx, s, smd, buffer, buffer_len)) {
if (s->sm_arrays[DETECT_SM_LIST_BASE64_DATA] != NULL) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
if (DetectBase64DataDoMatch(de_ctx, det_ctx, s, f)) {
/* Base64 is a terminal list. */
goto final_match;
}
}
}
} else {
SCLogDebug("sm->type %u", smd->type);
#ifdef DEBUG
BUG_ON(1);
#endif
}
no_match:
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCReturnInt(0);
match:
/* this sigmatch matched, inspect the next one. If it was the last,
* the buffer portion of the signature matched. */
if (!smd->is_last) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1,
f, buffer, buffer_len, stream_start_offset, inspection_mode, data);
SCReturnInt(r);
}
final_match:
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
SCReturnInt(1);
}
Vulnerability Type:
CWE ID:
Summary: In Suricata before 4.x, it was possible to trigger lots of redundant checks on the content of crafted network traffic with a certain signature, because of DetectEngineContentInspection in detect-engine-content-inspection.c. The search engine doesn't stop when it should after no match is found; instead, it stops only upon reaching inspection-recursion-limit (3000 by default).
Commit Message: detect: avoid needless recursive scanning
Don't recursively inspect a detect list if the recursion
doesn't increase chance of success.
|
Low
| 167,721
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel)
{
uint16 shortv;
uint32 w, l, tw, tl;
int bychunk;
(void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
if (shortv != config && bitspersample != 8 && samplesperpixel > 1) {
fprintf(stderr,
"%s: Cannot handle different planar configuration w/ bits/sample != 8\n",
TIFFFileName(in));
return (NULL);
}
TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l);
if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) {
uint32 irps = (uint32) -1L;
TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps);
/* if biased, force decoded copying to allow image subtraction */
bychunk = !bias && (rowsperstrip == irps);
}else{ /* either in or out is tiled */
if (bias) {
fprintf(stderr,
"%s: Cannot handle tiled configuration w/bias image\n",
TIFFFileName(in));
return (NULL);
}
if (TIFFIsTiled(out)) {
if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw))
tw = w;
if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl))
tl = l;
bychunk = (tw == tilewidth && tl == tilelength);
} else { /* out's not, so in must be tiled */
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
bychunk = (tw == w && tl == rowsperstrip);
}
}
#define T 1
#define F 0
#define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e)))
switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) {
/* Strips -> Tiles */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T):
return cpContigStrips2ContigTiles;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T):
return cpContigStrips2SeparateTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T):
return cpSeparateStrips2ContigTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T):
return cpSeparateStrips2SeparateTiles;
/* Tiles -> Tiles */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T):
return cpContigTiles2ContigTiles;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T):
return cpContigTiles2SeparateTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T):
return cpSeparateTiles2ContigTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T):
return cpSeparateTiles2SeparateTiles;
/* Tiles -> Strips */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T):
return cpContigTiles2ContigStrips;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T):
return cpContigTiles2SeparateStrips;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T):
return cpSeparateTiles2ContigStrips;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T):
return cpSeparateTiles2SeparateStrips;
/* Strips -> Strips */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F):
return bias ? cpBiasedContig2Contig : cpContig2ContigByRow;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T):
return cpDecodedStrips;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T):
return cpContig2SeparateByRow;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T):
return cpSeparate2ContigByRow;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T):
return cpSeparate2SeparateByRow;
}
#undef pack
#undef F
#undef T
fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n",
TIFFFileName(in));
return (NULL);
}
Vulnerability Type: Exec Code Overflow
CWE ID: CWE-119
Summary: LibTIFF version 4.0.7 is vulnerable to a heap buffer overflow in the tools/tiffcp resulting in DoS or code execution via a crafted BitsPerSample value.
Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and
cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and
http://bugzilla.maptools.org/show_bug.cgi?id=2657
|
Low
| 168,414
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: OMX_ERRORTYPE omx_vdec::free_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_U32 port,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned int nPortIndex;
(void) hComp;
DEBUG_PRINT_LOW("In for decoder free_buffer");
if (m_state == OMX_StateIdle &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
DEBUG_PRINT_LOW(" free buffer while Component in Loading pending");
} else if ((m_inp_bEnabled == OMX_FALSE && port == OMX_CORE_INPUT_PORT_INDEX)||
(m_out_bEnabled == OMX_FALSE && port == OMX_CORE_OUTPUT_PORT_INDEX)) {
DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port);
} else if ((port == OMX_CORE_INPUT_PORT_INDEX &&
BITMASK_PRESENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING)) ||
(port == OMX_CORE_OUTPUT_PORT_INDEX &&
BITMASK_PRESENT(&m_flags, OMX_COMPONENT_OUTPUT_ENABLE_PENDING))) {
DEBUG_PRINT_LOW("Free Buffer while port %u enable pending", (unsigned int)port);
} else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) {
DEBUG_PRINT_ERROR("Invalid state to free buffer,ports need to be disabled");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
return OMX_ErrorIncorrectStateOperation;
} else if (m_state != OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Invalid state to free buffer,port lost Buffers");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
}
if (port == OMX_CORE_INPUT_PORT_INDEX) {
/*Check if arbitrary bytes*/
if (!arbitrary_bytes && !input_use_buffer)
nPortIndex = buffer - m_inp_mem_ptr;
else
nPortIndex = buffer - m_inp_heap_ptr;
DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %d", nPortIndex);
if (nPortIndex < drv_ctx.ip_buf.actualcount) {
BITMASK_CLEAR(&m_inp_bm_count,nPortIndex);
BITMASK_CLEAR(&m_heap_inp_bm_count,nPortIndex);
if (input_use_buffer == true) {
DEBUG_PRINT_LOW("Free pmem Buffer index %d",nPortIndex);
if (m_phdr_pmem_ptr)
free_input_buffer(m_phdr_pmem_ptr[nPortIndex]);
} else {
if (arbitrary_bytes) {
if (m_phdr_pmem_ptr)
free_input_buffer(nPortIndex,m_phdr_pmem_ptr[nPortIndex]);
else
free_input_buffer(nPortIndex,NULL);
} else
free_input_buffer(buffer);
}
m_inp_bPopulated = OMX_FALSE;
if(release_input_done())
release_buffers(this, VDEC_BUFFER_TYPE_INPUT);
/*Free the Buffer Header*/
if (release_input_done()) {
DEBUG_PRINT_HIGH("ALL input buffers are freed/released");
free_input_buffer_header();
}
} else {
DEBUG_PRINT_ERROR("Error: free_buffer ,Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING)
&& release_input_done()) {
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING);
post_event(OMX_CommandPortDisable,
OMX_CORE_INPUT_PORT_INDEX,
OMX_COMPONENT_GENERATE_EVENT);
}
} else if (port == OMX_CORE_OUTPUT_PORT_INDEX) {
nPortIndex = buffer - client_buffers.get_il_buf_hdr();
if (nPortIndex < drv_ctx.op_buf.actualcount) {
DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %d", nPortIndex);
BITMASK_CLEAR(&m_out_bm_count,nPortIndex);
m_out_bPopulated = OMX_FALSE;
client_buffers.free_output_buffer (buffer);
if(release_output_done()) {
release_buffers(this, VDEC_BUFFER_TYPE_OUTPUT);
}
if (release_output_done()) {
free_output_buffer_header();
}
} else {
DEBUG_PRINT_ERROR("Error: free_buffer , Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING)
&& release_output_done()) {
DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it");
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING);
#ifdef _ANDROID_ICS_
if (m_enable_android_native_buffers) {
DEBUG_PRINT_LOW("FreeBuffer - outport disabled: reset native buffers");
memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS));
}
#endif
post_event(OMX_CommandPortDisable,
OMX_CORE_OUTPUT_PORT_INDEX,
OMX_COMPONENT_GENERATE_EVENT);
}
} else {
eRet = OMX_ErrorBadPortIndex;
}
if ((eRet == OMX_ErrorNone) &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
if (release_done()) {
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING);
post_event(OMX_CommandStateSet, OMX_StateLoaded,
OMX_COMPONENT_GENERATE_EVENT);
}
}
return eRet;
}
Vulnerability Type: Overflow +Priv
CWE ID: CWE-119
Summary: The mm-video-v4l2 vdec component 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-06-01 mishandles a buffer count, which allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27661749.
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers
Allow only up to 64 buffers on input/output port (since the
allocation bitmap is only 64-wide).
Do not allow changing theactual buffer count while still
holding allocation (Client can technically negotiate
buffer count on a free/disabled port)
Add safety checks to free only as many buffers were allocated.
Fixes: Security Vulnerability - Heap Overflow and Possible Local
Privilege Escalation in MediaServer (libOmxVdec problem #3)
Bug: 27532282 27661749
Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523
|
Medium
| 173,785
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
if (err != OK) {
mMetaDataSize = -1ll;
mContentType = "";
mSniffedMIME = "";
{
sp<DataSource> dataSource = mDataSource;
sp<NuCachedSource2> cachedSource = mCachedSource;
sp<DataSource> httpSource = mHttpSource;
{
Mutex::Autolock _l(mDisconnectLock);
mDataSource.clear();
mCachedSource.clear();
mHttpSource.clear();
}
}
cancelPollBuffering();
}
notifyPrepared(err);
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: The NuPlayer::GenericSource::notifyPreparedAndCleanup function in media/libmediaplayerservice/nuplayer/GenericSource.cpp in mediaserver in Android 5.x before 5.1.1 LMY49G and 6.x before 2016-02-01 improperly manages mDrmManagerClient objects, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, aka internal bug 25070434.
Commit Message: GenericSource: reset mDrmManagerClient when mDataSource is cleared.
Bug: 25070434
Change-Id: Iade3472c496ac42456e42db35e402f7b66416f5b
(cherry picked from commit b41fd0d4929f0a89811bafcc4fd944b128f00ce2)
|
Low
| 173,969
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: const BlockEntry* Segment::GetBlock(const CuePoint& cp,
const CuePoint::TrackPosition& tp) {
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < tp.m_pos)
i = k + 1;
else if (pos > tp.m_pos)
j = k;
else
return pCluster->GetEntry(cp, tp);
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster->GetEntry(cp, tp);
}
Vulnerability Type: DoS Exec Code Mem. Corr.
CWE ID: CWE-20
Summary: libvpx in libwebm 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-06-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted mkv file, aka internal bug 23167726.
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
|
Medium
| 173,814
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: long mkvparser::UnserializeString(
IMkvReader* pReader,
long long pos,
long long size_,
char*& str)
{
delete[] str;
str = NULL;
if (size_ >= LONG_MAX) //we need (size+1) chars
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
str = new (std::nothrow) char[size+1];
if (str == NULL)
return -1;
unsigned char* const buf = reinterpret_cast<unsigned char*>(str);
const long status = pReader->Read(pos, size, buf);
if (status)
{
delete[] str;
str = NULL;
return status;
}
str[size] = '\0';
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
|
Low
| 174,449
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb);
struct hstate *h = hstate_inode(dentry->d_inode);
buf->f_type = HUGETLBFS_MAGIC;
buf->f_bsize = huge_page_size(h);
if (sbinfo) {
spin_lock(&sbinfo->stat_lock);
/* If no limits set, just report 0 for max/free/used
* blocks, like simple_statfs() */
if (sbinfo->max_blocks >= 0) {
buf->f_blocks = sbinfo->max_blocks;
buf->f_bavail = buf->f_bfree = sbinfo->free_blocks;
buf->f_files = sbinfo->max_inodes;
buf->f_ffree = sbinfo->free_inodes;
}
spin_unlock(&sbinfo->stat_lock);
}
buf->f_namelen = NAME_MAX;
return 0;
}
Vulnerability Type: DoS +Priv
CWE ID: CWE-399
Summary: Use-after-free vulnerability in the Linux kernel before 3.3.6, when huge pages are enabled, allows local users to cause a denial of service (system crash) or possibly gain privileges by interacting with a hugetlbfs filesystem, as demonstrated by a umount operation that triggers improper handling of quota data.
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <abarry@cray.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Cc: Hugh Dickins <hughd@google.com>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Minchan Kim <minchan.kim@gmail.com>
Cc: Hillf Danton <dhillf@gmail.com>
Cc: Paul Mackerras <paulus@samba.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
|
High
| 165,607
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void br_mdb_notify(struct net_device *dev, struct net_bridge_port *port,
struct br_ip *group, int type)
{
struct br_mdb_entry entry;
entry.ifindex = port->dev->ifindex;
entry.addr.proto = group->proto;
entry.addr.u.ip4 = group->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
entry.addr.u.ip6 = group->u.ip6;
#endif
__br_mdb_notify(dev, &entry, type);
}
Vulnerability Type: +Info
CWE ID: CWE-399
Summary: net/bridge/br_mdb.c in the Linux kernel before 3.8.4 does not initialize certain structures, which allows local users to obtain sensitive information from kernel memory via a crafted application.
Commit Message: bridge: fix mdb info leaks
The bridging code discloses heap and stack bytes via the RTM_GETMDB
netlink interface and via the notify messages send to group RTNLGRP_MDB
afer a successful add/del.
Fix both cases by initializing all unset members/padding bytes with
memset(0).
Cc: Stephen Hemminger <stephen@networkplumber.org>
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Medium
| 166,054
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void InitPrefMembers() {
settings_->InitPrefMembers();
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: An off by one error resulting in an allocation of zero size in FFmpeg in Google Chrome prior to 54.0.2840.98 for Mac, and 54.0.2840.99 for Windows, and 54.0.2840.100 for Linux, and 55.0.2883.84 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted video file.
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
|
Medium
| 172,560
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
if (getGraphicBufferSource() != NULL) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: An information disclosure vulnerability 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, 6.x before 2016-11-01, and 7.0 before 2016-11-01 could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Android ID: A-29422020.
Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer
Bug: 29422020
Bug: 31412859
Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375
(cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2)
|
Medium
| 174,145
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return offset;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return offset;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
&nbuf[doff + 0x7c]) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: The ELF parser (readelf.c) in file before 5.21 allows remote attackers to cause a denial of service (CPU consumption or crash) via a large number of (1) program or (2) section headers or (3) invalid capabilities.
Commit Message: - limit the number of program and section header number of sections to be
processed to avoid excessive processing time.
- if a bad note is found, return 0 to stop processing immediately.
|
Low
| 169,903
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline ||
h263type->eLevel != OMX_VIDEO_H263Level45 ||
(h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
h263type->bPLUSPTYPEAllowed != OMX_FALSE ||
h263type->bForceRoundingTypeToZero != OMX_FALSE ||
h263type->nPictureHeaderRepetition != 0 ||
h263type->nGOBHeaderInterval != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore ||
mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 ||
(mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
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_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(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
|
Medium
| 174,210
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: bool DeserializeNotificationDatabaseData(const std::string& input,
NotificationDatabaseData* output) {
DCHECK(output);
NotificationDatabaseDataProto message;
if (!message.ParseFromString(input))
return false;
output->notification_id = message.notification_id();
output->origin = GURL(message.origin());
output->service_worker_registration_id =
message.service_worker_registration_id();
PlatformNotificationData* notification_data = &output->notification_data;
const NotificationDatabaseDataProto::NotificationData& payload =
message.notification_data();
notification_data->title = base::UTF8ToUTF16(payload.title());
switch (payload.direction()) {
case NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT:
notification_data->direction =
PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT;
break;
case NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT:
notification_data->direction =
PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT;
break;
case NotificationDatabaseDataProto::NotificationData::AUTO:
notification_data->direction = PlatformNotificationData::DIRECTION_AUTO;
break;
}
notification_data->lang = payload.lang();
notification_data->body = base::UTF8ToUTF16(payload.body());
notification_data->tag = payload.tag();
notification_data->icon = GURL(payload.icon());
if (payload.vibration_pattern().size() > 0) {
notification_data->vibration_pattern.assign(
payload.vibration_pattern().begin(), payload.vibration_pattern().end());
}
notification_data->timestamp =
base::Time::FromInternalValue(payload.timestamp());
notification_data->silent = payload.silent();
notification_data->require_interaction = payload.require_interaction();
if (payload.data().length()) {
notification_data->data.assign(payload.data().begin(),
payload.data().end());
}
for (const auto& payload_action : payload.actions()) {
PlatformNotificationAction action;
action.action = payload_action.action();
action.title = base::UTF8ToUTF16(payload_action.title());
notification_data->actions.push_back(action);
}
return true;
}
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}
|
Low
| 171,629
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Integer overflow in the SplFileObject::fread function in spl_directory.c in the SPL extension in PHP before 5.5.37 and 5.6.x before 5.6.23 allows remote attackers to cause a denial of service or possibly have unspecified other impact via a large integer argument, a related issue to CVE-2016-5096.
Commit Message: Fix bug #72262 - do not overflow int
|
Low
| 167,066
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BoundingBox "viewbox"
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
/*
Open image.
*/
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);
}
if ((image->columns == 0) || (image->rows == 0))
{
char
primitive[MaxTextExtent];
register char
*p;
SegmentInfo
bounds;
/*
Determine size of image canvas.
*/
while (ReadBlobString(image,primitive) != (char *) NULL)
{
for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ;
if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0)
continue;
(void) sscanf(p,"viewbox %lf %lf %lf %lf",&bounds.x1,&bounds.y1,
&bounds.x2,&bounds.y2);
image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5);
image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5);
break;
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/
DefaultResolution;
draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/
DefaultResolution;
image->columns=(size_t) (draw_info->affine.sx*image->columns);
image->rows=(size_t) (draw_info->affine.sy*image->rows);
if (SetImageBackgroundColor(image) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Render drawing.
*/
if (GetBlobStreamData(image) == (unsigned char *) NULL)
draw_info->primitive=FileToString(image->filename,~0UL,exception);
else
{
draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1);
if (draw_info->primitive != (char *) NULL)
{
CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image),
GetBlobSize(image));
draw_info->primitive[GetBlobSize(image)]='\0';
}
}
(void) DrawImage(image,draw_info);
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,585
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void XMLHttpRequest::genericError()
{
clearResponse();
clearRequest();
m_error = true;
changeState(DONE);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in core/xml/XMLHttpRequest.cpp in Blink, as used in Google Chrome before 30.0.1599.101, allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger multiple conflicting uses of the same XMLHttpRequest object.
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
Medium
| 171,168
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Vulnerability Type:
CWE ID: CWE-476
Summary: In radare 2.0.1, a pointer wraparound vulnerability exists in store_versioninfo_gnu_verdef() in libr/bin/format/elf/elf.c.
Commit Message: Fix #8764 - huge vd_aux caused pointer wraparound
|
Medium
| 167,688
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int get_gate_page(struct mm_struct *mm, unsigned long address,
unsigned int gup_flags, struct vm_area_struct **vma,
struct page **page)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int ret = -EFAULT;
/* user gate pages are read-only */
if (gup_flags & FOLL_WRITE)
return -EFAULT;
if (address > TASK_SIZE)
pgd = pgd_offset_k(address);
else
pgd = pgd_offset_gate(mm, address);
BUG_ON(pgd_none(*pgd));
p4d = p4d_offset(pgd, address);
BUG_ON(p4d_none(*p4d));
pud = pud_offset(p4d, address);
BUG_ON(pud_none(*pud));
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd))
return -EFAULT;
VM_BUG_ON(pmd_trans_huge(*pmd));
pte = pte_offset_map(pmd, address);
if (pte_none(*pte))
goto unmap;
*vma = get_gate_vma(mm);
if (!page)
goto out;
*page = vm_normal_page(*vma, address, *pte);
if (!*page) {
if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
goto unmap;
*page = pte_page(*pte);
/*
* This should never happen (a device public page in the gate
* area).
*/
if (is_device_public_page(*page))
goto unmap;
}
get_page(*page);
out:
ret = 0;
unmap:
pte_unmap(pte);
return ret;
}
Vulnerability Type: Overflow
CWE ID: CWE-416
Summary: The Linux kernel before 5.1-rc5 allows page->_refcount reference count overflow, with resultant use-after-free issues, if about 140 GiB of RAM exists. This is related to fs/fuse/dev.c, fs/pipe.c, fs/splice.c, include/linux/mm.h, include/linux/pipe_fs_i.h, kernel/trace/trace.c, mm/gup.c, and mm/hugetlb.c. It can occur with FUSE requests.
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
|
Low
| 170,224
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_,
long long size_) {
const long long stop = start_ + size_;
long long pos = start_;
m_track = -1;
m_pos = -1;
m_block = 1; // default
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x77) // CueTrack ID
m_track = UnserializeUInt(pReader, pos, size);
else if (id == 0x71) // CueClusterPos ID
m_pos = UnserializeUInt(pReader, pos, size);
else if (id == 0x1378) // CueBlockNumber
m_block = UnserializeUInt(pReader, pos, size);
pos += size; // consume payload
assert(pos <= stop);
}
assert(m_pos >= 0);
assert(m_track > 0);
}
Vulnerability Type: DoS Exec Code Mem. Corr.
CWE ID: CWE-20
Summary: libvpx in libwebm 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-06-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted mkv file, aka internal bug 23167726.
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
|
Medium
| 173,837
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
Vulnerability Type:
CWE ID: CWE-476
Summary: Unchecked NULL pointer usage when parsing invalid atoms in ExprResolveLhs in xkbcomp/expr.c in xkbcommon before 0.8.2 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because lookup failures are mishandled.
Commit Message: Fail expression lookup on invalid atoms
If we fail atom lookup, then we should not claim that we successfully
looked up the expression.
Signed-off-by: Daniel Stone <daniels@collabora.com>
|
Low
| 169,091
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int l2cap_build_conf_req(struct sock *sk, void *data)
{
struct l2cap_pinfo *pi = l2cap_pi(sk);
struct l2cap_conf_req *req = data;
struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
void *ptr = req->data;
BT_DBG("sk %p", sk);
switch (pi->mode) {
case L2CAP_MODE_BASIC:
if (pi->imtu != L2CAP_DEFAULT_MTU)
l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->imtu);
break;
case L2CAP_MODE_ERTM:
rfc.mode = L2CAP_MODE_ERTM;
rfc.txwin_size = L2CAP_DEFAULT_RX_WINDOW;
rfc.max_transmit = L2CAP_DEFAULT_MAX_RECEIVE;
rfc.retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO);
rfc.monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO);
rfc.max_pdu_size = cpu_to_le16(L2CAP_DEFAULT_MAX_RX_APDU);
l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,
sizeof(rfc), (unsigned long) &rfc);
break;
}
/* FIXME: Need actual value of the flush timeout */
req->dcid = cpu_to_le16(pi->dcid);
req->flags = cpu_to_le16(0);
return ptr - data;
}
Vulnerability Type: Exec Code Overflow
CWE ID: CWE-119
Summary: The native Bluetooth stack in the Linux Kernel (BlueZ), starting at the Linux kernel version 2.6.32 and up to and including 4.13.1, are vulnerable to a stack overflow vulnerability in the processing of L2CAP configuration responses resulting in Remote code execution in kernel space.
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <gustavo@las.ic.unicamp.br>
Signed-off-by: Marcel Holtmann <marcel@holtmann.org>
|
Low
| 167,621
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: cid_parse_font_matrix( CID_Face face,
CID_Parser* parser )
{
CID_FaceDict dict;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
{
FT_Matrix* matrix;
FT_Vector* offset;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
(void)cid_parser_to_fixed_array( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The (1) t1_parse_font_matrix function in type1/t1load.c, (2) cid_parse_font_matrix function in cid/cidload.c, (3) t42_parse_font_matrix function in type42/t42parse.c, and (4) ps_parser_load_field function in psaux/psobjs.c in FreeType before 2.5.4 do not check return values, which allows remote attackers to cause a denial of service (uninitialized memory access and application crash) or possibly have unspecified other impact via a crafted font.
Commit Message:
|
Low
| 165,341
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int orangefs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
int error = 0;
void *value = NULL;
size_t size = 0;
const char *name = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
umode_t mode = inode->i_mode;
/*
* can we represent this with the traditional file
* mode permission bits?
*/
error = posix_acl_equiv_mode(acl, &mode);
if (error < 0) {
gossip_err("%s: posix_acl_equiv_mode err: %d\n",
__func__,
error);
return error;
}
if (inode->i_mode != mode)
SetModeFlag(orangefs_inode);
inode->i_mode = mode;
mark_inode_dirty_sync(inode);
if (error == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
gossip_err("%s: invalid type %d!\n", __func__, type);
return -EINVAL;
}
gossip_debug(GOSSIP_ACL_DEBUG,
"%s: inode %pU, key %s type %d\n",
__func__, get_khandle_from_ino(inode),
name,
type);
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (error < 0)
goto out;
}
gossip_debug(GOSSIP_ACL_DEBUG,
"%s: name %s, value %p, size %zd, acl %p\n",
__func__, name, value, size, acl);
/*
* Go ahead and set the extended attribute now. NOTE: Suppose acl
* was NULL, then value will be NULL and size will be 0 and that
* will xlate to a removexattr. However, we don't want removexattr
* complain if attributes does not exist.
*/
error = orangefs_inode_setxattr(inode, name, value, size, 0);
out:
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
Vulnerability Type: +Priv
CWE ID: CWE-285
Summary: The filesystem implementation in the Linux kernel through 4.8.2 preserves the setgid bit during a setxattr call, which allows local users to gain group privileges by leveraging the existence of a setgid program with restrictions on execute permissions.
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>
|
Low
| 166,977
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void Cues::Init() const {
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) // CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; // consume payload
assert(pos <= stop);
}
}
Vulnerability Type: DoS Exec Code Mem. Corr.
CWE ID: CWE-20
Summary: libvpx in libwebm 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-06-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted mkv file, aka internal bug 23167726.
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
|
Medium
| 173,827
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length)
{
png_alloc_size_t limit = PNG_UINT_31_MAX;
# ifdef PNG_SET_USER_LIMITS_SUPPORTED
if (png_ptr->user_chunk_malloc_max > 0 &&
png_ptr->user_chunk_malloc_max < limit)
limit = png_ptr->user_chunk_malloc_max;
# elif PNG_USER_CHUNK_MALLOC_MAX > 0
if (PNG_USER_CHUNK_MALLOC_MAX < limit)
limit = PNG_USER_CHUNK_MALLOC_MAX;
# endif
if (png_ptr->chunk_name == png_IDAT)
{
png_alloc_size_t idat_limit = PNG_UINT_31_MAX;
size_t row_factor =
(png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1)
+ 1 + (png_ptr->interlaced? 6: 0));
if (png_ptr->height > PNG_UINT_32_MAX/row_factor)
idat_limit=PNG_UINT_31_MAX;
else
idat_limit = png_ptr->height * row_factor;
row_factor = row_factor > 32566? 32566 : row_factor;
idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */
idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;
limit = limit < idat_limit? idat_limit : limit;
}
if (length > limit)
{
png_debug2(0," length = %lu, limit = %lu",
(unsigned long)length,(unsigned long)limit);
png_chunk_error(png_ptr, "chunk data is too large");
}
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: In libpng 1.6.34, a wrong calculation of row_factor in the png_check_chunk_length function (pngrutil.c) may trigger an integer overflow and resultant divide-by-zero while processing a crafted PNG file, leading to a denial of service.
Commit Message: [libpng16] Fix the calculation of row_factor in png_check_chunk_length
(Bug report by Thuan Pham, SourceForge issue #278)
|
Medium
| 169,151
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() {
DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult();
if (!array_buffer) {
RejectPromise(kAllocationFailureImageBitmapRejectionReason);
return;
}
ScheduleAsyncImageBitmapDecoding(array_buffer);
}
Vulnerability Type:
CWE ID: CWE-416
Summary: Incorrect object lifecycle management in Blink in Google Chrome prior to 72.0.3626.81 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Marijn Kruisselbrink <mek@chromium.org>
Cr-Commit-Position: refs/heads/master@{#616342}
|
Medium
| 173,066
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int init_nss_hash(struct crypto_instance *instance)
{
PK11SlotInfo* hash_slot = NULL;
SECItem hash_param;
if (!hash_to_nss[instance->crypto_hash_type]) {
return 0;
}
hash_param.type = siBuffer;
hash_param.data = 0;
hash_param.len = 0;
hash_slot = PK11_GetBestSlot(hash_to_nss[instance->crypto_hash_type], NULL);
if (hash_slot == NULL) {
log_printf(instance->log_level_security, "Unable to find security slot (err %d)",
PR_GetError());
return -1;
}
instance->nss_sym_key_sign = PK11_ImportSymKey(hash_slot,
hash_to_nss[instance->crypto_hash_type],
PK11_OriginUnwrap, CKA_SIGN,
&hash_param, NULL);
if (instance->nss_sym_key_sign == NULL) {
log_printf(instance->log_level_security, "Failure to import key into NSS (err %d)",
PR_GetError());
return -1;
}
PK11_FreeSlot(hash_slot);
return 0;
}
Vulnerability Type: DoS
CWE ID:
Summary: The init_nss_hash function in exec/totemcrypto.c in Corosync 2.0 before 2.3 does not properly initialize the HMAC key, which allows remote attackers to cause a denial of service (crash) via a crafted packet.
Commit Message: totemcrypto: fix hmac key initialization
Signed-off-by: Fabio M. Di Nitto <fdinitto@redhat.com>
Reviewed-by: Jan Friesse <jfriesse@redhat.com>
|
Low
| 166,546
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static const char *parse_object( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '{' ) {
/* Not an object! */
ep = value;
return 0;
}
item->type = cJSON_Object;
value =skip( value + 1 );
if ( *value == '}' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0;
if ( ! ( value = skip( parse_string( child, skip( value ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_string( child, skip( value + 1 ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
}
if ( *value == '}' )
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 <bmah@es.net>
|
Low
| 167,303
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: read_header(struct archive_read *a, struct archive_entry *entry,
char head_type)
{
const void *h;
const char *p, *endp;
struct rar *rar;
struct rar_header rar_header;
struct rar_file_header file_header;
int64_t header_size;
unsigned filename_size, end;
char *filename;
char *strp;
char packed_size[8];
char unp_size[8];
int ttime;
struct archive_string_conv *sconv, *fn_sconv;
unsigned long crc32_val;
int ret = (ARCHIVE_OK), ret2;
rar = (struct rar *)(a->format->data);
/* Setup a string conversion object for non-rar-unicode filenames. */
sconv = rar->opt_sconv;
if (sconv == NULL) {
if (!rar->init_default_conversion) {
rar->sconv_default =
archive_string_default_conversion_for_read(
&(a->archive));
rar->init_default_conversion = 1;
}
sconv = rar->sconv_default;
}
if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
return (ARCHIVE_FATAL);
p = h;
memcpy(&rar_header, p, sizeof(rar_header));
rar->file_flags = archive_le16dec(rar_header.flags);
header_size = archive_le16dec(rar_header.size);
if (header_size < (int64_t)sizeof(file_header) + 7) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid header size");
return (ARCHIVE_FATAL);
}
crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2);
__archive_read_consume(a, 7);
if (!(rar->file_flags & FHD_SOLID))
{
rar->compression_method = 0;
rar->packed_size = 0;
rar->unp_size = 0;
rar->mtime = 0;
rar->ctime = 0;
rar->atime = 0;
rar->arctime = 0;
rar->mode = 0;
memset(&rar->salt, 0, sizeof(rar->salt));
rar->atime = 0;
rar->ansec = 0;
rar->ctime = 0;
rar->cnsec = 0;
rar->mtime = 0;
rar->mnsec = 0;
rar->arctime = 0;
rar->arcnsec = 0;
}
else
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"RAR solid archive support unavailable.");
return (ARCHIVE_FATAL);
}
if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
return (ARCHIVE_FATAL);
/* File Header CRC check. */
crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7));
if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Header CRC error");
return (ARCHIVE_FATAL);
}
/* If no CRC error, Go on parsing File Header. */
p = h;
endp = p + header_size - 7;
memcpy(&file_header, p, sizeof(file_header));
p += sizeof(file_header);
rar->compression_method = file_header.method;
ttime = archive_le32dec(file_header.file_time);
rar->mtime = get_time(ttime);
rar->file_crc = archive_le32dec(file_header.file_crc);
if (rar->file_flags & FHD_PASSWORD)
{
archive_entry_set_is_data_encrypted(entry, 1);
rar->has_encrypted_entries = 1;
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"RAR encryption support unavailable.");
/* Since it is only the data part itself that is encrypted we can at least
extract information about the currently processed entry and don't need
to return ARCHIVE_FATAL here. */
/*return (ARCHIVE_FATAL);*/
}
if (rar->file_flags & FHD_LARGE)
{
memcpy(packed_size, file_header.pack_size, 4);
memcpy(packed_size + 4, p, 4); /* High pack size */
p += 4;
memcpy(unp_size, file_header.unp_size, 4);
memcpy(unp_size + 4, p, 4); /* High unpack size */
p += 4;
rar->packed_size = archive_le64dec(&packed_size);
rar->unp_size = archive_le64dec(&unp_size);
}
else
{
rar->packed_size = archive_le32dec(file_header.pack_size);
rar->unp_size = archive_le32dec(file_header.unp_size);
}
if (rar->packed_size < 0 || rar->unp_size < 0)
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid sizes specified.");
return (ARCHIVE_FATAL);
}
rar->bytes_remaining = rar->packed_size;
/* TODO: RARv3 subblocks contain comments. For now the complete block is
* consumed at the end.
*/
if (head_type == NEWSUB_HEAD) {
size_t distance = p - (const char *)h;
header_size += rar->packed_size;
/* Make sure we have the extended data. */
if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
return (ARCHIVE_FATAL);
p = h;
endp = p + header_size - 7;
p += distance;
}
filename_size = archive_le16dec(file_header.name_size);
if (p + filename_size > endp) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid filename size");
return (ARCHIVE_FATAL);
}
if (rar->filename_allocated < filename_size * 2 + 2) {
char *newptr;
size_t newsize = filename_size * 2 + 2;
newptr = realloc(rar->filename, newsize);
if (newptr == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Couldn't allocate memory.");
return (ARCHIVE_FATAL);
}
rar->filename = newptr;
rar->filename_allocated = newsize;
}
filename = rar->filename;
memcpy(filename, p, filename_size);
filename[filename_size] = '\0';
if (rar->file_flags & FHD_UNICODE)
{
if (filename_size != strlen(filename))
{
unsigned char highbyte, flagbits, flagbyte;
unsigned fn_end, offset;
end = filename_size;
fn_end = filename_size * 2;
filename_size = 0;
offset = (unsigned)strlen(filename) + 1;
highbyte = *(p + offset++);
flagbits = 0;
flagbyte = 0;
while (offset < end && filename_size < fn_end)
{
if (!flagbits)
{
flagbyte = *(p + offset++);
flagbits = 8;
}
flagbits -= 2;
switch((flagbyte >> flagbits) & 3)
{
case 0:
filename[filename_size++] = '\0';
filename[filename_size++] = *(p + offset++);
break;
case 1:
filename[filename_size++] = highbyte;
filename[filename_size++] = *(p + offset++);
break;
case 2:
filename[filename_size++] = *(p + offset + 1);
filename[filename_size++] = *(p + offset);
offset += 2;
break;
case 3:
{
char extra, high;
uint8_t length = *(p + offset++);
if (length & 0x80) {
extra = *(p + offset++);
high = (char)highbyte;
} else
extra = high = 0;
length = (length & 0x7f) + 2;
while (length && filename_size < fn_end) {
unsigned cp = filename_size >> 1;
filename[filename_size++] = high;
filename[filename_size++] = p[cp] + extra;
length--;
}
}
break;
}
}
if (filename_size > fn_end) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid filename");
return (ARCHIVE_FATAL);
}
filename[filename_size++] = '\0';
/*
* Do not increment filename_size here as the computations below
* add the space for the terminating NUL explicitly.
*/
filename[filename_size] = '\0';
/* Decoded unicode form is UTF-16BE, so we have to update a string
* conversion object for it. */
if (rar->sconv_utf16be == NULL) {
rar->sconv_utf16be = archive_string_conversion_from_charset(
&a->archive, "UTF-16BE", 1);
if (rar->sconv_utf16be == NULL)
return (ARCHIVE_FATAL);
}
fn_sconv = rar->sconv_utf16be;
strp = filename;
while (memcmp(strp, "\x00\x00", 2))
{
if (!memcmp(strp, "\x00\\", 2))
*(strp + 1) = '/';
strp += 2;
}
p += offset;
} else {
/*
* If FHD_UNICODE is set but no unicode data, this file name form
* is UTF-8, so we have to update a string conversion object for
* it accordingly.
*/
if (rar->sconv_utf8 == NULL) {
rar->sconv_utf8 = archive_string_conversion_from_charset(
&a->archive, "UTF-8", 1);
if (rar->sconv_utf8 == NULL)
return (ARCHIVE_FATAL);
}
fn_sconv = rar->sconv_utf8;
while ((strp = strchr(filename, '\\')) != NULL)
*strp = '/';
p += filename_size;
}
}
else
{
fn_sconv = sconv;
while ((strp = strchr(filename, '\\')) != NULL)
*strp = '/';
p += filename_size;
}
/* Split file in multivolume RAR. No more need to process header. */
if (rar->filename_save &&
filename_size == rar->filename_save_size &&
!memcmp(rar->filename, rar->filename_save, filename_size + 1))
{
__archive_read_consume(a, header_size - 7);
rar->cursor++;
if (rar->cursor >= rar->nodes)
{
rar->nodes++;
if ((rar->dbo =
realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL)
{
archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
return (ARCHIVE_FATAL);
}
rar->dbo[rar->cursor].header_size = header_size;
rar->dbo[rar->cursor].start_offset = -1;
rar->dbo[rar->cursor].end_offset = -1;
}
if (rar->dbo[rar->cursor].start_offset < 0)
{
rar->dbo[rar->cursor].start_offset = a->filter->position;
rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +
rar->packed_size;
}
return ret;
}
rar->filename_save = (char*)realloc(rar->filename_save,
filename_size + 1);
memcpy(rar->filename_save, rar->filename, filename_size + 1);
rar->filename_save_size = filename_size;
/* Set info for seeking */
free(rar->dbo);
if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)
{
archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
return (ARCHIVE_FATAL);
}
rar->dbo[0].header_size = header_size;
rar->dbo[0].start_offset = -1;
rar->dbo[0].end_offset = -1;
rar->cursor = 0;
rar->nodes = 1;
if (rar->file_flags & FHD_SALT)
{
if (p + 8 > endp) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid header size");
return (ARCHIVE_FATAL);
}
memcpy(rar->salt, p, 8);
p += 8;
}
if (rar->file_flags & FHD_EXTTIME) {
if (read_exttime(p, rar, endp) < 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid header size");
return (ARCHIVE_FATAL);
}
}
__archive_read_consume(a, header_size - 7);
rar->dbo[0].start_offset = a->filter->position;
rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;
switch(file_header.host_os)
{
case OS_MSDOS:
case OS_OS2:
case OS_WIN32:
rar->mode = archive_le32dec(file_header.file_attr);
if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)
rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
else
rar->mode = AE_IFREG;
rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
break;
case OS_UNIX:
case OS_MAC_OS:
case OS_BEOS:
rar->mode = archive_le32dec(file_header.file_attr);
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown file attributes from RAR file's host OS");
return (ARCHIVE_FATAL);
}
rar->bytes_uncopied = rar->bytes_unconsumed = 0;
rar->lzss.position = rar->offset = 0;
rar->offset_seek = 0;
rar->dictionary_size = 0;
rar->offset_outgoing = 0;
rar->br.cache_avail = 0;
rar->br.avail_in = 0;
rar->crc_calculated = 0;
rar->entry_eof = 0;
rar->valid = 1;
rar->is_ppmd_block = 0;
rar->start_new_table = 1;
free(rar->unp_buffer);
rar->unp_buffer = NULL;
rar->unp_offset = 0;
rar->unp_buffer_size = UNP_BUFFER_SIZE;
memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
__archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
rar->ppmd_valid = rar->ppmd_eod = 0;
/* Don't set any archive entries for non-file header types */
if (head_type == NEWSUB_HEAD)
return ret;
archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);
archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);
archive_entry_set_atime(entry, rar->atime, rar->ansec);
archive_entry_set_size(entry, rar->unp_size);
archive_entry_set_mode(entry, rar->mode);
if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))
{
if (errno == ENOMEM)
{
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname cannot be converted from %s to current locale.",
archive_string_conversion_charset_name(fn_sconv));
ret = (ARCHIVE_WARN);
}
if (((rar->mode) & AE_IFMT) == AE_IFLNK)
{
/* Make sure a symbolic-link file does not have its body. */
rar->bytes_remaining = 0;
archive_entry_set_size(entry, 0);
/* Read a symbolic-link name. */
if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))
return ret2;
if (ret > ret2)
ret = ret2;
}
if (rar->bytes_remaining == 0)
rar->entry_eof = 1;
return ret;
}
Vulnerability Type:
CWE ID: CWE-416
Summary: libarchive version commit 416694915449219d505531b1096384f3237dd6cc onwards (release v3.1.0 onwards) contains a CWE-416: Use After Free vulnerability in RAR decoder - libarchive/archive_read_support_format_rar.c that can result in Crash/DoS - it is unknown if RCE is possible. This attack appear to be exploitable via the victim must open a specially crafted RAR archive.
Commit Message: rar: file split across multi-part archives must match
Fuzzing uncovered some UAF and memory overrun bugs where a file in a
single file archive reported that it was split across multiple
volumes. This was caused by ppmd7 operations calling
rar_br_fillup. This would invoke rar_read_ahead, which would in some
situations invoke archive_read_format_rar_read_header. That would
check the new file name against the old file name, and if they didn't
match up it would free the ppmd7 buffer and allocate a new
one. However, because the ppmd7 decoder wasn't actually done with the
buffer, it would continue to used the freed buffer. Both reads and
writes to the freed region can be observed.
This is quite tricky to solve: once the buffer has been freed it is
too late, as the ppmd7 decoder functions almost universally assume
success - there's no way for ppmd_read to signal error, nor are there
good ways for functions like Range_Normalise to propagate them. So we
can't detect after the fact that we're in an invalid state - e.g. by
checking rar->cursor, we have to prevent ourselves from ever ending up
there. So, when we are in the dangerous part or rar_read_ahead that
assumes a valid split, we set a flag force read_header to either go
down the path for split files or bail. This means that the ppmd7
decoder keeps a valid buffer and just runs out of data.
Found with a combination of AFL, afl-rb and qsym.
|
Medium
| 168,931
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL;
PGconn *pgsql;
smart_str str = {0};
zval **args[5];
int i, connect_type = 0;
PGresult *pg_result;
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5
|| zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) {
WRONG_PARAM_COUNT;
}
smart_str_appends(&str, "pgsql");
for (i = 0; i < ZEND_NUM_ARGS(); i++) {
/* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections
* can re-use this connection. Bug #39979
*/
if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE_PP(args[i]) == IS_LONG) {
if (Z_LVAL_PP(args[1]) == PGSQL_CONNECT_FORCE_NEW) {
continue;
} else if (Z_LVAL_PP(args[1]) & PGSQL_CONNECT_FORCE_NEW) {
smart_str_append_long(&str, Z_LVAL_PP(args[1]) ^ PGSQL_CONNECT_FORCE_NEW);
}
}
convert_to_string_ex(args[i]);
smart_str_appendc(&str, '_');
smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i]));
}
smart_str_0(&str);
if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */
connstring = Z_STRVAL_PP(args[0]);
} else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */
connstring = Z_STRVAL_PP(args[0]);
convert_to_long_ex(args[1]);
connect_type = Z_LVAL_PP(args[1]);
} else {
host = Z_STRVAL_PP(args[0]);
port = Z_STRVAL_PP(args[1]);
dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]);
switch (ZEND_NUM_ARGS()) {
case 5:
tty = Z_STRVAL_PP(args[3]);
/* fall through */
case 4:
options = Z_STRVAL_PP(args[2]);
break;
}
}
if (persistent && PGG(allow_persistent)) {
zend_rsrc_list_entry *le;
/* try to find if we already have this link in our persistent list */
if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) { /* we don't */
zend_rsrc_list_entry new_le;
if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Cannot create new link. Too many open links (%ld)", PGG(num_links));
goto err;
}
if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent));
goto err;
}
/* create the link */
if (connstring) {
pgsql=PQconnectdb(connstring);
} else {
pgsql=PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql)
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* hash it up */
Z_TYPE(new_le) = le_plink;
new_le.ptr = pgsql;
if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
goto err;
}
PGG(num_links)++;
PGG(num_persistent)++;
} else { /* we do */
if (Z_TYPE_P(le) != le_plink) {
RETURN_FALSE;
}
/* ensure that the link did not die */
if (PGG(auto_reset_persistent) & 1) {
/* need to send & get something from backend to
make sure we catch CONNECTION_BAD everytime */
PGresult *pg_result;
pg_result = PQexec(le->ptr, "select 1");
PQclear(pg_result);
}
if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */
if (le->ptr == NULL) {
if (connstring) {
le->ptr=PQconnectdb(connstring);
} else {
le->ptr=PQsetdb(host,port,options,tty,dbname);
}
}
else {
PQreset(le->ptr);
}
if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect");
zend_hash_del(&EG(persistent_list),str.c,str.len+1);
goto err;
}
}
pgsql = (PGconn *) le->ptr;
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) {
#else
if (atof(PG_VERSION) >= 7.2) {
#endif
pg_result = PQexec(pgsql, "RESET ALL;");
PQclear(pg_result);
}
}
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink);
} else { /* Non persistent connection */
zend_rsrc_list_entry *index_ptr,new_index_ptr;
/* first we check the hash for the hashed_details key. if it exists,
* it should point us to the right offset where the actual pgsql link sits.
* if it doesn't, open a new pgsql link, add it to the resource list,
* and add a pointer to it with hashed_details as the key.
*/
if (!(connect_type & PGSQL_CONNECT_FORCE_NEW)
&& zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) {
int type;
ulong link;
void *ptr;
if (Z_TYPE_P(index_ptr) != le_index_ptr) {
RETURN_FALSE;
}
link = (ulong) index_ptr->ptr;
ptr = zend_list_find(link,&type); /* check if the link is still there */
if (ptr && (type==le_link || type==le_plink)) {
Z_LVAL_P(return_value) = link;
zend_list_addref(link);
php_pgsql_set_default_link(link TSRMLS_CC);
Z_TYPE_P(return_value) = IS_RESOURCE;
goto cleanup;
} else {
zend_hash_del(&EG(regular_list),str.c,str.len+1);
}
}
if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links));
goto err;
}
if (connstring) {
pgsql = PQconnectdb(connstring);
} else {
pgsql = PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* add it to the list */
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link);
/* add it to the hash */
new_index_ptr.ptr = (void *) Z_LVAL_P(return_value);
Z_TYPE(new_index_ptr) = le_index_ptr;
if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
goto err;
}
PGG(num_links)++;
}
/* set notice processer */
if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) {
PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RESVAL_P(return_value));
}
php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC);
cleanup:
smart_str_free(&str);
return;
err:
smart_str_free(&str);
RETURN_FALSE;
}
/* }}} */
#if 0
/* {{{ php_pgsql_get_default_link
*/
static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS)
{
if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */
ht = 0;
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
return PGG(default_link);
}
/* }}} */
#endif
/* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)
Open a PostgreSQL connection */
PHP_FUNCTION(pg_connect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
/* }}} */
/* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)
Open a persistent PostgreSQL connection */
PHP_FUNCTION(pg_pconnect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1);
}
/* }}} */
/* {{{ proto bool pg_close([resource connection])
Close a PostgreSQL connection */
PHP_FUNCTION(pg_close)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (id==-1) { /* explicit resource number */
zend_list_delete(Z_RESVAL_P(pgsql_link));
}
if (id!=-1
|| (pgsql_link && Z_RESVAL_P(pgsql_link)==PGG(default_link))) {
zend_list_delete(PGG(default_link));
PGG(default_link) = -1;
}
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DBNAME 1
#define PHP_PG_ERROR_MESSAGE 2
#define PHP_PG_OPTIONS 3
#define PHP_PG_PORT 4
#define PHP_PG_TTY 5
#define PHP_PG_HOST 6
#define PHP_PG_VERSION 7
/* {{{ php_pgsql_get_link_info
*/
static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
char *msgbuf;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
switch(entry_type) {
case PHP_PG_DBNAME:
Z_STRVAL_P(return_value) = PQdb(pgsql);
break;
case PHP_PG_ERROR_MESSAGE:
RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0);
return;
case PHP_PG_OPTIONS:
Z_STRVAL_P(return_value) = PQoptions(pgsql);
break;
case PHP_PG_PORT:
Z_STRVAL_P(return_value) = PQport(pgsql);
break;
case PHP_PG_TTY:
Z_STRVAL_P(return_value) = PQtty(pgsql);
break;
case PHP_PG_HOST:
Z_STRVAL_P(return_value) = PQhost(pgsql);
break;
case PHP_PG_VERSION:
array_init(return_value);
add_assoc_string(return_value, "client", PG_VERSION, 1);
#if HAVE_PQPROTOCOLVERSION
add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql));
#if HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3) {
add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1);
}
#endif
#endif
return;
default:
RETURN_FALSE;
}
if (Z_STRVAL_P(return_value)) {
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
} else {
Z_STRLEN_P(return_value) = 0;
Z_STRVAL_P(return_value) = (char *) estrdup("");
}
Z_TYPE_P(return_value) = IS_STRING;
}
/* }}} */
/* {{{ proto string pg_dbname([resource connection])
Get the database name */
PHP_FUNCTION(pg_dbname)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME);
}
/* }}} */
/* {{{ proto string pg_last_error([resource connection])
Get the error message string */
PHP_FUNCTION(pg_last_error)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE);
}
/* }}} */
/* {{{ proto string pg_options([resource connection])
Get the options associated with the connection */
PHP_FUNCTION(pg_options)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS);
}
/* }}} */
/* {{{ proto int pg_port([resource connection])
Return the port number associated with the connection */
PHP_FUNCTION(pg_port)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT);
}
/* }}} */
/* {{{ proto string pg_tty([resource connection])
Return the tty name associated with the connection */
PHP_FUNCTION(pg_tty)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY);
}
/* }}} */
/* {{{ proto string pg_host([resource connection])
Returns the host name associated with the connection */
PHP_FUNCTION(pg_host)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST);
}
/* }}} */
/* {{{ proto array pg_version([resource connection])
Returns an array with client, protocol and server version (when available) */
PHP_FUNCTION(pg_version)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION);
}
/* }}} */
#if HAVE_PQPARAMETERSTATUS
/* {{{ proto string|false pg_parameter_status([resource connection,] string param_name)
Returns the value of a server parameter */
PHP_FUNCTION(pg_parameter_status)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
char *param;
int len;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, ¶m, &len) == SUCCESS) {
id = -1;
} else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", ¶m, &len) == SUCCESS) {
pgsql_link = NULL;
id = PGG(default_link);
} else {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
param = (char*)PQparameterStatus(pgsql, param);
if (param) {
RETURN_STRING(param, 1);
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
/* {{{ proto bool pg_ping([resource connection])
Ping database. If connection is bad, try to reconnect. */
PHP_FUNCTION(pg_ping)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
PGresult *res;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) {
id = -1;
} else {
pgsql_link = NULL;
id = PGG(default_link);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* ping connection */
res = PQexec(pgsql, "SELECT 1;");
PQclear(res);
/* check status. */
if (PQstatus(pgsql) == CONNECTION_OK)
RETURN_TRUE;
/* reset connection if it's broken */
PQreset(pgsql);
if (PQstatus(pgsql) == CONNECTION_OK) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto resource pg_query([resource connection,] string query)
Execute a query */
PHP_FUNCTION(pg_query)
{
zval *pgsql_link = NULL;
char *query;
int id = -1, query_len, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQexec(pgsql, query);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexec(pgsql, query);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED
/* {{{ _php_pgsql_free_params */
static void _php_pgsql_free_params(char **params, int num_params)
{
if (num_params > 0) {
int i;
for (i = 0; i < num_params; i++) {
if (params[i]) {
efree(params[i]);
}
}
efree(params);
}
}
/* }}} */
#endif
#if HAVE_PQEXECPARAMS
/* {{{ proto resource pg_query_params([resource connection,] string query, array params)
Execute a query */
PHP_FUNCTION(pg_query_params)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, **tmp;
char *query;
int query_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "sa", &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
for(i = 0; i < num_params; i++) {
if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
if (Z_TYPE_PP(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val = **tmp;
zval_copy_ctor(&tmp_val);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
zval_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_dtor(&tmp_val);
}
zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
}
}
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQPREPARE
/* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query)
Prepare a query for future execution */
PHP_FUNCTION(pg_prepare)
{
zval *pgsql_link = NULL;
char *query, *stmtname;
int query_len, stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQEXECPREPARED
/* {{{ proto resource pg_execute([resource connection,] string stmtname, array params)
Execute a prepared query */
PHP_FUNCTION(pg_execute)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, **tmp;
char *stmtname;
int stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
for(i = 0; i < num_params; i++) {
if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
if (Z_TYPE_PP(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val = **tmp;
zval_copy_ctor(&tmp_val);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
zval_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_dtor(&tmp_val);
}
zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
}
}
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#define PHP_PG_NUM_ROWS 1
#define PHP_PG_NUM_FIELDS 2
#define PHP_PG_CMD_TUPLES 3
/* {{{ php_pgsql_get_result_info
*/
static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
switch (entry_type) {
case PHP_PG_NUM_ROWS:
Z_LVAL_P(return_value) = PQntuples(pgsql_result);
break;
case PHP_PG_NUM_FIELDS:
Z_LVAL_P(return_value) = PQnfields(pgsql_result);
break;
case PHP_PG_CMD_TUPLES:
#if HAVE_PQCMDTUPLES
Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result));
#else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build");
Z_LVAL_P(return_value) = 0;
#endif
break;
default:
RETURN_FALSE;
}
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto int pg_num_rows(resource result)
Return the number of rows in the result */
PHP_FUNCTION(pg_num_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS);
}
/* }}} */
/* {{{ proto int pg_num_fields(resource result)
Return the number of fields in the result */
PHP_FUNCTION(pg_num_fields)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
}
/* }}} */
#if HAVE_PQCMDTUPLES
/* {{{ proto int pg_affected_rows(resource result)
Returns the number of affected tuples */
PHP_FUNCTION(pg_affected_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES);
}
/* }}} */
#endif
/* {{{ proto string pg_last_notice(resource connection)
Returns the last notice set by the backend */
PHP_FUNCTION(pg_last_notice)
{
zval *pgsql_link;
PGconn *pg_link;
int id = -1;
php_pgsql_notice **notice;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
return;
}
/* Just to check if user passed valid resoruce */
ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)¬ice) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL((*notice)->message, (*notice)->len, 1);
}
/* }}} */
/* {{{ get_field_name
*/
static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC)
{
PGresult *result;
smart_str str = {0};
zend_rsrc_list_entry *field_type;
char *ret=NULL;
/* try to lookup the type in the resource list */
smart_str_appends(&str, "pgsql_oid_");
smart_str_append_unsigned(&str, oid);
smart_str_0(&str);
if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) {
ret = estrdup((char *)field_type->ptr);
} else { /* hash all oid's */
int i,num_rows;
int oid_offset,name_offset;
char *tmp_oid, *end_ptr, *tmp_name;
zend_rsrc_list_entry new_oid_entry;
if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) {
if (result) {
PQclear(result);
}
smart_str_free(&str);
return STR_EMPTY_ALLOC();
}
num_rows = PQntuples(result);
oid_offset = PQfnumber(result,"oid");
name_offset = PQfnumber(result,"typname");
for (i=0; i<num_rows; i++) {
if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) {
continue;
}
str.len = 0;
smart_str_appends(&str, "pgsql_oid_");
smart_str_appends(&str, tmp_oid);
smart_str_0(&str);
if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) {
continue;
}
Z_TYPE(new_oid_entry) = le_string;
new_oid_entry.ptr = estrdup(tmp_name);
zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(zend_rsrc_list_entry), NULL);
if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) {
ret = estrdup(tmp_name);
}
}
PQclear(result);
}
smart_str_free(&str);
return ret;
}
/* }}} */
#ifdef HAVE_PQFTABLE
/* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only])
Returns the name of the table field belongs to, or table's oid if oid_only is true */
PHP_FUNCTION(pg_field_table)
{
zval *result;
pgsql_result_handle *pg_result;
long fnum = -1;
zend_bool return_oid = 0;
Oid oid;
smart_str hash_key = {0};
char *table_name;
zend_rsrc_list_entry *field_table;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|b", &result, &fnum, &return_oid) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (fnum < 0 || fnum >= PQnfields(pg_result->result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
oid = PQftable(pg_result->result, fnum);
if (InvalidOid == oid) {
RETURN_FALSE;
}
if (return_oid) {
#if UINT_MAX > LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */
if (oid > LONG_MAX) {
smart_str oidstr = {0};
smart_str_append_unsigned(&oidstr, oid);
smart_str_0(&oidstr);
RETURN_STRINGL(oidstr.c, oidstr.len, 0);
} else
#endif
RETURN_LONG((long)oid);
}
/* try to lookup the table name in the resource list */
smart_str_appends(&hash_key, "pgsql_table_oid_");
smart_str_append_unsigned(&hash_key, oid);
smart_str_0(&hash_key);
if (zend_hash_find(&EG(regular_list), hash_key.c, hash_key.len+1, (void **) &field_table) == SUCCESS) {
smart_str_free(&hash_key);
RETURN_STRING((char *)field_table->ptr, 1);
} else { /* Not found, lookup by querying PostgreSQL system tables */
PGresult *tmp_res;
smart_str querystr = {0};
zend_rsrc_list_entry new_field_table;
smart_str_appends(&querystr, "select relname from pg_class where oid=");
smart_str_append_unsigned(&querystr, oid);
smart_str_0(&querystr);
if ((tmp_res = PQexec(pg_result->conn, querystr.c)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
if (tmp_res) {
PQclear(tmp_res);
}
smart_str_free(&querystr);
smart_str_free(&hash_key);
RETURN_FALSE;
}
smart_str_free(&querystr);
if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
PQclear(tmp_res);
smart_str_free(&hash_key);
RETURN_FALSE;
}
Z_TYPE(new_field_table) = le_string;
new_field_table.ptr = estrdup(table_name);
zend_hash_update(&EG(regular_list), hash_key.c, hash_key.len+1, (void *) &new_field_table, sizeof(zend_rsrc_list_entry), NULL);
smart_str_free(&hash_key);
PQclear(tmp_res);
RETURN_STRING(table_name, 1);
}
}
/* }}} */
#endif
#define PHP_PG_FIELD_NAME 1
#define PHP_PG_FIELD_SIZE 2
#define PHP_PG_FIELD_TYPE 3
#define PHP_PG_FIELD_TYPE_OID 4
/* {{{ php_pgsql_get_field_info
*/
static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
long field;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
Oid oid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &field) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (field < 0 || field >= PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_FIELD_NAME:
Z_STRVAL_P(return_value) = PQfname(pgsql_result, field);
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
break;
case PHP_PG_FIELD_SIZE:
Z_LVAL_P(return_value) = PQfsize(pgsql_result, field);
Z_TYPE_P(return_value) = IS_LONG;
break;
case PHP_PG_FIELD_TYPE:
Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, field), &EG(regular_list) TSRMLS_CC);
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
break;
case PHP_PG_FIELD_TYPE_OID:
oid = PQftype(pgsql_result, field);
#if UINT_MAX > LONG_MAX
if (oid > LONG_MAX) {
smart_str s = {0};
smart_str_append_unsigned(&s, oid);
smart_str_0(&s);
Z_STRVAL_P(return_value) = s.c;
Z_STRLEN_P(return_value) = s.len;
Z_TYPE_P(return_value) = IS_STRING;
} else
#endif
{
Z_LVAL_P(return_value) = (long)oid;
Z_TYPE_P(return_value) = IS_LONG;
}
break;
default:
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string pg_field_name(resource result, int field_number)
Returns the name of the field */
PHP_FUNCTION(pg_field_name)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME);
}
/* }}} */
/* {{{ proto int pg_field_size(resource result, int field_number)
Returns the internal size of the field */
PHP_FUNCTION(pg_field_size)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE);
}
/* }}} */
/* {{{ proto string pg_field_type(resource result, int field_number)
Returns the type name for the given field */
PHP_FUNCTION(pg_field_type)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE);
}
/* }}} */
/* {{{ proto string pg_field_type_oid(resource result, int field_number)
Returns the type oid for the given field */
PHP_FUNCTION(pg_field_type_oid)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID);
}
/* }}} */
/* {{{ proto int pg_field_num(resource result, string field_name)
Returns the field number of the named field */
PHP_FUNCTION(pg_field_num)
{
zval *result;
char *field;
int field_len;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result, &field, &field_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
Z_LVAL_P(return_value) = PQfnumber(pgsql_result, field);
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)
Returns values from a result identifier */
PHP_FUNCTION(pg_fetch_result)
{
zval *result, **field=NULL;
long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
pgsql_row = row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
}
switch(Z_TYPE_PP(field)) {
case IS_STRING:
field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
break;
default:
convert_to_long_ex(field);
field_offset = Z_LVAL_PP(field);
break;
}
if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
Z_TYPE_P(return_value) = IS_NULL;
} else {
char *value = PQgetvalue(pgsql_result, pgsql_row, field_offset);
int value_len = PQgetlength(pgsql_result, pgsql_row, field_offset);
ZVAL_STRINGL(return_value, value, value_len, 1);
}
}
/* }}} */
/* {{{ void php_pgsql_fetch_hash */
static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object)
{
zval *result, *zrow = NULL;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int i, num_fields, pgsql_row, use_row;
long row = -1;
char *field_name;
zval *ctor_params = NULL;
zend_class_entry *ce = NULL;
if (into_object) {
char *class_name = NULL;
int class_name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!sz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) {
return;
}
if (!class_name) {
ce = zend_standard_class_def;
} else {
ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
}
if (!ce) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name);
return;
}
result_type = PGSQL_ASSOC;
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!l", &result, &zrow, &result_type) == FAILURE) {
return;
}
}
if (zrow == NULL) {
row = -1;
} else {
convert_to_long(zrow);
row = Z_LVAL_P(zrow);
if (row < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The row parameter must be greater or equal to zero");
RETURN_FALSE;
}
}
use_row = ZEND_NUM_ARGS() > 1 && row != -1;
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (use_row) {
pgsql_row = row;
pg_result->row = pgsql_row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
} else {
/* If 2nd param is NULL, use internal row counter to access next row */
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
pg_result->row++;
}
array_init(return_value);
for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) {
if (PQgetisnull(pgsql_result, pgsql_row, i)) {
if (result_type & PGSQL_NUM) {
add_index_null(return_value, i);
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_null(return_value, field_name);
}
} else {
char *element = PQgetvalue(pgsql_result, pgsql_row, i);
if (element) {
char *data;
int data_len;
int should_copy=0;
const uint element_len = strlen(element);
data = safe_estrndup(element, element_len);
data_len = element_len;
if (result_type & PGSQL_NUM) {
add_index_stringl(return_value, i, data, data_len, should_copy);
should_copy=1;
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_stringl(return_value, field_name, data, data_len, should_copy);
}
}
}
}
if (into_object) {
zval dataset = *return_value;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *retval_ptr;
object_and_properties_init(return_value, ce, NULL);
zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
if (ce->constructor) {
fci.size = sizeof(fci);
fci.function_table = &ce->function_table;
fci.function_name = NULL;
fci.symbol_table = NULL;
fci.object_ptr = return_value;
fci.retval_ptr_ptr = &retval_ptr;
if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
if (Z_TYPE_P(ctor_params) == IS_ARRAY) {
HashTable *ht = Z_ARRVAL_P(ctor_params);
Bucket *p;
fci.param_count = 0;
fci.params = safe_emalloc(sizeof(zval***), ht->nNumOfElements, 0);
p = ht->pListHead;
while (p != NULL) {
fci.params[fci.param_count++] = (zval**)p->pData;
p = p->pListNext;
}
} else {
/* Two problems why we throw exceptions here: PHP is typeless
* and hence passing one argument that's not an array could be
* by mistake and the other way round is possible, too. The
* single value is an array. Also we'd have to make that one
* argument passed by reference.
*/
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC);
return;
}
} else {
fci.param_count = 0;
fci.params = NULL;
}
fci.no_separation = 1;
fcc.initialized = 1;
fcc.function_handler = ce->constructor;
fcc.calling_scope = EG(scope);
fcc.called_scope = Z_OBJCE_P(return_value);
fcc.object_ptr = return_value;
if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name);
} else {
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
}
if (fci.params) {
efree(fci.params);
}
} else if (ctor_params) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name);
}
}
}
/* }}} */
/* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]])
Get a row as an enumerated array */
PHP_FUNCTION(pg_fetch_row)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_assoc(resource result [, int row])
Fetch a row as an assoc array */
PHP_FUNCTION(pg_fetch_assoc)
{
/* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when
there is 3rd parameter */
if (ZEND_NUM_ARGS() > 2)
WRONG_PARAM_COUNT;
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]])
Fetch a row as an array */
PHP_FUNCTION(pg_fetch_array)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0);
}
/* }}} */
/* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])
Fetch a row as an object */
PHP_FUNCTION(pg_fetch_object)
{
/* pg_fetch_object() allowed result_type used to be. 3rd parameter
must be allowed for compatibility */
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1);
}
/* }}} */
/* {{{ proto array pg_fetch_all(resource result)
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
array_init(return_value);
if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) {
zval_dtor(return_value);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto array pg_fetch_all_columns(resource result [, int column_number])
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all_columns)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
unsigned long colno=0;
int pg_numrows, pg_row;
size_t num_fields;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
num_fields = PQnfields(pgsql_result);
if (colno >= num_fields || colno < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno);
RETURN_FALSE;
}
array_init(return_value);
if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
return;
}
for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
if (PQgetisnull(pgsql_result, pg_row, colno)) {
add_next_index_null(return_value);
} else {
add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1);
}
}
}
/* }}} */
/* {{{ proto bool pg_result_seek(resource result, int offset)
Set internal row offset */
PHP_FUNCTION(pg_result_seek)
{
zval *result;
long row;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (row < 0 || row >= PQntuples(pg_result->result)) {
RETURN_FALSE;
}
/* seek to offset */
pg_result->row = row;
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DATA_LENGTH 1
#define PHP_PG_DATA_ISNULL 2
/* {{{ php_pgsql_data_info
*/
static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result, **field;
long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
pgsql_row = row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
}
switch(Z_TYPE_PP(field)) {
case IS_STRING:
convert_to_string_ex(field);
field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
break;
default:
convert_to_long_ex(field);
field_offset = Z_LVAL_PP(field);
break;
}
if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_DATA_LENGTH:
Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset);
break;
case PHP_PG_DATA_ISNULL:
Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset);
break;
}
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)
Returns the printed length */
PHP_FUNCTION(pg_field_prtlen)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH);
}
/* }}} */
/* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)
Test if a field is NULL */
PHP_FUNCTION(pg_field_is_null)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL);
}
/* }}} */
/* {{{ proto bool pg_free_result(resource result)
Free result memory */
PHP_FUNCTION(pg_free_result)
{
zval *result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (Z_LVAL_P(result) == 0) {
RETURN_FALSE;
}
zend_list_delete(Z_RESVAL_P(result));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string pg_last_oid(resource result)
Returns the last object identifier */
PHP_FUNCTION(pg_last_oid)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
#ifdef HAVE_PQOIDVALUE
Oid oid;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
#ifdef HAVE_PQOIDVALUE
oid = PQoidValue(pgsql_result);
if (oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(oid);
#else
Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result);
if (Z_STRVAL_P(return_value)) {
RETURN_STRING(Z_STRVAL_P(return_value), 1);
}
RETURN_STRING("", 1);
#endif
}
/* }}} */
/* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]])
Enable tracing a PostgreSQL connection */
PHP_FUNCTION(pg_trace)
{
char *z_filename, *mode = "w";
int z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = PGG(default_link);
if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_untrace([resource connection])
Disable tracing of a PostgreSQL connection */
PHP_FUNCTION(pg_untrace)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
PQuntrace(pgsql);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid])
Create a large object */
PHP_FUNCTION(pg_lo_create)
{
zval *pgsql_link = NULL, *oid = NULL;
PGconn *pgsql;
Oid pgsql_oid, wanted_oid = InvalidOid;
int id = -1, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|zz", &pgsql_link, &oid) == FAILURE) {
return;
}
if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) {
oid = pgsql_link;
pgsql_link = NULL;
}
if (pgsql_link == NULL) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
if (id == -1) {
RETURN_FALSE;
}
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_CREATE
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL");
#else
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (long)InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
#endif
}
if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid)
Delete a large object */
PHP_FUNCTION(pg_lo_unlink)
{
zval *pgsql_link = NULL;
long oid_long;
char *oid_string, *end_ptr;
int oid_strlen;
PGconn *pgsql;
Oid oid;
int id = -1;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid type is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rl", &pgsql_link, &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"s", &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"l", &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_unlink(pgsql, oid) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode)
Open a large object and return fd */
PHP_FUNCTION(pg_lo_open)
{
zval *pgsql_link = NULL;
long oid_long;
char *oid_string, *end_ptr, *mode_string;
int oid_strlen, mode_strlen;
PGconn *pgsql;
Oid oid;
int id = -1, pgsql_mode=0, pgsql_lofd;
int create=0;
pgLofp *pgsql_lofp;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of
faster to type. Unfortunately, doesn't behave the same way as fopen()...
(Jouni)
*/
if (strchr(mode_string, 'r') == mode_string) {
pgsql_mode |= INV_READ;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_WRITE;
}
}
if (strchr(mode_string, 'w') == mode_string) {
pgsql_mode |= INV_WRITE;
create = 1;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_READ;
}
}
pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp));
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (create) {
if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
} else {
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (lo_unlink(pgsql, oid) == -1) {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP");
RETURN_FALSE;
}
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC);
Z_TYPE_P(return_value) = IS_LONG;
}
}
} else {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
}
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
}
}
/* }}} */
/* {{{ proto bool pg_lo_close(resource large_object)
Close a large object */
PHP_FUNCTION(pg_lo_close)
{
zval *pgsql_lofp;
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_lofp) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_lofp, -1, "PostgreSQL large object", le_lofp);
if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd);
RETVAL_FALSE;
} else {
RETVAL_TRUE;
}
zend_list_delete(Z_RESVAL_P(pgsql_lofp));
return;
}
/* }}} */
#define PGSQL_LO_READ_BUF_SIZE 8192
/* {{{ proto string pg_lo_read(resource large_object [, int len])
Read a large object */
PHP_FUNCTION(pg_lo_read)
{
zval *pgsql_id;
long len;
int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes, argc = ZEND_NUM_ARGS();
char *buf;
pgLofp *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &pgsql_id, &len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (argc > 1) {
buf_len = len;
}
buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0);
if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) {
efree(buf);
RETURN_FALSE;
}
buf[nbytes] = '\0';
RETURN_STRINGL(buf, nbytes, 0);
}
/* }}} */
/* {{{ proto int pg_lo_write(resource large_object, string buf [, int len])
Write a large object */
PHP_FUNCTION(pg_lo_write)
{
zval *pgsql_id;
char *str;
long z_len;
int str_len, nbytes;
int len;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) {
return;
}
if (argc > 2) {
if (z_len > str_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld", str_len, z_len);
RETURN_FALSE;
}
if (z_len < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", z_len);
RETURN_FALSE;
}
len = z_len;
}
else {
len = str_len;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) {
RETURN_FALSE;
}
RETURN_LONG(nbytes);
}
/* }}} */
/* {{{ proto int pg_lo_read_all(resource large_object)
Read a large object and send straight to browser */
PHP_FUNCTION(pg_lo_read_all)
{
zval *pgsql_id;
int tbytes;
volatile int nbytes;
char buf[PGSQL_LO_READ_BUF_SIZE];
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
tbytes = 0;
while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) {
PHPWRITE(buf, nbytes);
tbytes += nbytes;
}
RETURN_LONG(tbytes);
}
/* }}} */
/* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid])
Import large object direct from filesystem */
PHP_FUNCTION(pg_lo_import)
{
zval *pgsql_link = NULL, *oid = NULL;
char *file_in;
int id = -1, name_len;
int argc = ZEND_NUM_ARGS();
PGconn *pgsql;
Oid returned_oid;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) {
;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"p|z", &file_in, &name_len, &oid) == SUCCESS) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
/* old calling convention, deprecated since PHP 4.2 */
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
}
else {
WRONG_PARAM_COUNT;
}
if (php_check_open_basedir(file_in TSRMLS_CC)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_IMPORT_WITH_OID
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "OID value passing not supported");
#else
Oid wanted_oid;
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (long)InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
#endif
}
returned_oid = lo_import(pgsql, file_in);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename)
Export large object direct to filesystem */
PHP_FUNCTION(pg_lo_export)
{
zval *pgsql_link = NULL;
char *file_out, *oid_string, *end_ptr;
int oid_strlen;
int id = -1, name_len;
long oid_long;
Oid oid;
PGconn *pgsql;
int argc = ZEND_NUM_ARGS();
/* allow string to handle large OID value correctly */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"lp", &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments");
RETURN_FALSE;
}
if (php_check_open_basedir(file_out TSRMLS_CC)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_export(pgsql, oid, file_out)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence])
Seeks position of large object */
PHP_FUNCTION(pg_lo_seek)
{
zval *pgsql_id = NULL;
long offset = 0, whence = SEEK_CUR;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) {
return;
}
if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter");
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence) > -1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int pg_lo_tell(resource large_object)
Returns current position of large object */
PHP_FUNCTION(pg_lo_tell)
{
zval *pgsql_id = NULL;
int offset = 0;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
RETURN_LONG(offset);
}
/* }}} */
#if HAVE_PQSETERRORVERBOSITY
/* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity)
Set error verbosity */
PHP_FUNCTION(pg_set_error_verbosity)
{
zval *pgsql_link = NULL;
long verbosity;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "l", &verbosity) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_link, &verbosity) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) {
Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, verbosity);
Z_TYPE_P(return_value) = IS_LONG;
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
#ifdef HAVE_PQCLIENTENCODING
/* {{{ proto int pg_set_client_encoding([resource connection,] string encoding)
Set client encoding */
PHP_FUNCTION(pg_set_client_encoding)
{
char *encoding;
int encoding_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "s", &encoding, &encoding_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, encoding);
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto string pg_client_encoding([resource connection])
Get the current client encoding */
PHP_FUNCTION(pg_client_encoding)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* Just do the same as found in PostgreSQL sources... */
Z_STRVAL_P(return_value) = (char *) pg_encoding_to_char(PQclientEncoding(pgsql));
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
}
/* }}} */
#endif
#if !HAVE_PQGETCOPYDATA
#define COPYBUFSIZ 8192
#endif
/* {{{ proto bool pg_end_copy([resource connection])
Sync with backend. Completes the Copy command */
PHP_FUNCTION(pg_end_copy)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
int result = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQendcopy(pgsql);
if (result!=0) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_put_line([resource connection,] string query)
Send null-terminated string to backend server*/
PHP_FUNCTION(pg_put_line)
{
char *query;
zval *pgsql_link = NULL;
int query_len, id = -1;
PGconn *pgsql;
int result = 0, argc = ZEND_NUM_ARGS();
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQputline(pgsql, query);
if (result==EOF) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])
Copy table to array */
PHP_FUNCTION(pg_copy_to)
{
zval *pgsql_link;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
int table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0;
char *query;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int copydone = 0;
#if !HAVE_PQGETCOPYDATA
char copybuf[COPYBUFSIZ];
#endif
char *csv = (char *)NULL;
int ret;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss",
&pgsql_link, &table_name, &table_name_len,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!pg_null_as) {
pg_null_as = safe_estrdup("\\\\N");
free_pg_null = 1;
}
spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (free_pg_null) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_OUT:
if (pgsql_result) {
PQclear(pgsql_result);
array_init(return_value);
#if HAVE_PQGETCOPYDATA
while (!copydone)
{
ret = PQgetCopyData(pgsql, &csv, 0);
switch (ret) {
case -1:
copydone = 1;
break;
case 0:
case -2:
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
break;
default:
add_next_index_string(return_value, csv, 1);
PQfreemem(csv);
break;
}
}
#else
while (!copydone)
{
if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) {
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
}
if (copybuf[0] == '\\' &&
copybuf[1] == '.' &&
copybuf[2] == '\0')
{
copydone = 1;
}
else
{
if (csv == (char *)NULL) {
csv = estrdup(copybuf);
} else {
csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1));
strcat(csv, copybuf);
}
switch (ret)
{
case EOF:
copydone = 1;
case 0:
add_next_index_string(return_value, csv, 1);
efree(csv);
csv = (char *)NULL;
break;
case 1:
break;
}
}
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])
Copy table from array */
PHP_FUNCTION(pg_copy_from)
{
zval *pgsql_link = NULL, *pg_rows;
zval **tmp;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
int table_name_len, pg_delim_len, pg_null_as_len;
int pg_null_as_free = 0;
char *query;
HashPosition pos;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rsa|ss",
&pgsql_link, &table_name, &table_name_len, &pg_rows,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
if (!pg_null_as) {
pg_null_as = safe_estrdup("\\\\N");
pg_null_as_free = 1;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (pg_null_as_free) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_IN:
if (pgsql_result) {
int command_failed = 0;
PQclear(pgsql_result);
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
#if HAVE_PQPUTCOPYDATA
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
}
if (PQputCopyData(pgsql, query, strlen(query)) != 1) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
}
if (PQputCopyEnd(pgsql, NULL) != 1) {
PHP_PQ_ERROR("putcopyend failed: %s", pgsql);
RETURN_FALSE;
}
#else
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
}
if (PQputline(pgsql, query)==EOF) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
}
if (PQputline(pgsql, "\\.\n") == EOF) {
PHP_PQ_ERROR("putline failed: %s", pgsql);
RETURN_FALSE;
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
command_failed = 1;
}
PQclear(pgsql_result);
}
if (command_failed) {
RETURN_FALSE;
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
RETURN_TRUE;
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
#ifdef HAVE_PQESCAPE
/* {{{ proto string pg_escape_string([resource connection,] string data)
Escape string for text/char type */
PHP_FUNCTION(pg_escape_string)
{
char *from = NULL, *to = NULL;
zval *pgsql_link;
#ifdef HAVE_PQESCAPE_CONN
PGconn *pgsql;
#endif
int to_len;
int from_len;
int id = -1;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = PGG(default_link);
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
to = (char *) safe_emalloc(from_len, 2, 1);
#ifdef HAVE_PQESCAPE_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL);
} else
#endif
to_len = (int) PQescapeString(to, from, (size_t)from_len);
RETURN_STRINGL(to, to_len, 0);
}
/* }}} */
/* {{{ proto string pg_escape_bytea([resource connection,] string data)
Escape binary for bytea type */
PHP_FUNCTION(pg_escape_bytea)
{
char *from = NULL, *to = NULL;
size_t to_len;
int from_len, id = -1;
#ifdef HAVE_PQESCAPE_BYTEA_CONN
PGconn *pgsql;
#endif
zval *pgsql_link;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = PGG(default_link);
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
#ifdef HAVE_PQESCAPE_BYTEA_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len);
} else
#endif
to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */
PQfreemem(to);
}
/* }}} */
#if !HAVE_PQUNESCAPEBYTEA
/* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users.
Renamed to php_pgsql_unescape_bytea() */
/*
* PQunescapeBytea - converts the null terminated string representation
* of a bytea, strtext, into binary, filling a buffer. It returns a
* pointer to the buffer which is NULL on error, and the size of the
* buffer in retbuflen. The pointer may subsequently be used as an
* argument to the function free(3). It is the reverse of PQescapeBytea.
*
* The following transformations are reversed:
* '\0' == ASCII 0 == \000
* '\'' == ASCII 39 == \'
* '\\' == ASCII 92 == \\
*
* States:
* 0 normal 0->1->2->3->4
* 1 \ 1->5
* 2 \0 1->6
* 3 \00
* 4 \000
* 5 \'
* 6 \\
*/
static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen)
{
size_t buflen;
unsigned char *buffer,
*sp,
*bp;
unsigned int state = 0;
if (strtext == NULL)
return NULL;
buflen = strlen(strtext); /* will shrink, also we discover if
* strtext */
buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */
for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++)
{
Vulnerability Type: Bypass
CWE ID: CWE-254
Summary: PHP before 5.4.40, 5.5.x before 5.5.24, and 5.6.x before 5.6.8 does not ensure that pathnames lack %00 sequences, which might allow remote attackers to read arbitrary files via crafted input to an application that calls the stream_resolve_include_path function in ext/standard/streamsfuncs.c, as demonstrated by a filename\0.extension attack that bypasses an intended configuration in which client users may read files with only one specific extension.
Commit Message:
|
Low
| 165,315
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t *qop_state, gss_iov_buffer_desc *iov,
int iov_count)
{
return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov,
iov_count);
}
Vulnerability Type: DoS
CWE ID: CWE-18
Summary: lib/gssapi/spnego/spnego_mech.c in MIT Kerberos 5 (aka krb5) before 1.14 relies on an inappropriate context handle, which allows remote attackers to cause a denial of service (incorrect pointer read and process crash) via a crafted SPNEGO packet that is mishandled during a gss_inquire_context call.
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[ghudson@mit.edu: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
|
Medium
| 166,670
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int sysMapFile(const char* fn, MemMapping* pMap)
{
memset(pMap, 0, sizeof(*pMap));
if (fn && fn[0] == '@') {
FILE* mapf = fopen(fn+1, "r");
if (mapf == NULL) {
LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno));
return -1;
}
if (sysMapBlockFile(mapf, pMap) != 0) {
LOGW("Map of '%s' failed\n", fn);
return -1;
}
fclose(mapf);
} else {
int fd = open(fn, O_RDONLY, 0);
if (fd < 0) {
LOGE("Unable to open '%s': %s\n", fn, strerror(errno));
return -1;
}
if (sysMapFD(fd, pMap) != 0) {
LOGE("Map of '%s' failed\n", fn);
close(fd);
return -1;
}
close(fd);
}
return 0;
}
Vulnerability Type: Overflow +Priv
CWE ID: CWE-189
Summary: Multiple integer overflows in minzip/SysUtil.c in the Recovery Procedure in Android 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-04-01 allow attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 26960931.
Commit Message: Fix integer overflows in recovery procedure.
Bug: 26960931
Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf
(cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b)
|
Low
| 173,905
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: bool nodeHasRole(Node* node, const String& role) {
if (!node || !node->isElementNode())
return false;
return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role);
}
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,930
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
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
|
Low
| 174,331
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int remove_bond(const bt_bdaddr_t *bd_addr)
{
/* sanity check */
if (interface_ready() == FALSE)
return BT_STATUS_NOT_READY;
return btif_dm_remove_bond(bd_addr);
}
Vulnerability Type: +Priv
CWE ID: CWE-20
Summary: Bluetooth in Android 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01 allows local users to gain privileges by establishing a pairing that remains present during a session of the primary user, aka internal bug 27410683.
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
|
Medium
| 173,552
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
}
Vulnerability Type:
CWE ID: CWE-476
Summary: Unchecked NULL pointer usage in LookupModMask in xkbcomp/expr.c in xkbcommon before 0.8.2 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file with invalid virtual modifiers.
Commit Message: xkbcomp: Don't explode on invalid virtual modifiers
testcase: 'virtualModifiers=LevelThreC'
Signed-off-by: Daniel Stone <daniels@collabora.com>
|
Low
| 169,089
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: CreateSampleTransformNodeWithElementId() {
TransformPaintPropertyNode::State state;
state.matrix.Rotate(90);
state.origin = FloatPoint3D(100, 100, 0);
state.direct_compositing_reasons = CompositingReason::k3DTransform;
state.compositor_element_id = CompositorElementId(3);
return TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(),
std::move(state));
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 47.0.2526.73 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <trchen@chromium.org>
> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org>
> Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#554653}
TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#563930}
|
Low
| 171,818
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
Vulnerability Type: Dir. Trav.
CWE ID: CWE-22
Summary: Directory traversal vulnerability in device-linux.c in the router advertisement daemon (radvd) before 1.8.2 allows local users to overwrite arbitrary files, and remote attackers to overwrite certain files, via a .. (dot dot) in an interface name. NOTE: this can be leveraged with a symlink to overwrite arbitrary files.
Commit Message: set_interface_var() doesn't check interface name and blindly does
fopen(path "/" ifname, "w") on it. As "ifname" is an untrusted input, it
should be checked for ".." and/or "/" in it. Otherwise, an infected
unprivileged daemon may overwrite contents of file named "mtu",
"hoplimit", etc. in arbitrary location with arbitrary 32-bit value in
decimal representation ("%d"). If an attacker has a local account or
may create arbitrary symlinks with these names in any location (e.g.
/tmp), any file may be overwritten with a decimal value.
|
Low
| 166,550
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
{
jpc_siz_t *siz;
jpc_cod_t *cod;
jpc_qcd_t *qcd;
int i;
long startoff;
long mainhdrlen;
jpc_enc_cp_t *cp;
jpc_qcc_t *qcc;
jpc_enc_tccp_t *tccp;
uint_fast16_t cmptno;
jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
jpc_fix_t mctsynweight;
jpc_enc_tcp_t *tcp;
jpc_tsfb_t *tsfb;
jpc_tsfb_band_t *bandinfo;
uint_fast16_t numbands;
uint_fast16_t bandno;
uint_fast16_t rlvlno;
uint_fast16_t analgain;
jpc_fix_t absstepsize;
char buf[1024];
jpc_com_t *com;
cp = enc->cp;
startoff = jas_stream_getrwcount(enc->out);
/* Write SOC marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
return -1;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SOC marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
/* Write SIZ marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
return -1;
}
siz = &enc->mrk->parms.siz;
siz->caps = 0;
siz->xoff = cp->imgareatlx;
siz->yoff = cp->imgareatly;
siz->width = cp->refgrdwidth;
siz->height = cp->refgrdheight;
siz->tilexoff = cp->tilegrdoffx;
siz->tileyoff = cp->tilegrdoffy;
siz->tilewidth = cp->tilewidth;
siz->tileheight = cp->tileheight;
siz->numcomps = cp->numcmpts;
siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
assert(siz->comps);
for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
siz->comps[i].prec = cp->ccps[i].prec;
siz->comps[i].sgnd = cp->ccps[i].sgnd;
siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SIZ marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
return -1;
}
sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
com = &enc->mrk->parms.com;
com->len = JAS_CAST(uint_fast16_t, strlen(buf));
com->regid = JPC_COM_LATIN;
if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {
abort();
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COM marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#if 0
if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
return -1;
}
crg = &enc->mrk->parms.crg;
crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write CRG marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#endif
tcp = &cp->tcp;
tccp = &cp->tccp;
for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
bandinfos);
jpc_tsfb_destroy(tsfb);
mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
numbands = 3 * tccp->maxrlvls - 2;
for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
++bandno, ++bandinfo) {
rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
rlvlno, bandinfo->orient);
if (!tcp->intmode) {
absstepsize = jpc_fix_div(jpc_inttofix(1 <<
(analgain + 1)), bandinfo->synenergywt);
} else {
absstepsize = jpc_inttofix(1);
}
cp->ccps[cmptno].stepsizes[bandno] =
jpc_abstorelstepsize(absstepsize,
cp->ccps[cmptno].prec + analgain);
}
cp->ccps[cmptno].numstepsizes = numbands;
}
if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
return -1;
}
cod = &enc->mrk->parms.cod;
cod->csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
cod->compparms.numrlvls = cp->tccp.maxrlvls;
cod->prg = cp->tcp.prg;
cod->numlyrs = cp->tcp.numlyrs;
cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
cod->compparms.cblksty = cp->tccp.cblksty;
cod->compparms.qmfbid = cp->tccp.qmfbid;
cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
if (tccp->csty & JPC_COX_PRT) {
for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
}
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COD marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
return -1;
}
qcd = &enc->mrk->parms.qcd;
qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
qcd->compparms.numguard = cp->tccp.numgbits;
qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
return -1;
}
/* We do not want the step size array to be freed! */
qcd->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
tccp = &cp->tccp;
for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
return -1;
}
qcc = &enc->mrk->parms.qcc;
qcc->compno = cmptno;
qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
qcc->compparms.numguard = cp->tccp.numgbits;
qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
return -1;
}
/* We do not want the step size array to be freed! */
qcc->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
}
#define MAINTLRLEN 2
mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
enc->len += mainhdrlen;
if (enc->cp->totalsize != UINT_FAST32_MAX) {
uint_fast32_t overhead;
overhead = mainhdrlen + MAINTLRLEN;
enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
(enc->cp->totalsize - overhead) : 0;
} else {
enc->mainbodysize = UINT_FAST32_MAX;
}
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,720
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void BaseAudioContext::Initialize() {
if (IsDestinationInitialized())
return;
FFTFrame::Initialize();
audio_worklet_ = AudioWorklet::Create(this);
if (destination_node_) {
destination_node_->Handler().Initialize();
listener_ = AudioListener::Create(*this);
}
}
Vulnerability Type:
CWE ID: CWE-416
Summary: A use after free in WebAudio 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: Audio thread should not access destination node
The AudioDestinationNode is an object managed by Oilpan so the audio
thread should not access it. However, the audio thread needs
information (currentTime, etc) from the destination node. So instead
of accessing the audio destination handler (a scoped_refptr) via the
destination node, add a new member to the base audio context that
holds onto the destination handler.
The destination handler is not an oilpan object and lives at least as
long as the base audio context.
Bug: 860626, 860522, 863951
Test: Test case from 860522 doesn't crash on asan build
Change-Id: I3add844d4eb8fdc7e05b89292938b843a0abbb99
Reviewed-on: https://chromium-review.googlesource.com/1138974
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#575509}
|
Medium
| 173,175
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int handle_vmon(struct kvm_vcpu *vcpu)
{
int ret;
gpa_t vmptr;
struct page *page;
struct vcpu_vmx *vmx = to_vmx(vcpu);
const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
| FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
/*
* The Intel VMX Instruction Reference lists a bunch of bits that are
* prerequisite to running VMXON, most notably cr4.VMXE must be set to
* 1 (see vmx_set_cr4() for when we allow the guest to set this).
* Otherwise, we should fail with #UD. But most faulting conditions
* have already been checked by hardware, prior to the VM-exit for
* VMXON. We do test guest cr4.VMXE because processor CR4 always has
* that bit set to 1 in non-root mode.
*/
if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (vmx->nested.vmxon) {
nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
return kvm_skip_emulated_instruction(vcpu);
}
if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
!= VMXON_NEEDED_FEATURES) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (nested_vmx_get_vmptr(vcpu, &vmptr))
return 1;
/*
* SDM 3: 24.11.5
* The first 4 bytes of VMXON region contain the supported
* VMCS revision identifier
*
* Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
* which replaces physical address width with 32
*/
if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
if (is_error_page(page)) {
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
if (*(u32 *)kmap(page) != VMCS12_REVISION) {
kunmap(page);
kvm_release_page_clean(page);
nested_vmx_failInvalid(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
kunmap(page);
kvm_release_page_clean(page);
vmx->nested.vmxon_ptr = vmptr;
ret = enter_vmx_operation(vcpu);
if (ret)
return ret;
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
Vulnerability Type: DoS
CWE ID:
Summary: In arch/x86/kvm/vmx.c in the Linux kernel before 4.17.2, when nested virtualization is used, local attackers could cause L1 KVM guests to VMEXIT, potentially allowing privilege escalations and denial of service attacks due to lack of checking of CPL.
Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions
VMX instructions executed inside a L1 VM will always trigger a VM exit
even when executed with cpl 3. This means we must perform the
privilege check in software.
Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks")
Cc: stable@vger.kernel.org
Signed-off-by: Felix Wilhelm <fwilhelm@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
|
Medium
| 169,173
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static void *etm_setup_aux(int event_cpu, void **pages,
int nr_pages, bool overwrite)
{
int cpu;
cpumask_t *mask;
struct coresight_device *sink;
struct etm_event_data *event_data = NULL;
event_data = alloc_event_data(event_cpu);
if (!event_data)
return NULL;
/*
* In theory nothing prevent tracers in a trace session from being
* associated with different sinks, nor having a sink per tracer. But
* until we have HW with this kind of topology we need to assume tracers
* in a trace session are using the same sink. Therefore go through
* the coresight bus and pick the first enabled sink.
*
* When operated from sysFS users are responsible to enable the sink
* while from perf, the perf tools will do it based on the choice made
* on the cmd line. As such the "enable_sink" flag in sysFS is reset.
*/
sink = coresight_get_enabled_sink(true);
if (!sink)
goto err;
INIT_WORK(&event_data->work, free_event_data);
mask = &event_data->mask;
/* Setup the path for each CPU in a trace session */
for_each_cpu(cpu, mask) {
struct coresight_device *csdev;
csdev = per_cpu(csdev_src, cpu);
if (!csdev)
goto err;
/*
* Building a path doesn't enable it, it simply builds a
* list of devices from source to sink that can be
* referenced later when the path is actually needed.
*/
event_data->path[cpu] = coresight_build_path(csdev, sink);
if (IS_ERR(event_data->path[cpu]))
goto err;
}
if (!sink_ops(sink)->alloc_buffer)
goto err;
/* Get the AUX specific data from the sink buffer */
event_data->snk_config =
sink_ops(sink)->alloc_buffer(sink, cpu, pages,
nr_pages, overwrite);
if (!event_data->snk_config)
goto err;
out:
return event_data;
err:
etm_free_aux(event_data);
event_data = NULL;
goto out;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The etm_setup_aux function in drivers/hwtracing/coresight/coresight-etm-perf.c in the Linux kernel before 4.10.2 allows attackers to cause a denial of service (panic) because a parameter is incorrectly used as a local variable.
Commit Message: coresight: fix kernel panic caused by invalid CPU
Commit d52c9750f150 ("coresight: reset "enable_sink" flag when need be")
caused a kernel panic because of the using of an invalid value: after
'for_each_cpu(cpu, mask)', value of local variable 'cpu' become invalid,
causes following 'cpu_to_node' access invalid memory area.
This patch brings the deleted 'cpu = cpumask_first(mask)' back.
Panic log:
$ perf record -e cs_etm// ls
Unable to handle kernel paging request at virtual address fffe801804af4f10
pgd = ffff8017ce031600
[fffe801804af4f10] *pgd=0000000000000000, *pud=0000000000000000
Internal error: Oops: 96000004 [#1] SMP
Modules linked in:
CPU: 33 PID: 1619 Comm: perf Not tainted 4.7.1+ #16
Hardware name: Huawei Taishan 2280 /CH05TEVBA, BIOS 1.10 11/24/2016
task: ffff8017cb0c8400 ti: ffff8017cb154000 task.ti: ffff8017cb154000
PC is at tmc_alloc_etf_buffer+0x60/0xd4
LR is at tmc_alloc_etf_buffer+0x44/0xd4
pc : [<ffff000008633df8>] lr : [<ffff000008633ddc>] pstate: 60000145
sp : ffff8017cb157b40
x29: ffff8017cb157b40 x28: 0000000000000000
...skip...
7a60: ffff000008c64dc8 0000000000000006 0000000000000253 ffffffffffffffff
7a80: 0000000000000000 0000000000000000 ffff0000080872cc 0000000000000001
[<ffff000008633df8>] tmc_alloc_etf_buffer+0x60/0xd4
[<ffff000008632b9c>] etm_setup_aux+0x1dc/0x1e8
[<ffff00000816eed4>] rb_alloc_aux+0x2b0/0x338
[<ffff00000816a5e4>] perf_mmap+0x414/0x568
[<ffff0000081ab694>] mmap_region+0x324/0x544
[<ffff0000081abbe8>] do_mmap+0x334/0x3e0
[<ffff000008191150>] vm_mmap_pgoff+0xa4/0xc8
[<ffff0000081a9a30>] SyS_mmap_pgoff+0xb0/0x22c
[<ffff0000080872e4>] sys_mmap+0x18/0x28
[<ffff0000080843f0>] el0_svc_naked+0x24/0x28
Code: 912040a5 d0001c00 f873d821 911c6000 (b8656822)
---[ end trace 98933da8f92b0c9a ]---
Signed-off-by: Wang Nan <wangnan0@huawei.com>
Cc: Xia Kaixu <xiakaixu@huawei.com>
Cc: Li Zefan <lizefan@huawei.com>
Cc: Mathieu Poirier <mathieu.poirier@linaro.org>
Cc: linux-arm-kernel@lists.infradead.org
Cc: linux-kernel@vger.kernel.org
Fixes: d52c9750f150 ("coresight: reset "enable_sink" flag when need be")
Signed-off-by: Mathieu Poirier <mathieu.poirier@linaro.org>
Cc: stable <stable@vger.kernel.org> # 4.10
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
|
Low
| 169,236
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
ContentSecurityPolicy* policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
if (IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
}
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Vulnerability Type: Bypass
CWE ID: CWE-732
Summary: Blink in Google Chrome prior to 61.0.3163.79 for Mac, Windows, and Linux, and 61.0.3163.81 for Android, failed to correctly propagate CSP restrictions to javascript scheme pages, which allowed a remote attacker to bypass content security policy via a crafted HTML page.
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#492333}
|
Medium
| 172,299
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
if (insn_bitness == 32) {
/* Relevant for 32-bit RSH: Information can propagate towards
* LSB, so it isn't sufficient to only truncate the output to
* 32 bits.
*/
coerce_reg_to_size(dst_reg, 4);
coerce_reg_to_size(&src_reg, 4);
}
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (!src_known &&
opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
__mark_reg_unknown(dst_reg);
return 0;
}
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift. If the value in dst_reg might
* be negative, then either:
* 1) src_reg might be zero, so the sign bit of the result is
* unknown, so we lose our signed bounds
* 2) it's known negative, thus the unsigned bounds capture the
* signed bounds
* 3) the signed bounds cross zero, so they tell us nothing
* about the result
* If the value in dst_reg is known nonnegative, then again the
* unsigned bounts capture the signed bounds.
* Thus, in all cases it suffices to blow away our signed bounds
* and rely on inferring new ones from the unsigned bounds and
* var_off of the result.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_ARSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* Upon reaching here, src_known is true and
* umax_val is equal to umin_val.
*/
dst_reg->smin_value >>= umin_val;
dst_reg->smax_value >>= umin_val;
dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
/* blow away the dst_reg umin_value/umax_value and rely on
* dst_reg var_off to refine the result.
*/
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->32 */
coerce_reg_to_size(dst_reg, 4);
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
Vulnerability Type:
CWE ID: CWE-189
Summary: kernel/bpf/verifier.c in the Linux kernel before 4.20.6 performs undesirable out-of-bounds speculation on pointer arithmetic in various cases, including cases of different branches with different state or limits to sanitize, leading to side-channel attacks.
Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths
While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer
arithmetic") took care of rejecting alu op on pointer when e.g. pointer
came from two different map values with different map properties such as
value size, Jann reported that a case was not covered yet when a given
alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from
different branches where we would incorrectly try to sanitize based
on the pointer's limit. Catch this corner case and reject the program
instead.
Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
|
Medium
| 169,730
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg,
bool_t *no_dispatch)
{
enum auth_stat retstat;
XDR xdrs;
SVCAUTH *auth;
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
struct rpc_gss_init_res gr;
int call_stat, offset;
OM_uint32 min_stat;
log_debug("in svcauth_gss()");
/* Initialize reply. */
rqst->rq_xprt->xp_verf = gssrpc__null_auth;
/* Allocate and set up server auth handle. */
if (rqst->rq_xprt->xp_auth == NULL ||
rqst->rq_xprt->xp_auth == &svc_auth_none) {
if ((auth = calloc(sizeof(*auth), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
if ((gd = calloc(sizeof(*gd), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
auth->svc_ah_ops = &svc_auth_gss_ops;
SVCAUTH_PRIVATE(auth) = gd;
rqst->rq_xprt->xp_auth = auth;
}
else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd);
/* Deserialize client credentials. */
if (rqst->rq_cred.oa_length <= 0)
return (AUTH_BADCRED);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gc, 0, sizeof(*gc));
log_debug("calling xdrmem_create()");
log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length);
xdrmem_create(&xdrs, rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length, XDR_DECODE);
log_debug("xdrmem_create() returned");
if (!xdr_rpc_gss_cred(&xdrs, gc)) {
log_debug("xdr_rpc_gss_cred() failed");
XDR_DESTROY(&xdrs);
return (AUTH_BADCRED);
}
XDR_DESTROY(&xdrs);
retstat = AUTH_FAILED;
#define ret_freegc(code) do { retstat = code; goto freegc; } while (0)
/* Check version. */
if (gc->gc_v != RPCSEC_GSS_VERSION)
ret_freegc (AUTH_BADCRED);
/* Check RPCSEC_GSS service. */
if (gc->gc_svc != RPCSEC_GSS_SVC_NONE &&
gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY &&
gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY)
ret_freegc (AUTH_BADCRED);
/* Check sequence number. */
if (gd->established) {
if (gc->gc_seq > MAXSEQ)
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
if ((offset = gd->seqlast - gc->gc_seq) < 0) {
gd->seqlast = gc->gc_seq;
offset = 0 - offset;
gd->seqmask <<= offset;
offset = 0;
} else if ((u_int)offset >= gd->win ||
(gd->seqmask & (1 << offset))) {
*no_dispatch = 1;
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
}
gd->seq = gc->gc_seq;
gd->seqmask |= (1 << offset);
}
if (gd->established) {
rqst->rq_clntname = (char *)gd->client_name;
rqst->rq_svccred = (char *)gd->ctx;
}
/* Handle RPCSEC_GSS control procedure. */
switch (gc->gc_proc) {
case RPCSEC_GSS_INIT:
case RPCSEC_GSS_CONTINUE_INIT:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_acquire_cred())
ret_freegc (AUTH_FAILED);
if (!svcauth_gss_accept_sec_context(rqst, &gr))
ret_freegc (AUTH_REJECTEDCRED);
if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) {
gss_release_buffer(&min_stat, &gr.gr_token);
mem_free(gr.gr_ctx.value,
sizeof(gss_union_ctx_id_desc));
ret_freegc (AUTH_FAILED);
}
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res,
(caddr_t)&gr);
gss_release_buffer(&min_stat, &gr.gr_token);
gss_release_buffer(&min_stat, &gd->checksum);
mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc));
if (!call_stat)
ret_freegc (AUTH_FAILED);
if (gr.gr_major == GSS_S_COMPLETE)
gd->established = TRUE;
break;
case RPCSEC_GSS_DATA:
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
break;
case RPCSEC_GSS_DESTROY:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt,
xdr_void, (caddr_t)NULL);
log_debug("sendreply in destroy: %d", call_stat);
if (!svcauth_gss_release_cred())
ret_freegc (AUTH_FAILED);
SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth);
rqst->rq_xprt->xp_auth = &svc_auth_none;
break;
default:
ret_freegc (AUTH_REJECTEDCRED);
break;
}
retstat = AUTH_OK;
freegc:
xdr_free(xdr_rpc_gss_cred, gc);
log_debug("returning %d from svcauth_gss()", retstat);
return (retstat);
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The svcauth_gss_accept_sec_context function in lib/rpc/svc_auth_gss.c in MIT Kerberos 5 (aka krb5) 1.11.x through 1.11.5, 1.12.x through 1.12.2, and 1.13.x before 1.13.1 transmits uninitialized interposer data to clients, which allows remote attackers to obtain sensitive information from process heap memory by sniffing the network for data in a handle field.
Commit Message: Fix gssrpc data leakage [CVE-2014-9423]
[MITKRB5-SA-2015-001] In svcauth_gss_accept_sec_context(), do not copy
bytes from the union context into the handle field we send to the
client. We do not use this handle field, so just supply a fixed
string of "xxxx".
In gss_union_ctx_id_struct, remove the unused "interposer" field which
was causing part of the union context to remain uninitialized.
ticket: 8058 (new)
target_version: 1.13.1
tags: pullup
|
Low
| 166,787
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The Array.prototype.concat implementation in builtins.cc in Google V8, as used in Google Chrome before 49.0.2623.108, does not properly consider element data types, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via crafted JavaScript code.
Commit Message: OomIntervention opt-out should work properly with 'show original'
OomIntervention should not be re-triggered on the same page if the user declines the intervention once.
This CL fixes the bug.
Bug: 889131, 887119
Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8
Reviewed-on: https://chromium-review.googlesource.com/1245019
Commit-Queue: Yuzu Saijo <yuzus@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#594574}
|
Medium
| 172,115
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
if (!start_page(f)) return FALSE;
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
c->lookup_values = lookup1_values(c->entries, c->dimensions);
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
for (j=2; j < g->values; ++j) {
int low,hi;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
int n_read = r->end - r->begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
Vulnerability Type: DoS Overflow Mem. Corr.
CWE ID: CWE-119
Summary: Sean Barrett stb_vorbis version 1.12 and earlier contains a Buffer Overflow vulnerability in All vorbis decoding paths. that can result in memory corruption, denial of service, comprised execution of host program. This attack appear to be exploitable via Victim must open a specially crafted Ogg Vorbis file. This vulnerability appears to have been fixed in 1.13.
Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
|
Medium
| 168,945
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: long Cluster::GetNext(
const BlockEntry* pCurr,
const BlockEntry*& pNext) const
{
assert(pCurr);
assert(m_entries);
assert(m_entries_count > 0);
size_t idx = pCurr->GetIndex();
assert(idx < size_t(m_entries_count));
assert(m_entries[idx] == pCurr);
++idx;
if (idx >= size_t(m_entries_count))
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pNext = NULL;
return status;
}
if (status > 0)
{
pNext = NULL;
return 0;
}
assert(m_entries);
assert(m_entries_count > 0);
assert(idx < size_t(m_entries_count));
}
pNext = m_entries[idx];
assert(pNext);
return 0;
}
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
|
Low
| 174,345
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
WebKitWebFrame *frame;
JSGlobalContextRef context;
JSObjectRef globalobject;
JSStringRef var_name;
JSStringRef js_script;
JSValueRef js_result;
JSStringRef js_result_string;
size_t js_result_size;
js_init();
frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view));
context = webkit_web_frame_get_global_context(frame);
globalobject = JSContextGetGlobalObject(context);
/* uzbl javascript namespace */
var_name = JSStringCreateWithUTF8CString("Uzbl");
JSObjectSetProperty(context, globalobject, var_name,
JSObjectMake(context, uzbl.js.classref, NULL),
kJSClassAttributeNone, NULL);
/* evaluate the script and get return value*/
js_script = JSStringCreateWithUTF8CString(script);
js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL);
if (js_result && !JSValueIsUndefined(context, js_result)) {
js_result_string = JSValueToStringCopy(context, js_result, NULL);
js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string);
if (js_result_size) {
char js_result_utf8[js_result_size];
JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size);
g_string_assign(result, js_result_utf8);
}
JSStringRelease(js_result_string);
}
/* cleanup */
JSObjectDeleteProperty(context, globalobject, var_name, NULL);
JSStringRelease(var_name);
JSStringRelease(js_script);
}
Vulnerability Type: Exec Code
CWE ID: CWE-264
Summary: The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
Commit Message: disable Uzbl javascript object because of security problem.
|
Low
| 165,523
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function)
{
if (!enabled()) {
NOTREACHED();
return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
}
v8::Local<v8::Value> argv[] = { function };
v8::Local<v8::Value> scopesValue;
if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue) || !scopesValue->IsArray())
return v8::MaybeLocal<v8::Value>();
v8::Local<v8::Array> scopes = scopesValue.As<v8::Array>();
v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate);
if (!markAsInternal(context, scopes, V8InternalValueType::kScopeList))
return v8::MaybeLocal<v8::Value>();
if (!markArrayEntriesAsInternal(context, scopes, V8InternalValueType::kScope))
return v8::MaybeLocal<v8::Value>();
if (!scopes->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false))
return v8::Undefined(m_isolate);
return scopes;
}
Vulnerability Type: XSS
CWE ID: CWE-79
Summary: Cross-site scripting (XSS) vulnerability in WebKit/Source/platform/v8_inspector/V8Debugger.cpp in Blink, as used in Google Chrome before 53.0.2785.89 on Windows and OS X and before 53.0.2785.92 on Linux, allows remote attackers to inject arbitrary web script or HTML into the Developer Tools (aka DevTools) subsystem via a crafted web site, aka *Universal XSS (UXSS).*
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
|
Medium
| 172,066
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int x25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name;
size_t copied;
int qbit, header_len;
struct sk_buff *skb;
unsigned char *asmptr;
int rc = -ENOTCONN;
lock_sock(sk);
if (x25->neighbour == NULL)
goto out;
header_len = x25->neighbour->extended ?
X25_EXT_MIN_LEN : X25_STD_MIN_LEN;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if (flags & MSG_OOB) {
rc = -EINVAL;
if (sock_flag(sk, SOCK_URGINLINE) ||
!skb_peek(&x25->interrupt_in_queue))
goto out;
skb = skb_dequeue(&x25->interrupt_in_queue);
if (!pskb_may_pull(skb, X25_STD_MIN_LEN))
goto out_free_dgram;
skb_pull(skb, X25_STD_MIN_LEN);
/*
* No Q bit information on Interrupt data.
*/
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = 0x00;
}
msg->msg_flags |= MSG_OOB;
} else {
/* Now we can treat all alike */
release_sock(sk);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
lock_sock(sk);
if (!skb)
goto out;
if (!pskb_may_pull(skb, header_len))
goto out_free_dgram;
qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT;
skb_pull(skb, header_len);
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
/* Currently, each datagram always contains a complete record */
msg->msg_flags |= MSG_EOR;
rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (rc)
goto out_free_dgram;
if (sx25) {
sx25->sx25_family = AF_X25;
sx25->sx25_addr = x25->dest_addr;
}
msg->msg_namelen = sizeof(struct sockaddr_x25);
x25_check_rbuf(sk);
rc = copied;
out_free_dgram:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
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 <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Low
| 166,524
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
Vulnerability Type: DoS
CWE ID: CWE-17
Summary: The ASN1_TYPE_cmp function in crypto/asn1/a_type.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not properly perform boolean-type comparisons, which allows remote attackers to cause a denial of service (invalid read operation and application crash) via a crafted X.509 certificate to an endpoint that uses the certificate-verification feature.
Commit Message:
|
Low
| 164,811
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
int bit_depth, unsigned int npalette, int interlace_type,
png_uint_32 w, png_uint_32 h, int do_interlace)
{
pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
if (npalette > 0)
{
pos = safecat(buffer, bufsize, pos, "[");
pos = safecatn(buffer, bufsize, pos, npalette);
pos = safecat(buffer, bufsize, pos, "]");
}
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, bit_depth);
pos = safecat(buffer, bufsize, pos, " bit");
if (interlace_type != PNG_INTERLACE_NONE)
{
pos = safecat(buffer, bufsize, pos, " interlaced");
if (do_interlace)
pos = safecat(buffer, bufsize, pos, "(pngvalid)");
else
pos = safecat(buffer, bufsize, pos, "(libpng)");
}
if (w > 0 || h > 0)
{
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, w);
pos = safecat(buffer, bufsize, pos, "x");
pos = safecatn(buffer, bufsize, pos, h);
}
return pos;
}
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)
|
Low
| 173,700
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int get_bitmap_file(struct mddev *mddev, void __user * arg)
{
mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
char *ptr;
int err;
file = kmalloc(sizeof(*file), GFP_NOIO);
if (!file)
return -ENOMEM;
err = 0;
spin_lock(&mddev->lock);
/* bitmap disabled, zero the first byte and copy out */
if (!mddev->bitmap_info.file)
file->pathname[0] = '\0';
else if ((ptr = file_path(mddev->bitmap_info.file,
file->pathname, sizeof(file->pathname))),
IS_ERR(ptr))
err = PTR_ERR(ptr);
else
memmove(file->pathname, ptr,
sizeof(file->pathname)-(ptr-file->pathname));
spin_unlock(&mddev->lock);
if (err == 0 &&
copy_to_user(arg, file, sizeof(*file)))
err = -EFAULT;
kfree(file);
return err;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The get_bitmap_file function in drivers/md/md.c in the Linux kernel before 4.1.6 does not initialize a certain bitmap data structure, which allows local users to obtain sensitive information from kernel memory via a GET_BITMAP_FILE ioctl call.
Commit Message: md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr>
Signed-off-by: NeilBrown <neilb@suse.com>
|
Low
| 166,595
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int newque(struct ipc_namespace *ns, struct ipc_params *params)
{
struct msg_queue *msq;
int id, retval;
key_t key = params->key;
int msgflg = params->flg;
msq = ipc_rcu_alloc(sizeof(*msq));
if (!msq)
return -ENOMEM;
msq->q_perm.mode = msgflg & S_IRWXUGO;
msq->q_perm.key = key;
msq->q_perm.security = NULL;
retval = security_msg_queue_alloc(msq);
if (retval) {
ipc_rcu_putref(msq, ipc_rcu_free);
return retval;
}
/* ipc_addid() locks msq upon success. */
id = ipc_addid(&msg_ids(ns), &msq->q_perm, ns->msg_ctlmni);
if (id < 0) {
ipc_rcu_putref(msq, msg_rcu_free);
return id;
}
msq->q_stime = msq->q_rtime = 0;
msq->q_ctime = get_seconds();
msq->q_cbytes = msq->q_qnum = 0;
msq->q_qbytes = ns->msg_ctlmnb;
msq->q_lspid = msq->q_lrpid = 0;
INIT_LIST_HEAD(&msq->q_messages);
INIT_LIST_HEAD(&msq->q_receivers);
INIT_LIST_HEAD(&msq->q_senders);
ipc_unlock_object(&msq->q_perm);
rcu_read_unlock();
return msq->q_perm.id;
}
Vulnerability Type: +Priv
CWE ID: CWE-362
Summary: Race condition in the IPC object implementation in the Linux kernel through 4.2.3 allows local users to gain privileges by triggering an ipc_addid call that leads to uid and gid comparisons against uninitialized data, related to msg.c, shm.c, and util.c.
Commit Message: Initialize msg/shm IPC objects before doing ipc_addid()
As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before
having initialized the IPC object state. Yes, we initialize the IPC
object in a locked state, but with all the lockless RCU lookup work,
that IPC object lock no longer means that the state cannot be seen.
We already did this for the IPC semaphore code (see commit e8577d1f0329:
"ipc/sem.c: fully initialize sem_array before making it visible") but we
clearly forgot about msg and shm.
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Cc: Manfred Spraul <manfred@colorfullife.com>
Cc: Davidlohr Bueso <dbueso@suse.de>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
|
Medium
| 166,578
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int do_ip_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct inet_sock *inet = inet_sk(sk);
int val;
int len;
if (level != SOL_IP)
return -EOPNOTSUPP;
if (ip_mroute_opt(optname))
return ip_mroute_getsockopt(sk, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
unsigned char optbuf[sizeof(struct ip_options)+40];
struct ip_options * opt = (struct ip_options *)optbuf;
opt->optlen = 0;
if (inet->opt)
memcpy(optbuf, inet->opt,
sizeof(struct ip_options)+
inet->opt->optlen);
release_sock(sk);
if (opt->optlen == 0)
return put_user(0, optlen);
ip_options_undo(opt);
len = min_t(unsigned int, len, opt->optlen);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, opt->__data, len))
return -EFAULT;
return 0;
}
case IP_PKTINFO:
val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0;
break;
case IP_RECVTTL:
val = (inet->cmsg_flags & IP_CMSG_TTL) != 0;
break;
case IP_RECVTOS:
val = (inet->cmsg_flags & IP_CMSG_TOS) != 0;
break;
case IP_RECVOPTS:
val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0;
break;
case IP_RETOPTS:
val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0;
break;
case IP_PASSSEC:
val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0;
break;
case IP_RECVORIGDSTADDR:
val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0;
break;
case IP_TOS:
val = inet->tos;
break;
case IP_TTL:
val = (inet->uc_ttl == -1 ?
sysctl_ip_default_ttl :
inet->uc_ttl);
break;
case IP_HDRINCL:
val = inet->hdrincl;
break;
case IP_NODEFRAG:
val = inet->nodefrag;
break;
case IP_MTU_DISCOVER:
val = inet->pmtudisc;
break;
case IP_MTU:
{
struct dst_entry *dst;
val = 0;
dst = sk_dst_get(sk);
if (dst) {
val = dst_mtu(dst);
dst_release(dst);
}
if (!val) {
release_sock(sk);
return -ENOTCONN;
}
break;
}
case IP_RECVERR:
val = inet->recverr;
break;
case IP_MULTICAST_TTL:
val = inet->mc_ttl;
break;
case IP_MULTICAST_LOOP:
val = inet->mc_loop;
break;
case IP_MULTICAST_IF:
{
struct in_addr addr;
len = min_t(unsigned int, len, sizeof(struct in_addr));
addr.s_addr = inet->mc_addr;
release_sock(sk);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &addr, len))
return -EFAULT;
return 0;
}
case IP_MSFILTER:
{
struct ip_msfilter msf;
int err;
if (len < IP_MSFILTER_SIZE(0)) {
release_sock(sk);
return -EINVAL;
}
if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) {
release_sock(sk);
return -EFAULT;
}
err = ip_mc_msfget(sk, &msf,
(struct ip_msfilter __user *)optval, optlen);
release_sock(sk);
return err;
}
case MCAST_MSFILTER:
{
struct group_filter gsf;
int err;
if (len < GROUP_FILTER_SIZE(0)) {
release_sock(sk);
return -EINVAL;
}
if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) {
release_sock(sk);
return -EFAULT;
}
err = ip_mc_gsfget(sk, &gsf,
(struct group_filter __user *)optval,
optlen);
release_sock(sk);
return err;
}
case IP_MULTICAST_ALL:
val = inet->mc_all;
break;
case IP_PKTOPTIONS:
{
struct msghdr msg;
release_sock(sk);
if (sk->sk_type != SOCK_STREAM)
return -ENOPROTOOPT;
msg.msg_control = optval;
msg.msg_controllen = len;
msg.msg_flags = 0;
if (inet->cmsg_flags & IP_CMSG_PKTINFO) {
struct in_pktinfo info;
info.ipi_addr.s_addr = inet->inet_rcv_saddr;
info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr;
info.ipi_ifindex = inet->mc_index;
put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info);
}
if (inet->cmsg_flags & IP_CMSG_TTL) {
int hlim = inet->mc_ttl;
put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim);
}
len -= msg.msg_controllen;
return put_user(len, optlen);
}
case IP_FREEBIND:
val = inet->freebind;
break;
case IP_TRANSPARENT:
val = inet->transparent;
break;
case IP_MINTTL:
val = inet->min_ttl;
break;
default:
release_sock(sk);
return -ENOPROTOOPT;
}
release_sock(sk);
if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) {
unsigned char ucval = (unsigned char)val;
len = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &ucval, 1))
return -EFAULT;
} else {
len = min_t(unsigned int, sizeof(int), len);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
}
return 0;
}
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 <eric.dumazet@gmail.com>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
High
| 165,566
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (ret || !write)
return ret;
if (sysctl_perf_cpu_time_max_percent == 100 ||
sysctl_perf_cpu_time_max_percent == 0) {
printk(KERN_WARNING
"perf: Dynamic interrupt throttling disabled, can hang your system!\n");
WRITE_ONCE(perf_sample_allowed_ns, 0);
} else {
update_perf_cpu_limits();
}
return 0;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: The perf_cpu_time_max_percent_handler function in kernel/events/core.c in the Linux kernel before 4.11 allows local users to cause a denial of service (integer overflow) or possibly have unspecified other impact via a large value, as demonstrated by an incorrect sample-rate calculation.
Commit Message: perf/core: Fix the perf_cpu_time_max_percent check
Use "proc_dointvec_minmax" instead of "proc_dointvec" to check the input
value from user-space.
If not, we can set a big value and some vars will overflow like
"sysctl_perf_event_sample_rate" which will cause a lot of unexpected
problems.
Signed-off-by: Tan Xiaojun <tanxiaojun@huawei.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Cc: <acme@kernel.org>
Cc: <alexander.shishkin@linux.intel.com>
Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com>
Cc: Arnaldo Carvalho de Melo <acme@redhat.com>
Cc: Jiri Olsa <jolsa@redhat.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Stephane Eranian <eranian@google.com>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Vince Weaver <vincent.weaver@maine.edu>
Link: http://lkml.kernel.org/r/1487829879-56237-1-git-send-email-tanxiaojun@huawei.com
Signed-off-by: Ingo Molnar <mingo@kernel.org>
|
Low
| 169,378
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
*buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
Vulnerability Type: DoS
CWE ID: CWE-125
Summary: libarchive version commit bf9aec176c6748f0ee7a678c5f9f9555b9a757c1 onwards (release v3.0.2 onwards) contains a CWE-125: Out-of-bounds Read vulnerability in 7zip decompression, archive_read_support_format_7zip.c, header_bytes() that can result in a crash (denial of service). This attack appears to be exploitable via the victim opening a specially crafted 7zip file.
Commit Message: 7zip: fix crash when parsing certain archives
Fuzzing with CRCs disabled revealed that a call to get_uncompressed_data()
would sometimes fail to return at least 'minimum' bytes. This can cause
the crc32() invocation in header_bytes to read off into invalid memory.
A specially crafted archive can use this to cause a crash.
An ASAN trace is below, but ASAN is not required - an uninstrumented
binary will also crash.
==7719==ERROR: AddressSanitizer: SEGV on unknown address 0x631000040000 (pc 0x7fbdb3b3ec1d bp 0x7ffe77a51310 sp 0x7ffe77a51150 T0)
==7719==The signal is caused by a READ memory access.
#0 0x7fbdb3b3ec1c in crc32_z (/lib/x86_64-linux-gnu/libz.so.1+0x2c1c)
#1 0x84f5eb in header_bytes (/tmp/libarchive/bsdtar+0x84f5eb)
#2 0x856156 in read_Header (/tmp/libarchive/bsdtar+0x856156)
#3 0x84e134 in slurp_central_directory (/tmp/libarchive/bsdtar+0x84e134)
#4 0x849690 in archive_read_format_7zip_read_header (/tmp/libarchive/bsdtar+0x849690)
#5 0x5713b7 in _archive_read_next_header2 (/tmp/libarchive/bsdtar+0x5713b7)
#6 0x570e63 in _archive_read_next_header (/tmp/libarchive/bsdtar+0x570e63)
#7 0x6f08bd in archive_read_next_header (/tmp/libarchive/bsdtar+0x6f08bd)
#8 0x52373f in read_archive (/tmp/libarchive/bsdtar+0x52373f)
#9 0x5257be in tar_mode_x (/tmp/libarchive/bsdtar+0x5257be)
#10 0x51daeb in main (/tmp/libarchive/bsdtar+0x51daeb)
#11 0x7fbdb27cab96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310
#12 0x41dd09 in _start (/tmp/libarchive/bsdtar+0x41dd09)
This was primarly done with afl and FairFuzz. Some early corpus entries
may have been generated by qsym.
|
Medium
| 169,484
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
Vulnerability Type: +Priv
CWE ID: CWE-285
Summary: The filesystem implementation in the Linux kernel through 4.8.2 preserves the setgid bit during a setxattr call, which allows local users to gain group privileges by leveraging the existence of a setgid program with restrictions on execute permissions.
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>
|
Low
| 166,978
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int command_read(struct pci_dev *dev, int offset, u16 *value, void *data)
{
int i;
int ret;
ret = xen_pcibk_read_config_word(dev, offset, value, data);
if (!pci_is_enabled(dev))
return ret;
for (i = 0; i < PCI_ROM_RESOURCE; i++) {
if (dev->resource[i].flags & IORESOURCE_IO)
*value |= PCI_COMMAND_IO;
if (dev->resource[i].flags & IORESOURCE_MEM)
*value |= PCI_COMMAND_MEMORY;
}
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: Xen 3.3.x through 4.5.x and the Linux kernel through 3.19.1 do not properly restrict access to PCI command registers, which might allow local guest OS users to cause a denial of service (non-maskable interrupt and host crash) by disabling the (1) memory or (2) I/O decoding for a PCI Express device and then accessing the device, which triggers an Unsupported Request (UR) response.
Commit Message: xen-pciback: limit guest control of command register
Otherwise the guest can abuse that control to cause e.g. PCIe
Unsupported Request responses by disabling memory and/or I/O decoding
and subsequently causing (CPU side) accesses to the respective address
ranges, which (depending on system configuration) may be fatal to the
host.
Note that to alter any of the bits collected together as
PCI_COMMAND_GUEST permissive mode is now required to be enabled
globally or on the specific device.
This is CVE-2015-2150 / XSA-120.
Signed-off-by: Jan Beulich <jbeulich@suse.com>
Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: David Vrabel <david.vrabel@citrix.com>
|
Low
| 166,682
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
_cleanup_close_ int fd;
int r;
assert(path);
if (parents)
mkdir_parents(path, 0755);
fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
if (fd < 0)
return -errno;
if (mode != MODE_INVALID) {
r = fchmod(fd, mode);
if (r < 0)
return -errno;
}
if (uid != UID_INVALID || gid != GID_INVALID) {
r = fchown(fd, uid, gid);
if (r < 0)
return -errno;
}
if (stamp != USEC_INFINITY) {
struct timespec ts[2];
timespec_store(&ts[0], stamp);
ts[1] = ts[0];
r = futimens(fd, ts);
} else
r = futimens(fd, NULL);
if (r < 0)
return -errno;
return 0;
}
Vulnerability Type:
CWE ID: CWE-264
Summary: A flaw in systemd v228 in /src/basic/fs-util.c caused world writable suid files to be created when using the systemd timers features, allowing local attackers to escalate their privileges to root. This is fixed in v229.
Commit Message: basic: fix touch() creating files with 07777 mode
mode_t is unsigned, so MODE_INVALID < 0 can never be true.
This fixes a possible DoS where any user could fill /run by writing to
a world-writable /run/systemd/show-status.
|
Low
| 168,517
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static void btu_exec_tap_fd_read(void *p_param) {
struct pollfd ufd;
int fd = (int)p_param;
if (fd == INVALID_FD || fd != btpan_cb.tap_fd)
return;
for (int i = 0; i < PAN_POOL_MAX && btif_is_enabled() && btpan_cb.flow; i++) {
BT_HDR *buffer = (BT_HDR *)GKI_getpoolbuf(PAN_POOL_ID);
if (!buffer) {
BTIF_TRACE_WARNING("%s unable to allocate buffer for packet.", __func__);
break;
}
buffer->offset = PAN_MINIMUM_OFFSET;
buffer->len = GKI_get_buf_size(buffer) - sizeof(BT_HDR) - buffer->offset;
UINT8 *packet = (UINT8 *)buffer + sizeof(BT_HDR) + buffer->offset;
if (!btpan_cb.congest_packet_size) {
ssize_t ret = read(fd, btpan_cb.congest_packet, sizeof(btpan_cb.congest_packet));
switch (ret) {
case -1:
BTIF_TRACE_ERROR("%s unable to read from driver: %s", __func__, strerror(errno));
GKI_freebuf(buffer);
btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
return;
case 0:
BTIF_TRACE_WARNING("%s end of file reached.", __func__);
GKI_freebuf(buffer);
btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
return;
default:
btpan_cb.congest_packet_size = ret;
break;
}
}
memcpy(packet, btpan_cb.congest_packet, MIN(btpan_cb.congest_packet_size, buffer->len));
buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len);
if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR *)packet)) {
tETH_HDR hdr;
memcpy(&hdr, packet, sizeof(tETH_HDR));
buffer->len -= sizeof(tETH_HDR);
buffer->offset += sizeof(tETH_HDR);
if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST)
btpan_cb.congest_packet_size = 0;
} else {
BTIF_TRACE_WARNING("%s dropping packet of length %d", __func__, buffer->len);
btpan_cb.congest_packet_size = 0;
GKI_freebuf(buffer);
}
ufd.fd = fd;
ufd.events = POLLIN;
ufd.revents = 0;
if (poll(&ufd, 1, 0) <= 0 || IS_EXCEPTION(ufd.revents))
break;
}
btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
}
Vulnerability Type: DoS
CWE ID: CWE-284
Summary: Bluetooth 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-08-01 allows attackers to cause a denial of service (loss of Bluetooth 911 functionality) via a crafted application that sends a signal to a Bluetooth process, aka internal bug 28885210.
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
|
Medium
| 173,447
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static char *decode_text_string(const char *str, size_t str_len)
{
int idx, is_hex, is_utf16be, ascii_idx;
char *ascii, hex_buf[5] = {0};
is_hex = is_utf16be = idx = ascii_idx = 0;
/* Regular encoding */
if (str[0] == '(')
{
ascii = malloc(strlen(str) + 1);
strncpy(ascii, str, strlen(str) + 1);
return ascii;
}
else if (str[0] == '<')
{
is_hex = 1;
++idx;
}
/* Text strings can be either PDFDocEncoding or UTF-16BE */
if (is_hex && (str_len > 5) &&
(str[idx] == 'F') && (str[idx+1] == 'E') &&
(str[idx+2] == 'F') && (str[idx+3] == 'F'))
{
is_utf16be = 1;
idx += 4;
}
else
return NULL;
/* Now decode as hex */
ascii = malloc(str_len);
for ( ; idx<str_len; ++idx)
{
hex_buf[0] = str[idx++];
hex_buf[1] = str[idx++];
hex_buf[2] = str[idx++];
hex_buf[3] = str[idx];
ascii[ascii_idx++] = strtol(hex_buf, NULL, 16);
}
return ascii;
}
Vulnerability Type:
CWE ID: CWE-787
Summary: An issue was discovered in PDFResurrect before 0.18. pdf_load_pages_kids in pdf.c doesn't validate a certain size value, which leads to a malloc failure and out-of-bounds write.
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
|
Medium
| 169,566
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void UpdateUI(const char* current_global_engine_id) {
DCHECK(current_global_engine_id);
const IBusEngineInfo* engine_info = NULL;
for (size_t i = 0; i < arraysize(kIBusEngines); ++i) {
if (kIBusEngines[i].name == std::string(current_global_engine_id)) {
engine_info = &kIBusEngines[i];
break;
}
}
if (!engine_info) {
LOG(ERROR) << current_global_engine_id
<< " is not found in the input method white-list.";
return;
}
InputMethodDescriptor current_input_method =
CreateInputMethodDescriptor(engine_info->name,
engine_info->longname,
engine_info->layout,
engine_info->language);
DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id
<< ", keyboard_layout:" << current_input_method.keyboard_layout;
current_input_method_changed_(language_library_, current_input_method);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Google Chrome before 13.0.782.107 does not properly handle nested functions in PDF documents, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted document.
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 170,552
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static void mark_screen_rdonly(struct mm_struct *mm)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
int i;
pgd = pgd_offset(mm, 0xA0000);
if (pgd_none_or_clear_bad(pgd))
goto out;
pud = pud_offset(pgd, 0xA0000);
if (pud_none_or_clear_bad(pud))
goto out;
pmd = pmd_offset(pud, 0xA0000);
split_huge_page_pmd(mm, pmd);
if (pmd_none_or_clear_bad(pmd))
goto out;
pte = pte_offset_map_lock(mm, pmd, 0xA0000, &ptl);
for (i = 0; i < 32; i++) {
if (pte_present(*pte))
set_pte(pte, pte_wrprotect(*pte));
pte++;
}
pte_unmap_unlock(pte, ptl);
out:
flush_tlb();
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: The Linux kernel before 3.3.1, when KVM is used, allows guest OS users to cause a denial of service (host OS crash) by leveraging administrative access to the guest OS, related to the pmd_none_or_clear_bad function and page faults for huge pages.
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[akpm@linux-foundation.org: checkpatch fixes]
Reported-by: Ulrich Obergfell <uobergfe@redhat.com>
Signed-off-by: Andrea Arcangeli <aarcange@redhat.com>
Acked-by: Johannes Weiner <hannes@cmpxchg.org>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Hugh Dickins <hughd@google.com>
Cc: Dave Jones <davej@redhat.com>
Acked-by: Larry Woodman <lwoodman@redhat.com>
Acked-by: Rik van Riel <riel@redhat.com>
Cc: Mark Salter <msalter@redhat.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
|
Medium
| 165,626
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int ECDSA_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int sig_len, EC_KEY *eckey)
{
ECDSA_SIG *s;
int ret=-1;
s = ECDSA_SIG_new();
if (s == NULL) return(ret);
if (d2i_ECDSA_SIG(&s, &sigbuf, sig_len) == NULL) goto err;
ret=ECDSA_do_verify(dgst, dgst_len, s, eckey);
err:
ECDSA_SIG_free(s);
return(ret);
}
Vulnerability Type:
CWE ID: CWE-310
Summary: OpenSSL before 0.9.8zd, 1.0.0 before 1.0.0p, and 1.0.1 before 1.0.1k does not enforce certain constraints on certificate data, which allows remote attackers to defeat a fingerprint-based certificate-blacklist protection mechanism by including crafted data within a certificate's unsigned portion, related to crypto/asn1/a_verify.c, crypto/dsa/dsa_asn1.c, crypto/ecdsa/ecs_vrf.c, and crypto/x509/x_all.c.
Commit Message: Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
CVE-2014-8275
Reviewed-by: Emilia Käsper <emilia@openssl.org>
|
Low
| 169,933
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
}
Vulnerability Type: Bypass
CWE ID: CWE-704
Summary: psi/zicc.c in Artifex Ghostscript before 9.26 allows remote attackers to bypass intended access restrictions because of a setcolorspace type confusion.
Commit Message:
|
Medium
| 164,635
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
{
char tmp[256];
struct dpc_ctx *ctx = c;
switch (rr) {
case RR_A:
if (len != 4) return -1;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
break;
case RR_AAAA:
if (len != 16) return -1;
ctx->addrs[ctx->cnt].family = AF_INET6;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
break;
case RR_CNAME:
if (__dn_expand(packet, (const unsigned char *)packet + 512,
data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
strcpy(ctx->canon, tmp);
break;
}
return 0;
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: musl libc before 1.1.17 has a buffer overflow via crafted DNS replies because dns_parse_callback in network/lookup_name.c does not restrict the number of addresses, and thus an attacker can provide an unexpected number by sending A records in a reply to an AAAA query.
Commit Message:
|
Low
| 164,652
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
}
Vulnerability Type:
CWE ID: CWE-787
Summary: A flaw was found in the Linux 4.x kernel's implementation of 32-bit syscall interface for bridging. This allowed a privileged user to arbitrarily write to a limited range of kernel memory.
Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <syzbot+845a53d13171abf8bf29@syzkaller.appspotmail.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
|
Low
| 169,358
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void HostPortAllocatorSession::OnSessionRequestDone(
UrlFetcher* url_fetcher,
const net::URLRequestStatus& status,
int response_code,
const std::string& response) {
url_fetchers_.erase(url_fetcher);
delete url_fetcher;
if (response_code != net::HTTP_OK) {
LOG(WARNING) << "Received error when allocating relay session: "
<< response_code;
TryCreateRelaySession();
return;
}
ReceiveSessionResponse(response);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in the PDF functionality in Google Chrome before 22.0.1229.79 allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted document.
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
|
Medium
| 170,810
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void FragmentPaintPropertyTreeBuilder::UpdateInnerBorderRadiusClip() {
DCHECK(properties_);
if (NeedsPaintPropertyUpdate()) {
if (NeedsInnerBorderRadiusClip(object_)) {
const LayoutBox& box = ToLayoutBox(object_);
ClipPaintPropertyNode::State state;
state.local_transform_space = context_.current.transform;
if (box.IsLayoutReplaced()) {
state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor(
LayoutRect(context_.current.paint_offset, box.Size()),
LayoutRectOutsets(-(box.PaddingTop() + box.BorderTop()),
-(box.PaddingRight() + box.BorderRight()),
-(box.PaddingBottom() + box.BorderBottom()),
-(box.PaddingLeft() + box.BorderLeft())));
} else {
state.clip_rect = box.StyleRef().GetRoundedInnerBorderFor(
LayoutRect(context_.current.paint_offset, box.Size()));
}
OnUpdateClip(properties_->UpdateInnerBorderRadiusClip(
context_.current.clip, std::move(state)));
} else {
OnClearClip(properties_->ClearInnerBorderRadiusClip());
}
}
if (auto* border_radius_clip = properties_->InnerBorderRadiusClip())
context_.current.clip = border_radius_clip;
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 47.0.2526.73 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <trchen@chromium.org>
> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org>
> Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#554653}
TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#563930}
|
Low
| 171,798
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static inline int check_sticky(struct inode *dir, struct inode *inode)
{
kuid_t fsuid = current_fsuid();
if (!(dir->i_mode & S_ISVTX))
return 0;
if (uid_eq(inode->i_uid, fsuid))
return 0;
if (uid_eq(dir->i_uid, fsuid))
return 0;
return !inode_capable(inode, CAP_FOWNER);
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The capabilities implementation in the Linux kernel before 3.14.8 does not properly consider that namespaces are inapplicable to inodes, which allows local users to bypass intended chmod restrictions by first creating a user namespace, as demonstrated by setting the setgid bit on a file with group ownership of root.
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <tytso@mit.edu>
Cc: Serge Hallyn <serge.hallyn@ubuntu.com>
Cc: "Eric W. Biederman" <ebiederm@xmission.com>
Cc: Dave Chinner <david@fromorbit.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
|
High
| 166,320
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int inode_change_ok(const struct inode *inode, struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
/*
* First check size constraints. These can't be overriden using
* ATTR_FORCE.
*/
if (ia_valid & ATTR_SIZE) {
int error = inode_newsize_ok(inode, attr->ia_size);
if (error)
return error;
}
/* If force is set do it anyway. */
if (ia_valid & ATTR_FORCE)
return 0;
/* Make sure a caller can chown. */
if ((ia_valid & ATTR_UID) &&
(!uid_eq(current_fsuid(), inode->i_uid) ||
!uid_eq(attr->ia_uid, inode->i_uid)) &&
!inode_capable(inode, CAP_CHOWN))
return -EPERM;
/* Make sure caller can chgrp. */
if ((ia_valid & ATTR_GID) &&
(!uid_eq(current_fsuid(), inode->i_uid) ||
(!in_group_p(attr->ia_gid) && !gid_eq(attr->ia_gid, inode->i_gid))) &&
!inode_capable(inode, CAP_CHOWN))
return -EPERM;
/* Make sure a caller can chmod. */
if (ia_valid & ATTR_MODE) {
if (!inode_owner_or_capable(inode))
return -EPERM;
/* Also check the setgid bit! */
if (!in_group_p((ia_valid & ATTR_GID) ? attr->ia_gid :
inode->i_gid) &&
!inode_capable(inode, CAP_FSETID))
attr->ia_mode &= ~S_ISGID;
}
/* Check for setting the inode time. */
if (ia_valid & (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET)) {
if (!inode_owner_or_capable(inode))
return -EPERM;
}
return 0;
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The capabilities implementation in the Linux kernel before 3.14.8 does not properly consider that namespaces are inapplicable to inodes, which allows local users to bypass intended chmod restrictions by first creating a user namespace, as demonstrated by setting the setgid bit on a file with group ownership of root.
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <tytso@mit.edu>
Cc: Serge Hallyn <serge.hallyn@ubuntu.com>
Cc: "Eric W. Biederman" <ebiederm@xmission.com>
Cc: Dave Chinner <david@fromorbit.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andy Lutomirski <luto@amacapital.net>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
|
High
| 166,317
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: WORD32 ih264d_process_intra_mb(dec_struct_t * ps_dec,
dec_mb_info_t * ps_cur_mb_info,
UWORD8 u1_mb_num)
{
UWORD8 u1_mb_type = ps_cur_mb_info->u1_mb_type;
UWORD8 uc_temp = ps_cur_mb_info->u1_mb_ngbr_availablity;
UWORD8 u1_top_available = BOOLEAN(uc_temp & TOP_MB_AVAILABLE_MASK);
UWORD8 u1_left_available = BOOLEAN(uc_temp & LEFT_MB_AVAILABLE_MASK);
UWORD8 u1_use_top_right_mb = BOOLEAN(uc_temp & TOP_RIGHT_MB_AVAILABLE_MASK);
UWORD8 u1_use_top_left_mb = BOOLEAN(uc_temp & TOP_LEFT_MB_AVAILABLE_MASK);
UWORD8 uc_useTopMB = u1_top_available;
UWORD16 u2_use_left_mb = u1_left_available;
UWORD16 u2_use_left_mb_pack;
UWORD8 *pu1_luma_pred_buffer;
/* CHANGED CODE */
UWORD8 *pu1_luma_rec_buffer;
UWORD8 *puc_top;
mb_neigbour_params_t *ps_left_mb;
mb_neigbour_params_t *ps_top_mb;
mb_neigbour_params_t *ps_top_right_mb;
mb_neigbour_params_t *ps_curmb;
UWORD16 u2_mbx = ps_cur_mb_info->u2_mbx;
UWORD32 ui_pred_width, ui_rec_width;
WORD16 *pi2_y_coeff;
UWORD8 u1_mbaff, u1_topmb, u1_mb_field_decoding_flag;
UWORD32 u4_num_pmbair;
UWORD16 ui2_luma_csbp = ps_cur_mb_info->u2_luma_csbp;
UWORD8 *pu1_yleft, *pu1_ytop_left;
/* Chroma variables*/
UWORD8 *pu1_top_u;
UWORD8 *pu1_uleft;
UWORD8 *pu1_u_top_left;
/* CHANGED CODE */
UWORD8 *pu1_mb_cb_rei1_buffer, *pu1_mb_cr_rei1_buffer;
UWORD32 u4_recwidth_cr;
/* CHANGED CODE */
tfr_ctxt_t *ps_frame_buf = ps_dec->ps_frame_buf_ip_recon;
UWORD32 u4_luma_dc_only_csbp = 0;
UWORD32 u4_luma_dc_only_cbp = 0;
UWORD8 *pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; //Pointer to keep track of intra4x4_pred_mode data in pv_proc_tu_coeff_data buffer
u1_mbaff = ps_dec->ps_cur_slice->u1_mbaff_frame_flag;
u1_topmb = ps_cur_mb_info->u1_topmb;
u4_num_pmbair = (u1_mb_num >> u1_mbaff);
/*--------------------------------------------------------------------*/
/* Find the current MB's mb params */
/*--------------------------------------------------------------------*/
u1_mb_field_decoding_flag = ps_cur_mb_info->u1_mb_field_decodingflag;
ps_curmb = ps_cur_mb_info->ps_curmb;
ps_top_mb = ps_cur_mb_info->ps_top_mb;
ps_left_mb = ps_cur_mb_info->ps_left_mb;
ps_top_right_mb = ps_cur_mb_info->ps_top_right_mb;
/*--------------------------------------------------------------------*/
/* Check whether neighbouring MB is Inter MB and */
/* constrained intra pred is 1. */
/*--------------------------------------------------------------------*/
u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb;
if(ps_dec->ps_cur_pps->u1_constrained_intra_pred_flag)
{
UWORD8 u1_left = (UWORD8)u2_use_left_mb;
uc_useTopMB = uc_useTopMB
&& ((ps_top_mb->u1_mb_type != P_MB)
&& (ps_top_mb->u1_mb_type != B_MB));
u2_use_left_mb = u2_use_left_mb
&& ((ps_left_mb->u1_mb_type != P_MB)
&& (ps_left_mb->u1_mb_type != B_MB));
u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb;
if(u1_mbaff)
{
if(u1_mb_field_decoding_flag ^ ps_left_mb->u1_mb_fld)
{
u1_left = u1_left
&& (((ps_left_mb + 1)->u1_mb_type != P_MB)
&& ((ps_left_mb + 1)->u1_mb_type
!= B_MB));
u2_use_left_mb = u2_use_left_mb && u1_left;
if(u1_mb_field_decoding_flag)
u2_use_left_mb_pack = (u1_left << 8)
+ (u2_use_left_mb_pack & 0xff);
else
u2_use_left_mb_pack = (u2_use_left_mb << 8)
+ (u2_use_left_mb);
}
}
u1_use_top_right_mb =
u1_use_top_right_mb
&& ((ps_top_right_mb->u1_mb_type != P_MB)
&& (ps_top_right_mb->u1_mb_type
!= B_MB));
u1_use_top_left_mb =
u1_use_top_left_mb
&& ((ps_cur_mb_info->u1_topleft_mbtype != P_MB)
&& (ps_cur_mb_info->u1_topleft_mbtype
!= B_MB));
}
/*********************Common pointer calculations *************************/
/* CHANGED CODE */
pu1_luma_pred_buffer = ps_dec->pu1_y;
pu1_luma_rec_buffer = ps_frame_buf->pu1_dest_y + (u4_num_pmbair << 4);
pu1_mb_cb_rei1_buffer = ps_frame_buf->pu1_dest_u
+ (u4_num_pmbair << 3) * YUV420SP_FACTOR;
pu1_mb_cr_rei1_buffer = ps_frame_buf->pu1_dest_v + (u4_num_pmbair << 3);
ui_pred_width = MB_SIZE;
ui_rec_width = ps_dec->u2_frm_wd_y << u1_mb_field_decoding_flag;
u4_recwidth_cr = ps_dec->u2_frm_wd_uv << u1_mb_field_decoding_flag;
/************* Current and top luma pointer *****************/
if(u1_mbaff)
{
if(u1_topmb == 0)
{
pu1_luma_rec_buffer += (
u1_mb_field_decoding_flag ?
(ui_rec_width >> 1) :
(ui_rec_width << 4));
pu1_mb_cb_rei1_buffer += (
u1_mb_field_decoding_flag ?
(u4_recwidth_cr >> 1) :
(u4_recwidth_cr << 3));
pu1_mb_cr_rei1_buffer += (
u1_mb_field_decoding_flag ?
(u4_recwidth_cr >> 1) :
(u4_recwidth_cr << 3));
}
}
/* CHANGED CODE */
if(ps_dec->u4_use_intrapred_line_copy == 1)
{
puc_top = ps_dec->pu1_prev_y_intra_pred_line + (ps_cur_mb_info->u2_mbx << 4);
pu1_top_u = ps_dec->pu1_prev_u_intra_pred_line
+ (ps_cur_mb_info->u2_mbx << 3) * YUV420SP_FACTOR;
}
else
{
puc_top = pu1_luma_rec_buffer - ui_rec_width;
pu1_top_u = pu1_mb_cb_rei1_buffer - u4_recwidth_cr;
}
/* CHANGED CODE */
/************* Left pointer *****************/
pu1_yleft = pu1_luma_rec_buffer - 1;
pu1_uleft = pu1_mb_cb_rei1_buffer - 1 * YUV420SP_FACTOR;
/**************Top Left pointer calculation**********/
pu1_ytop_left = puc_top - 1;
pu1_u_top_left = pu1_top_u - 1 * YUV420SP_FACTOR;
/* CHANGED CODE */
PROFILE_DISABLE_INTRA_PRED()
{
pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data;
if(u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 0)
{
ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 32);
}
else if (u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 1)
{
ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 8);
}
}
if(!ps_cur_mb_info->u1_tran_form8x8)
{
u4_luma_dc_only_csbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec,
ps_cur_mb_info,
1);
}
else
{
if(!ps_dec->ps_cur_pps->u1_entropy_coding_mode)
{
u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec,
ps_cur_mb_info,
1);
}
else
{
u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff8x8_mb(ps_dec,
ps_cur_mb_info);
}
}
pi2_y_coeff = ps_dec->pi2_coeff_data;
if(u1_mb_type != I_4x4_MB)
{
UWORD8 u1_intrapred_mode = MB_TYPE_TO_INTRA_16x16_MODE(u1_mb_type);
/*--------------------------------------------------------------------*/
/* 16x16 IntraPrediction */
/*--------------------------------------------------------------------*/
{
UWORD8 u1_packed_modes = (u1_top_available << 1)
+ u1_left_available;
UWORD8 u1_err_code =
(u1_intrapred_mode & 1) ?
u1_intrapred_mode :
(u1_intrapred_mode ^ 2);
if((u1_err_code & u1_packed_modes) ^ u1_err_code)
{
u1_intrapred_mode = 0;
ps_dec->i4_error_code = ERROR_INTRAPRED;
}
}
{
UWORD8 au1_ngbr_pels[33];
/* Get neighbour pixels */
/* left pels */
if(u2_use_left_mb)
{
WORD32 i;
for(i = 0; i < 16; i++)
au1_ngbr_pels[16 - 1 - i] = pu1_yleft[i * ui_rec_width];
}
else
{
memset(au1_ngbr_pels, 0, 16);
}
/* top left pels */
au1_ngbr_pels[16] = *pu1_ytop_left;
/* top pels */
if(uc_useTopMB)
{
memcpy(au1_ngbr_pels + 16 + 1, puc_top, 16);
}
else
{
memset(au1_ngbr_pels + 16 + 1, 0, 16);
}
PROFILE_DISABLE_INTRA_PRED()
ps_dec->apf_intra_pred_luma_16x16[u1_intrapred_mode](
au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width,
((uc_useTopMB << 2) | u2_use_left_mb));
}
{
UWORD32 i;
WORD16 ai2_tmp[16];
for(i = 0; i < 16; i++)
{
WORD16 *pi2_level = pi2_y_coeff + (i << 4);
UWORD8 *pu1_pred_sblk = pu1_luma_rec_buffer
+ ((i & 0x3) * BLK_SIZE)
+ (i >> 2) * (ui_rec_width << 2);
PROFILE_DISABLE_IQ_IT_RECON()
{
if(CHECKBIT(ps_cur_mb_info->u2_luma_csbp, i))
{
ps_dec->pf_iquant_itrans_recon_luma_4x4(
pi2_level,
pu1_pred_sblk,
pu1_pred_sblk,
ui_rec_width,
ui_rec_width,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0],
ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1,
pi2_level);
}
else if((CHECKBIT(u4_luma_dc_only_csbp, i)) && pi2_level[0] != 0)
{
ps_dec->pf_iquant_itrans_recon_luma_4x4_dc(
pi2_level,
pu1_pred_sblk,
pu1_pred_sblk,
ui_rec_width,
ui_rec_width,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0],
ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1,
pi2_level);
}
}
}
}
}
else if(!ps_cur_mb_info->u1_tran_form8x8)
{
UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB;
UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num;
WORD8 i1_top_pred_mode;
WORD8 i1_left_pred_mode;
UWORD8 *pu1_top, *pu1_left, *pu1_top_left, *pu1_top_right;
WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode;
UWORD16 ui2_left_pred_buf_width = 0xffff;
WORD8 i1_intra_pred;
UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data;
UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 16;
WORD16 *pi2_y_coeff1;
UWORD8 u1_cur_sub_block;
UWORD16 ui2_top_rt_mask;
/*--------------------------------------------------------------------*/
/* 4x4 IntraPrediction */
/*--------------------------------------------------------------------*/
/* Calculation of Top Right subblock mask */
/* */
/* (a) Set it to default mask */
/* [It has 0 for sublocks which will never have top-right sub block] */
/* */
/* (b) If top MB is not available */
/* Clear the bits of the first row sub blocks */
/* */
/* (c) Set/Clear bit for top-right sublock of MB */
/* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */
/*--------------------------------------------------------------------*/
pu1_top = puc_top;
ui2_top_rt_mask = (u1_use_top_right_mb << 3) | (0x5750);
if(uc_useTopMB)
ui2_top_rt_mask |= 0x7;
/*Top Related initialisations*/
pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes;
pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes;
/*--------------------------------------
if(u1_mbaff)
{
pi1_cur_pred_mode += (u2_mbx << 2);
pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset;
pi1_cur_pred_mode += (u1_topmb) ? 0: 4;
}*/
if(u1_top_available)
{
if(ps_top_mb->u1_mb_type == I_4x4_MB)
*(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode;
else
*(WORD32*)pi1_cur_pred_mode =
(uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID;
}
else
*(WORD32*)pi1_cur_pred_mode = NOT_VALID;
/* CHANGED CODE */
/* CHANGED CODE */
/*Left Related initialisations*/
pi1_left_pred_mode = ps_dec->pi1_left_pred_mode;
if(!u1_mbaff)
{
if(u1_left_available)
{
if(ps_left_mb->u1_mb_type != I_4x4_MB)
*(WORD32*)pi1_left_pred_mode =
(u2_use_left_mb_pack) ?
DC_DC_DC_DC :
NOT_VALID;
}
else
{
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
}
}
else
{
UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag;
UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld;
if(u1_curMbfld ^ u1_leftMbfld)
{
if(u1_topmb
| ((u1_topmb == 0)
&& ((ps_curmb - 1)->u1_mb_type
!= I_4x4_MB)))
{
if(u1_left_available)
{
if(ps_left_mb->u1_mb_type != I_4x4_MB)
{
if(CHECKBIT(u2_use_left_mb_pack,0) == 0)
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
else
*(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC;
}
}
else
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
if(u1_curMbfld)
{
if(u1_left_available)
{
if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB)
{
if(u2_use_left_mb_pack >> 8)
*(WORD32*)(pi1_left_pred_mode + 4) =
DC_DC_DC_DC;
else
*(WORD32*)(pi1_left_pred_mode + 4) =
NOT_VALID;
}
}
else
*(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID;
pi1_left_pred_mode[1] = pi1_left_pred_mode[2];
pi1_left_pred_mode[2] = pi1_left_pred_mode[4];
pi1_left_pred_mode[3] = pi1_left_pred_mode[6];
*(WORD32*)(pi1_left_pred_mode + 4) =
*(WORD32*)pi1_left_pred_mode;
}
else
{
pi1_left_pred_mode[7] = pi1_left_pred_mode[3];
pi1_left_pred_mode[6] = pi1_left_pred_mode[3];
pi1_left_pred_mode[5] = pi1_left_pred_mode[2];
pi1_left_pred_mode[4] = pi1_left_pred_mode[2];
pi1_left_pred_mode[3] = pi1_left_pred_mode[1];
pi1_left_pred_mode[2] = pi1_left_pred_mode[1];
pi1_left_pred_mode[1] = pi1_left_pred_mode[0];
}
}
pi1_left_pred_mode += (u1_topmb) ? 0 : 4;
}
else
{
pi1_left_pred_mode += (u1_topmb) ? 0 : 4;
if(u1_left_available)
{
if(ps_left_mb->u1_mb_type != I_4x4_MB)
*(WORD32*)pi1_left_pred_mode =
(u2_use_left_mb_pack) ?
DC_DC_DC_DC :
NOT_VALID;
}
else
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
}
}
/* One time pointer initialisations*/
pi2_y_coeff1 = pi2_y_coeff;
pu1_top_left = pu1_ytop_left;
/* Scan the sub-blocks in Raster Scan Order */
for(u1_sub_mb_num = 0; u1_sub_mb_num < 16; u1_sub_mb_num++)
{
UWORD8 au1_ngbr_pels[13];
u1_sub_blk_x = u1_sub_mb_num & 0x3;
u1_sub_blk_y = u1_sub_mb_num >> 2;
i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x];
i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y];
u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num));
/*********** left subblock availability**********/
if(u1_sub_blk_x)
u1_is_left_sub_block = 1;
else
u1_is_left_sub_block =
(u1_sub_blk_y < 2) ?
(CHECKBIT(u2_use_left_mb_pack,
0)) :
(u2_use_left_mb_pack >> 8);
/* CHANGED CODE */
if(u1_sub_blk_y)
u1_is_top_sub_block = 1;
/* CHANGED CODE */
/***************** Top *********************/
if(ps_dec->u4_use_intrapred_line_copy == 1)
{
if(u1_sub_blk_y)
pu1_top = pu1_luma_rec_buffer - ui_rec_width;
else
pu1_top = puc_top + (u1_sub_blk_x << 2);
}
else
{
pu1_top = pu1_luma_rec_buffer - ui_rec_width;
}
/***************** Top Right *********************/
pu1_top_right = pu1_top + 4;
/***************** Top Left *********************/
pu1_top_left = pu1_top - 1;
/***************** Left *********************/
pu1_left = pu1_luma_rec_buffer - 1;
/* CHANGED CODE */
/*---------------------------------------------------------------*/
/* Calculation of Intra prediction mode */
/*---------------------------------------------------------------*/
i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ?
DC : MIN(i1_left_pred_mode, i1_top_pred_mode);
{
UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1)
+ u1_is_left_sub_block;
UWORD8 *pu1_intra_err_codes =
(UWORD8 *)gau1_ih264d_intra_pred_err_code;
UWORD8 uc_b2b0 = ((u1_sub_mb_num & 4) >> 1) | (u1_sub_mb_num & 1);
UWORD8 uc_b3b1 = ((u1_sub_mb_num & 8) >> 2)
| ((u1_sub_mb_num & 2) >> 1);
u1_cur_sub_block = (uc_b3b1 << 2) + uc_b2b0;
PROFILE_DISABLE_INTRA_PRED()
if(!pu1_prev_intra4x4_pred_mode_flag[u1_cur_sub_block])
{
i1_intra_pred =
pu1_rem_intra4x4_pred_mode[u1_cur_sub_block]
+ (pu1_rem_intra4x4_pred_mode[u1_cur_sub_block]
>= i1_intra_pred);
}
{
UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred];
if((u1_err_code & u1_packed_modes) ^ u1_err_code)
{
i1_intra_pred = 0;
ps_dec->i4_error_code = ERROR_INTRAPRED;
}
}
}
{
/* Get neighbour pixels */
/* left pels */
if(u1_is_left_sub_block)
{
WORD32 i;
for(i = 0; i < 4; i++)
au1_ngbr_pels[4 - 1 - i] = pu1_left[i * ui_rec_width];
}
else
{
memset(au1_ngbr_pels, 0, 4);
}
/* top left pels */
au1_ngbr_pels[4] = *pu1_top_left;
/* top pels */
if(u1_is_top_sub_block)
{
memcpy(au1_ngbr_pels + 4 + 1, pu1_top, 4);
}
else
{
memset(au1_ngbr_pels + 4 + 1, 0, 4);
}
/* top right pels */
if(u1_use_top_right_mb)
{
memcpy(au1_ngbr_pels + 4 * 2 + 1, pu1_top_right, 4);
}
else if(u1_is_top_sub_block)
{
memset(au1_ngbr_pels + 4 * 2 + 1, au1_ngbr_pels[4 * 2], 4);
}
}
PROFILE_DISABLE_INTRA_PRED()
ps_dec->apf_intra_pred_luma_4x4[i1_intra_pred](
au1_ngbr_pels, pu1_luma_rec_buffer, 1,
ui_rec_width,
((u1_is_top_sub_block << 2) | u1_is_left_sub_block));
/* CHANGED CODE */
if(CHECKBIT(ui2_luma_csbp, u1_sub_mb_num))
{
WORD16 ai2_tmp[16];
PROFILE_DISABLE_IQ_IT_RECON()
{
if(CHECKBIT(u4_luma_dc_only_csbp, u1_sub_mb_num))
{
ps_dec->pf_iquant_itrans_recon_luma_4x4_dc(
pi2_y_coeff1,
pu1_luma_rec_buffer,
pu1_luma_rec_buffer,
ui_rec_width,
ui_rec_width,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0],
ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0,
NULL);
}
else
{
ps_dec->pf_iquant_itrans_recon_luma_4x4(
pi2_y_coeff1,
pu1_luma_rec_buffer,
pu1_luma_rec_buffer,
ui_rec_width,
ui_rec_width,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0],
ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0,
NULL);
}
}
}
/*---------------------------------------------------------------*/
/* Update sub block number */
/*---------------------------------------------------------------*/
pi2_y_coeff1 += 16;
pu1_luma_rec_buffer +=
(u1_sub_blk_x == 3) ? (ui_rec_width << 2) - 12 : 4;
pu1_luma_pred_buffer +=
(u1_sub_blk_x == 3) ? (ui_pred_width << 2) - 12 : 4;
/* CHANGED CODE */
pi1_cur_pred_mode[u1_sub_blk_x] = i1_intra_pred;
pi1_left_pred_mode[u1_sub_blk_y] = i1_intra_pred;
}
}
else if((u1_mb_type == I_4x4_MB) && (ps_cur_mb_info->u1_tran_form8x8 == 1))
{
UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB;
UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num;
WORD8 i1_top_pred_mode;
WORD8 i1_left_pred_mode;
UWORD8 *pu1_top, *pu1_left, *pu1_top_left;
WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode;
UWORD16 ui2_left_pred_buf_width = 0xffff;
WORD8 i1_intra_pred;
UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data;
UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 4;
WORD16 *pi2_y_coeff1;
UWORD16 ui2_top_rt_mask;
UWORD32 u4_4x4_left_offset = 0;
/*--------------------------------------------------------------------*/
/* 8x8 IntraPrediction */
/*--------------------------------------------------------------------*/
/* Calculation of Top Right subblock mask */
/* */
/* (a) Set it to default mask */
/* [It has 0 for sublocks which will never have top-right sub block] */
/* */
/* (b) If top MB is not available */
/* Clear the bits of the first row sub blocks */
/* */
/* (c) Set/Clear bit for top-right sublock of MB */
/* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */
/* */
/* ui2_top_rt_mask: marks availibility of top right(neighbour) */
/* in the 8x8 Block ordering */
/* */
/* tr0 tr1 */
/* 0 1 tr3 */
/* 2 3 */
/* */
/* Top rights for 0 is in top MB */
/* top right of 1 will be in top right MB */
/* top right of 3 in right MB and hence not available */
/* This corresponds to ui2_top_rt_mask having default value 0x4 */
/*--------------------------------------------------------------------*/
ui2_top_rt_mask = (u1_use_top_right_mb << 1) | (0x4);
if(uc_useTopMB)
{
ui2_top_rt_mask |= 0x1;
}
/* Top Related initialisations */
pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes;
pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes;
/*
if(u1_mbaff)
{
pi1_cur_pred_mode += (u2_mbx << 2);
pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset;
pi1_cur_pred_mode += (u1_topmb) ? 0: 4;
}
*/
if(u1_top_available)
{
if(ps_top_mb->u1_mb_type == I_4x4_MB)
{
*(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode;
}
else
{
*(WORD32*)pi1_cur_pred_mode =
(uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID;
}
}
else
{
*(WORD32*)pi1_cur_pred_mode = NOT_VALID;
}
pu1_top = puc_top - 8;
/*Left Related initialisations*/
pi1_left_pred_mode = ps_dec->pi1_left_pred_mode;
if(!u1_mbaff)
{
if(u1_left_available)
{
if(ps_left_mb->u1_mb_type != I_4x4_MB)
{
*(WORD32*)pi1_left_pred_mode =
(u2_use_left_mb_pack) ?
DC_DC_DC_DC :
NOT_VALID;
}
}
else
{
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
}
}
else
{
UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag;
UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld;
if((!u1_curMbfld) && (u1_leftMbfld))
{
u4_4x4_left_offset = 1;
}
if(u1_curMbfld ^ u1_leftMbfld)
{
if(u1_topmb
| ((u1_topmb == 0)
&& ((ps_curmb - 1)->u1_mb_type
!= I_4x4_MB)))
{
if(u1_left_available)
{
if(ps_left_mb->u1_mb_type != I_4x4_MB)
{
if(CHECKBIT(u2_use_left_mb_pack,0) == 0)
{
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
}
else
{
*(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC;
}
}
}
else
{
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
}
if(u1_curMbfld)
{
if(u1_left_available)
{
if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB)
{
if(u2_use_left_mb_pack >> 8)
{
*(WORD32*)(pi1_left_pred_mode + 4) =
DC_DC_DC_DC;
}
else
{
*(WORD32*)(pi1_left_pred_mode + 4) =
NOT_VALID;
}
}
}
else
{
*(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID;
}
pi1_left_pred_mode[1] = pi1_left_pred_mode[2];
pi1_left_pred_mode[2] = pi1_left_pred_mode[4];
pi1_left_pred_mode[3] = pi1_left_pred_mode[6];
*(WORD32*)(pi1_left_pred_mode + 4) =
*(WORD32*)pi1_left_pred_mode;
}
else
{
pi1_left_pred_mode[7] = pi1_left_pred_mode[3];
pi1_left_pred_mode[6] = pi1_left_pred_mode[3];
pi1_left_pred_mode[5] = pi1_left_pred_mode[2];
pi1_left_pred_mode[4] = pi1_left_pred_mode[2];
pi1_left_pred_mode[3] = pi1_left_pred_mode[1];
pi1_left_pred_mode[2] = pi1_left_pred_mode[1];
pi1_left_pred_mode[1] = pi1_left_pred_mode[0];
}
}
pi1_left_pred_mode += (u1_topmb) ? 0 : 4;
}
else
{
pi1_left_pred_mode += (u1_topmb) ? 0 : 4;
if(u1_left_available)
{
if(ps_left_mb->u1_mb_type != I_4x4_MB)
{
*(WORD32*)pi1_left_pred_mode =
(u2_use_left_mb_pack) ?
DC_DC_DC_DC :
NOT_VALID;
}
}
else
{
*(WORD32*)pi1_left_pred_mode = NOT_VALID;
}
}
}
/* One time pointer initialisations*/
pi2_y_coeff1 = pi2_y_coeff;
if(u1_use_top_left_mb)
{
pu1_top_left = pu1_ytop_left;
}
else
{
pu1_top_left = NULL;
}
/* Scan the sub-blocks in Raster Scan Order */
for(u1_sub_mb_num = 0; u1_sub_mb_num < 4; u1_sub_mb_num++)
{
u1_sub_blk_x = (u1_sub_mb_num & 0x1);
u1_sub_blk_y = (u1_sub_mb_num >> 1);
i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x << 1];
i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y << 1];
if(2 == u1_sub_mb_num)
{
i1_left_pred_mode = pi1_left_pred_mode[(u1_sub_blk_y << 1)
+ u4_4x4_left_offset];
}
u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num));
/*********** left subblock availability**********/
if(u1_sub_blk_x)
{
u1_is_left_sub_block = 1;
}
else
{
u1_is_left_sub_block =
(u1_sub_blk_y < 1) ?
(CHECKBIT(u2_use_left_mb_pack,
0)) :
(u2_use_left_mb_pack >> 8);
}
/***************** Top *********************/
if(u1_sub_blk_y)
{
u1_is_top_sub_block = 1;
pu1_top = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - ui_rec_width;
}
else
{
pu1_top += 8;
}
/***************** Left *********************/
if((u1_sub_blk_x) | (u4_num_pmbair != 0))
{
pu1_left = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - 1;
ui2_left_pred_buf_width = ui_rec_width;
}
else
{
pu1_left = pu1_yleft;
pu1_yleft += (ui_rec_width << 3);
ui2_left_pred_buf_width = ui_rec_width;
}
/***************** Top Left *********************/
if(u1_sub_mb_num)
{
pu1_top_left = (u1_sub_blk_x) ?
pu1_top - 1 : pu1_left - ui_rec_width;
if((u1_sub_blk_x && (!u1_is_top_sub_block))
|| ((!u1_sub_blk_x) && (!u1_is_left_sub_block)))
{
pu1_top_left = NULL;
}
}
/*---------------------------------------------------------------*/
/* Calculation of Intra prediction mode */
/*---------------------------------------------------------------*/
i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ?
DC : MIN(i1_left_pred_mode, i1_top_pred_mode);
{
UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1)
+ u1_is_left_sub_block;
UWORD8 *pu1_intra_err_codes =
(UWORD8 *)gau1_ih264d_intra_pred_err_code;
/********************************************************************/
/* Same intra4x4_pred_mode array is filled with intra4x4_pred_mode */
/* for a MB with 8x8 intrapredicition */
/********************************************************************/
PROFILE_DISABLE_INTRA_PRED()
if(!pu1_prev_intra4x4_pred_mode_flag[u1_sub_mb_num])
{
i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_sub_mb_num]
+ (pu1_rem_intra4x4_pred_mode[u1_sub_mb_num]
>= i1_intra_pred);
}
{
UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred];
if((u1_err_code & u1_packed_modes) ^ u1_err_code)
{
i1_intra_pred = 0;
ps_dec->i4_error_code = ERROR_INTRAPRED;
}
}
}
{
UWORD8 au1_ngbr_pels[25];
WORD32 ngbr_avail;
ngbr_avail = u1_is_left_sub_block << 0;
ngbr_avail |= u1_is_top_sub_block << 2;
if(pu1_top_left)
ngbr_avail |= 1 << 1;
ngbr_avail |= u1_use_top_right_mb << 3;
PROFILE_DISABLE_INTRA_PRED()
{
ps_dec->pf_intra_pred_ref_filtering(pu1_left, pu1_top_left,
pu1_top, au1_ngbr_pels,
ui2_left_pred_buf_width,
ngbr_avail);
ps_dec->apf_intra_pred_luma_8x8[i1_intra_pred](
au1_ngbr_pels, pu1_luma_rec_buffer, 1,
ui_rec_width,
((u1_is_top_sub_block << 2) | u1_is_left_sub_block));
}
}
/* Inverse Transform and Reconstruction */
if(CHECKBIT(ps_cur_mb_info->u1_cbp, u1_sub_mb_num))
{
WORD16 *pi2_scale_matrix_ptr;
WORD16 ai2_tmp[64];
pi2_scale_matrix_ptr =
ps_dec->s_high_profile.i2_scalinglist8x8[0];
PROFILE_DISABLE_IQ_IT_RECON()
{
if(CHECKBIT(u4_luma_dc_only_cbp, u1_sub_mb_num))
{
ps_dec->pf_iquant_itrans_recon_luma_8x8_dc(
pi2_y_coeff1,
pu1_luma_rec_buffer,
pu1_luma_rec_buffer,
ui_rec_width,
ui_rec_width,
gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6],
(UWORD16 *)pi2_scale_matrix_ptr,
ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0,
NULL);
}
else
{
ps_dec->pf_iquant_itrans_recon_luma_8x8(
pi2_y_coeff1,
pu1_luma_rec_buffer,
pu1_luma_rec_buffer,
ui_rec_width,
ui_rec_width,
gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6],
(UWORD16 *)pi2_scale_matrix_ptr,
ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0,
NULL);
}
}
}
/*---------------------------------------------------------------*/
/* Update sub block number */
/*---------------------------------------------------------------*/
pi2_y_coeff1 += 64;
pu1_luma_rec_buffer +=
(u1_sub_blk_x == 1) ?
(ui_rec_width << 3) - (8 * 1) : 8;
/*---------------------------------------------------------------*/
/* Pred mode filled in terms of 4x4 block so replicated in 2 */
/* locations. */
/*---------------------------------------------------------------*/
pi1_cur_pred_mode[u1_sub_blk_x << 1] = i1_intra_pred;
pi1_cur_pred_mode[(u1_sub_blk_x << 1) + 1] = i1_intra_pred;
pi1_left_pred_mode[u1_sub_blk_y << 1] = i1_intra_pred;
pi1_left_pred_mode[(u1_sub_blk_y << 1) + 1] = i1_intra_pred;
}
}
/* Decode Chroma Block */
ih264d_unpack_chroma_coeff4x4_mb(ps_dec,
ps_cur_mb_info);
/*--------------------------------------------------------------------*/
/* Chroma Blocks decoding */
/*--------------------------------------------------------------------*/
{
UWORD8 u1_intra_chrom_pred_mode;
UWORD8 u1_chroma_cbp = (UWORD8)(ps_cur_mb_info->u1_cbp >> 4);
/*--------------------------------------------------------------------*/
/* Perform Chroma intra prediction */
/*--------------------------------------------------------------------*/
u1_intra_chrom_pred_mode = CHROMA_TO_LUMA_INTRA_MODE(
ps_cur_mb_info->u1_chroma_pred_mode);
{
UWORD8 u1_packed_modes = (u1_top_available << 1)
+ u1_left_available;
UWORD8 u1_err_code =
(u1_intra_chrom_pred_mode & 1) ?
u1_intra_chrom_pred_mode :
(u1_intra_chrom_pred_mode ^ 2);
if((u1_err_code & u1_packed_modes) ^ u1_err_code)
{
u1_intra_chrom_pred_mode = 0;
ps_dec->i4_error_code = ERROR_INTRAPRED;
}
}
/* CHANGED CODE */
if(u1_chroma_cbp != CBPC_ALLZERO)
{
UWORD16 u2_chroma_csbp =
(u1_chroma_cbp == CBPC_ACZERO) ?
0 : ps_cur_mb_info->u2_chroma_csbp;
UWORD32 u4_scale_u;
UWORD32 u4_scale_v;
{
UWORD16 au2_ngbr_pels[33];
UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels;
UWORD16 *pu2_left_uv;
UWORD16 *pu2_topleft_uv;
WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff);
WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8;
pu2_left_uv = (UWORD16 *)pu1_uleft;
pu2_topleft_uv = (UWORD16 *)pu1_u_top_left;
/* Get neighbour pixels */
/* left pels */
if(u2_use_left_mb_pack)
{
WORD32 i;
if(use_left1)
{
for(i = 0; i < 4; i++)
au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i
* u4_recwidth_cr / YUV420SP_FACTOR];
}
else
{
memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16));
}
if(use_left2)
{
for(i = 4; i < 8; i++)
au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i
* u4_recwidth_cr / YUV420SP_FACTOR];
}
else
{
memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16));
}
}
else
{
memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16));
}
/* top left pels */
au2_ngbr_pels[8] = *pu2_topleft_uv;
/* top pels */
if(uc_useTopMB)
{
memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u,
8 * sizeof(UWORD16));
}
else
{
memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16));
}
PROFILE_DISABLE_INTRA_PRED()
ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode](
pu1_ngbr_pels,
pu1_mb_cb_rei1_buffer,
1,
u4_recwidth_cr,
((uc_useTopMB << 2) | (use_left2 << 4)
| use_left1));
}
u4_scale_u = ps_cur_mb_info->u1_qpc_div6;
u4_scale_v = ps_cur_mb_info->u1_qpcr_div6;
pi2_y_coeff = ps_dec->pi2_coeff_data;
{
UWORD32 i;
WORD16 ai2_tmp[16];
for(i = 0; i < 4; i++)
{
WORD16 *pi2_level = pi2_y_coeff + (i << 4);
UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer
+ ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR)
+ (i >> 1) * (u4_recwidth_cr << 2);
PROFILE_DISABLE_IQ_IT_RECON()
{
if(CHECKBIT(u2_chroma_csbp, i))
{
ps_dec->pf_iquant_itrans_recon_chroma_4x4(
pi2_level,
pu1_pred_sblk,
pu1_pred_sblk,
u4_recwidth_cr,
u4_recwidth_cr,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1],
u4_scale_u, ai2_tmp, pi2_level);
}
else if(pi2_level[0] != 0)
{
ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc(
pi2_level,
pu1_pred_sblk,
pu1_pred_sblk,
u4_recwidth_cr,
u4_recwidth_cr,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1],
u4_scale_u, ai2_tmp, pi2_level);
}
}
}
}
pi2_y_coeff += MB_CHROM_SIZE;
u2_chroma_csbp = u2_chroma_csbp >> 4;
{
UWORD32 i;
WORD16 ai2_tmp[16];
for(i = 0; i < 4; i++)
{
WORD16 *pi2_level = pi2_y_coeff + (i << 4);
UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + 1
+ ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR)
+ (i >> 1) * (u4_recwidth_cr << 2);
PROFILE_DISABLE_IQ_IT_RECON()
{
if(CHECKBIT(u2_chroma_csbp, i))
{
ps_dec->pf_iquant_itrans_recon_chroma_4x4(
pi2_level,
pu1_pred_sblk,
pu1_pred_sblk,
u4_recwidth_cr,
u4_recwidth_cr,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2],
u4_scale_v, ai2_tmp, pi2_level);
}
else if(pi2_level[0] != 0)
{
ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc(
pi2_level,
pu1_pred_sblk,
pu1_pred_sblk,
u4_recwidth_cr,
u4_recwidth_cr,
gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6],
(UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2],
u4_scale_v, ai2_tmp, pi2_level);
}
}
}
}
}
else
{
/* If no inverse transform is needed, pass recon buffer pointer */
/* to Intraprediction module instead of pred buffer pointer */
{
UWORD16 au2_ngbr_pels[33];
UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels;
UWORD16 *pu2_left_uv;
UWORD16 *pu2_topleft_uv;
WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff);
WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8;
pu2_topleft_uv = (UWORD16 *)pu1_u_top_left;
pu2_left_uv = (UWORD16 *)pu1_uleft;
/* Get neighbour pixels */
/* left pels */
if(u2_use_left_mb_pack)
{
WORD32 i;
if(use_left1)
{
for(i = 0; i < 4; i++)
au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i
* u4_recwidth_cr / YUV420SP_FACTOR];
}
else
{
memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16));
}
if(use_left2)
{
for(i = 4; i < 8; i++)
au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i
* u4_recwidth_cr / YUV420SP_FACTOR];
}
else
{
memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16));
}
}
else
{
memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16));
}
/* top left pels */
au2_ngbr_pels[8] = *pu2_topleft_uv;
/* top pels */
if(uc_useTopMB)
{
memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u,
8 * sizeof(UWORD16));
}
else
{
memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16));
}
PROFILE_DISABLE_INTRA_PRED()
ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode](
pu1_ngbr_pels,
pu1_mb_cb_rei1_buffer,
1,
u4_recwidth_cr,
((uc_useTopMB << 2) | (use_left2 << 4)
| use_left1));
}
}
}
return OK;
}
Vulnerability Type: DoS Exec Code Mem. Corr.
CWE ID: CWE-20
Summary: decoder/ih264d_process_intra_mb.c in mediaserver in Android 6.x before 2016-07-01 mishandles intra mode, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, aka internal bug 28165659.
Commit Message: Decoder: Fix for handling invalid intra mode
Bug: 28165659
Change-Id: I2291a287c27291695f4f3d6e753b6bbd7dfd9e42
|
Low
| 173,759
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: xfs_file_splice_write(
struct pipe_inode_info *pipe,
struct file *outfilp,
loff_t *ppos,
size_t count,
unsigned int flags)
{
struct inode *inode = outfilp->f_mapping->host;
struct xfs_inode *ip = XFS_I(inode);
int ioflags = 0;
ssize_t ret;
XFS_STATS_INC(xs_write_calls);
if (outfilp->f_mode & FMODE_NOCMTIME)
ioflags |= IO_INVIS;
if (XFS_FORCED_SHUTDOWN(ip->i_mount))
return -EIO;
xfs_ilock(ip, XFS_IOLOCK_EXCL);
trace_xfs_file_splice_write(ip, count, *ppos, ioflags);
ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags);
if (ret > 0)
XFS_STATS_ADD(xs_write_bytes, ret);
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: The implementation of certain splice_write file operations in the Linux kernel before 3.16 does not enforce a restriction on the maximum size of a single file, which allows local users to cause a denial of service (system crash) or possibly have unspecified other impact via a crafted splice system call, as demonstrated by use of a file descriptor associated with an ext4 filesystem.
Commit Message: ->splice_write() via ->write_iter()
iter_file_splice_write() - a ->splice_write() instance that gathers the
pipe buffers, builds a bio_vec-based iov_iter covering those and feeds
it to ->write_iter(). A bunch of simple cases coverted to that...
[AV: fixed the braino spotted by Cyrill]
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
|
Low
| 166,810
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: bool PasswordAutofillAgent::TryToShowTouchToFill(
const WebFormControlElement& control_element) {
const WebInputElement* element = ToWebInputElement(&control_element);
if (!element || (!base::Contains(web_input_to_password_info_, *element) &&
!base::Contains(password_to_username_, *element))) {
return false;
}
if (was_touch_to_fill_ui_shown_)
return false;
was_touch_to_fill_ui_shown_ = true;
GetPasswordManagerDriver()->ShowTouchToFill();
return true;
}
Vulnerability Type: Exec Code
CWE ID: CWE-125
Summary: An out-of-bounds read in V8 in Google Chrome prior to 57.0.2987.133 for Linux, Windows, and Mac, and 57.0.2987.132 for Android, allowed a remote attacker to execute arbitrary code inside a sandbox via a crafted HTML page, related to Array.prototype.indexOf.
Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering
Use for TouchToFill the same triggering logic that is used for regular
suggestions.
Bug: 1010233
Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230
Commit-Queue: Boris Sazonov <bsazonov@chromium.org>
Reviewed-by: Vadym Doroshenko <dvadym@chromium.org>
Cr-Commit-Position: refs/heads/master@{#702058}
|
Medium
| 172,407
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->SetRenderer(frame_host_ ? frame_host_->GetProcess() : nullptr,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler()));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
if (frame_tree_node_ && !frame_tree_node_->parent()) {
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
}
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
}
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 <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
|
Medium
| 172,781
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction) const
{
SecurityOrigin* securityOrigin = options.securityOrigin.get();
if (!securityOrigin && document())
securityOrigin = document()->securityOrigin();
if (securityOrigin && !securityOrigin->canDisplay(url)) {
if (!forPreload)
context().reportLocalLoadFailed(url);
WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource URL was not allowed by SecurityOrigin::canDisplay");
return 0;
}
bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script().shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy);
switch (type) {
case Resource::MainResource:
case Resource::Image:
case Resource::CSSStyleSheet:
case Resource::Script:
case Resource::Font:
case Resource::Raw:
case Resource::LinkPrefetch:
case Resource::LinkSubresource:
case Resource::TextTrack:
case Resource::ImportResource:
case Resource::Media:
if (originRestriction == FetchRequest::RestrictToSameOrigin && !securityOrigin->canRequest(url)) {
printAccessDeniedMessage(url);
return false;
}
break;
case Resource::XSLStyleSheet:
ASSERT(RuntimeEnabledFeatures::xsltEnabled());
case Resource::SVGDocument:
if (!securityOrigin->canRequest(url)) {
printAccessDeniedMessage(url);
return false;
}
break;
}
ContentSecurityPolicy::ReportingStatus cspReporting = forPreload ?
ContentSecurityPolicy::SuppressReport : ContentSecurityPolicy::SendReport;
switch (type) {
case Resource::XSLStyleSheet:
ASSERT(RuntimeEnabledFeatures::xsltEnabled());
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url, cspReporting))
return false;
break;
case Resource::Script:
case Resource::ImportResource:
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url, cspReporting))
return false;
if (frame()) {
Settings* settings = frame()->settings();
if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->scriptEnabled(), url)) {
frame()->loader().client()->didNotAllowScript();
return false;
}
}
break;
case Resource::CSSStyleSheet:
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowStyleFromSource(url, cspReporting))
return false;
break;
case Resource::SVGDocument:
case Resource::Image:
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowImageFromSource(url, cspReporting))
return false;
break;
case Resource::Font: {
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowFontFromSource(url, cspReporting))
return false;
break;
}
case Resource::MainResource:
case Resource::Raw:
case Resource::LinkPrefetch:
case Resource::LinkSubresource:
break;
case Resource::Media:
case Resource::TextTrack:
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url, cspReporting))
return false;
break;
}
if (!checkInsecureContent(type, url, options.mixedContentBlockingTreatment))
return false;
return true;
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The ResourceFetcher::canRequest function in core/fetch/ResourceFetcher.cpp in Blink, as used in Google Chrome before 36.0.1985.125, does not properly restrict subresource requests associated with SVG files, which allows remote attackers to bypass the Same Origin Policy via a crafted file.
Commit Message: Enforce SVG image security rules
SVG images have unique security rules that prevent them from loading
any external resources. This patch enforces these rules in
ResourceFetcher::canRequest for all non-data-uri resources. This locks
down our SVG resource handling and fixes two security bugs.
In the case of SVG images that reference other images, we had a bug
where a cached subresource would be used directly from the cache.
This has been fixed because the canRequest check occurs before we use
cached resources.
In the case of SVG images that use CSS imports, we had a bug where
imports were blindly requested. This has been fixed by stopping all
non-data-uri requests in SVG images.
With this patch we now match Gecko's behavior on both testcases.
BUG=380885, 382296
Review URL: https://codereview.chromium.org/320763002
git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
Medium
| 171,671
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: xsltStylesheetPtr XSLStyleSheet::compileStyleSheet()
{
if (m_embedded)
return xsltLoadStylesheetPI(document());
ASSERT(!m_stylesheetDocTaken);
xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc);
if (result)
m_stylesheetDocTaken = true;
return result;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in the XSLStyleSheet::compileStyleSheet function in core/xml/XSLStyleSheetLibxslt.cpp in Blink, as used in Google Chrome before 30.0.1599.66, allows remote attackers to cause a denial of service or possibly have unspecified other impact by leveraging improper handling of post-failure recompilation in unspecified libxslt versions.
Commit Message: Avoid reparsing an XSLT stylesheet after the first failure.
Certain libxslt versions appear to leave the doc in an invalid state when parsing fails. We should cache this result and avoid re-parsing.
(The test cannot be converted to text-only due to its invalid stylesheet).
R=inferno@chromium.org,abarth@chromium.org,pdr@chromium.org
BUG=271939
Review URL: https://chromiumcodereview.appspot.com/23103007
git-svn-id: svn://svn.chromium.org/blink/trunk@156248 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
Medium
| 171,185
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void InspectorClientImpl::clearBrowserCache()
{
if (WebDevToolsAgentImpl* agent = devToolsAgent())
agent->clearBrowserCache();
}
Vulnerability Type:
CWE ID:
Summary: Google Chrome before 25.0.1364.97 on Windows and Linux, and before 25.0.1364.99 on Mac OS X, does not properly load Native Client (aka NaCl) code, which has unspecified impact and attack vectors.
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
Low
| 171,346
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: png_get_mmx_rowbytes_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0L: 0L);
}
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
TBR=darin@chromium.org
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
|
Low
| 172,167
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: __imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax)
{
ImlibUpdate *nu = NULL, *uu;
struct _tile *t;
int tw, th, x, y, i;
int *gaps = NULL;
/* if theres no rects to process.. return NULL */
if (!u)
return NULL;
tw = w >> TB;
if (w & TM)
tw++;
th = h >> TB;
if (h & TM)
th++;
t = malloc(tw * th * sizeof(struct _tile));
/* fill in tiles to be all not used */
for (i = 0, y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
t[i++].used = T_UNUSED;
}
/* fill in all tiles */
for (uu = u; uu; uu = uu->next)
{
CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h);
for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++)
{
for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++)
T(x, y).used = T_USED;
}
}
/* scan each line - if > hgapmax gaps between tiles, then fill smallest */
gaps = malloc(tw * sizeof(int));
for (y = 0; y < th; y++)
{
int hgaps = 0, start = -1, min;
char have = 1, gap = 0;
for (x = 0; x < tw; x++)
gaps[x] = 0;
for (x = 0; x < tw; x++)
{
if ((have) && (T(x, y).used == T_UNUSED))
{
start = x;
gap = 1;
have = 0;
}
else if ((!have) && (gap) && (T(x, y).used & T_USED))
{
gap = 0;
hgaps++;
have = 1;
gaps[start] = x - start;
}
else if (T(x, y).used & T_USED)
have = 1;
}
while (hgaps > hgapmax)
{
start = -1;
min = tw;
for (x = 0; x < tw; x++)
{
if ((gaps[x] > 0) && (gaps[x] < min))
{
start = x;
min = gaps[x];
}
}
if (start >= 0)
{
gaps[start] = 0;
for (x = start;
T(x, y).used == T_UNUSED; T(x++, y).used = T_USED);
hgaps--;
}
}
}
free(gaps);
/* coalesce tiles into larger blocks and make new rect list */
for (y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
{
if (T(x, y).used & T_USED)
{
int xx, yy, ww, hh, ok, xww;
for (xx = x + 1, ww = 1;
(T(xx, y).used & T_USED) && (xx < tw); xx++, ww++);
xww = x + ww;
for (yy = y + 1, hh = 1, ok = 1;
(yy < th) && (ok); yy++, hh++)
{
for (xx = x; xx < xww; xx++)
{
if (!(T(xx, yy).used & T_USED))
{
ok = 0;
hh--;
break;
}
}
}
for (yy = y; yy < (y + hh); yy++)
{
for (xx = x; xx < xww; xx++)
T(xx, yy).used = T_UNUSED;
}
nu = __imlib_AddUpdate(nu, (x << TB), (y << TB),
(ww << TB), (hh << TB));
}
}
}
free(t);
__imlib_FreeUpdates(u);
return nu;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Off-by-one error in the __imlib_MergeUpdate function in lib/updates.c in imlib2 before 1.4.9 allows remote attackers to cause a denial of service (out-of-bounds read and application crash) via crafted coordinates.
Commit Message:
|
Low
| 165,080
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void GpuCommandBufferStub::OnCreateVideoDecoder(
media::VideoCodecProfile profile,
IPC::Message* reply_message) {
int decoder_route_id = channel_->GenerateRouteID();
GpuCommandBufferMsg_CreateVideoDecoder::WriteReplyParams(
reply_message, decoder_route_id);
GpuVideoDecodeAccelerator* decoder =
new GpuVideoDecodeAccelerator(this, decoder_route_id, this);
video_decoders_.AddWithID(decoder, decoder_route_id);
channel_->AddRoute(decoder_route_id, decoder);
decoder->Initialize(profile, reply_message,
channel_->renderer_process());
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 170,936
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int virtio_net_load(QEMUFile *f, void *opaque, int version_id)
{
VirtIONet *n = opaque;
VirtIODevice *vdev = VIRTIO_DEVICE(n);
int ret, i, link_down;
if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION)
return -EINVAL;
ret = virtio_load(vdev, f);
if (ret) {
return ret;
}
qemu_get_buffer(f, n->mac, ETH_ALEN);
n->vqs[0].tx_waiting = qemu_get_be32(f);
virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f));
if (version_id >= 3)
n->status = qemu_get_be16(f);
if (version_id >= 4) {
if (version_id < 8) {
n->promisc = qemu_get_be32(f);
n->allmulti = qemu_get_be32(f);
} else {
n->promisc = qemu_get_byte(f);
n->allmulti = qemu_get_byte(f);
}
}
if (version_id >= 5) {
n->mac_table.in_use = qemu_get_be32(f);
/* MAC_TABLE_ENTRIES may be different from the saved image */
if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) {
qemu_get_buffer(f, n->mac_table.macs,
n->mac_table.in_use * ETH_ALEN);
} else if (n->mac_table.in_use) {
uint8_t *buf = g_malloc0(n->mac_table.in_use);
qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN);
g_free(buf);
n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1;
n->mac_table.in_use = 0;
}
error_report("virtio-net: saved image requires vnet_hdr=on");
return -1;
}
}
Vulnerability Type: Exec Code Overflow
CWE ID: CWE-119
Summary: Buffer overflow in virtio_net_load function in net/virtio-net.c in QEMU 1.3.0 through 1.7.x before 1.7.2 might allow remote attackers to execute arbitrary code via a large MAC table.
Commit Message:
|
Low
| 165,363
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int modbus_reply(modbus_t *ctx, const uint8_t *req,
int req_length, modbus_mapping_t *mb_mapping)
{
int offset;
int slave;
int function;
uint16_t address;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length = 0;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
address = (req[offset + 1] << 8) + req[offset + 2];
sft.slave = slave;
sft.function = function;
sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
/* Data are flushed on illegal number of values errors. */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
const char * const name = is_input ? "read_input_bits" : "read_bits";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_bits;
if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_BITS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
rsp_length = response_io_status(tab_bits, mapping_address, nb,
rsp, rsp_length);
}
}
break;
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS: {
unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
const char * const name = is_input ? "read_input_registers" : "read_registers";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_registers;
if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_REGISTERS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
int i;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = tab_registers[i] >> 8;
rsp[rsp_length++] = tab_registers[i] & 0xFF;
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_COIL: {
int mapping_address = address - mb_mapping->start_bits;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bit\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
memcpy(rsp, req, req_length);
rsp_length = req_length;
} else {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,
"Illegal data value 0x%0X in write_bit request at address %0X\n",
data, address);
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int mapping_address = address - mb_mapping->start_bits;
if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) {
/* May be the indication has been truncated on reading because of
* invalid address (eg. nb is 0 but the request contains values to
* write) so it's necessary to flush. */
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_bits (max %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bits\n",
mapping_address < 0 ? address : address + nb);
} else {
/* 6 = byte count */
modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,
&req[offset + 6]);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the bit address (2) and the quantity of bits */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int mapping_address = address - mb_mapping->start_registers;
if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_registers (max %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_registers\n",
mapping_address < 0 ? address : address + nb);
} else {
int i, j;
for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
/* 6 and 7 = first value */
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_REPORT_SLAVE_ID: {
int str_len;
int byte_count_pos;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Skip byte count for now */
byte_count_pos = rsp_length++;
rsp[rsp_length++] = _REPORT_SLAVE_ID;
/* Run indicator status to ON */
rsp[rsp_length++] = 0xFF;
/* LMB + length of LIBMODBUS_VERSION_STRING */
str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
rsp_length += str_len;
rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
}
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
if (ctx->debug) {
fprintf(stderr, "FIXME Not implemented\n");
}
errno = ENOPROTOOPT;
return -1;
break;
case MODBUS_FC_MASK_WRITE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
uint16_t data = mb_mapping->tab_registers[mapping_address];
uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
data = (data & and) | (or & (~and));
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
int nb_write = (req[offset + 7] << 8) + req[offset + 8];
int nb_write_bytes = req[offset + 9];
int mapping_address = address - mb_mapping->start_registers;
int mapping_address_write = address_write - mb_mapping->start_registers;
if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||
nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||
nb_write_bytes != nb_write * 2) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n",
nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers ||
mapping_address < 0 ||
(mapping_address_write + nb_write) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n",
mapping_address < 0 ? address : address + nb,
mapping_address_write < 0 ? address_write : address_write + nb_write);
} else {
int i, j;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
/* Write first.
10 and 11 are the offset of the first values to write */
for (i = mapping_address_write, j = 10;
i < mapping_address_write + nb_write; i++, j += 2) {
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
/* and read the data for the response */
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
}
}
}
break;
default:
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,
"Unknown Modbus function code: 0x%0X\n", function);
break;
}
/* Suppress any responses when the request was a broadcast */
return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);
}
Vulnerability Type:
CWE ID: CWE-125
Summary: An issue was discovered in libmodbus before 3.0.7 and 3.1.x before 3.1.5. There is an out-of-bounds read for the MODBUS_FC_WRITE_MULTIPLE_REGISTERS case, aka VD-1301.
Commit Message: Fix VD-1301 and VD-1302 vulnerabilities
This patch was contributed by Maor Vermucht and Or Peles from
VDOO Connected Trust.
|
Low
| 169,581
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
BUG_ON(new->thread_keyring);
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
Vulnerability Type: DoS
CWE ID: CWE-404
Summary: The KEYS subsystem in the Linux kernel before 4.10.13 allows local users to cause a denial of service (memory consumption) via a series of KEY_REQKEY_DEFL_THREAD_KEYRING keyctl_set_reqkey_keyring calls.
Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings
This fixes CVE-2017-7472.
Running the following program as an unprivileged user exhausts kernel
memory by leaking thread keyrings:
#include <keyutils.h>
int main()
{
for (;;)
keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING);
}
Fix it by only creating a new thread keyring if there wasn't one before.
To make things more consistent, make install_thread_keyring_to_cred()
and install_process_keyring_to_cred() both return 0 if the corresponding
keyring is already present.
Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials")
Cc: stable@vger.kernel.org # 2.6.29+
Signed-off-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: David Howells <dhowells@redhat.com>
|
Low
| 168,276
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index,
const OMX_PTR param) {
const int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
return internalSetBitrateParams(
(const OMX_VIDEO_PARAM_BITRATETYPE *)param);
case OMX_IndexParamVideoVp8:
return internalSetVp8Params(
(const OMX_VIDEO_PARAM_VP8TYPE *)param);
case OMX_IndexParamVideoAndroidVp8Encoder:
return internalSetAndroidVp8Params(
(const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param);
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, param);
}
}
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
|
Medium
| 174,214
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
Vulnerability Type: DoS
CWE ID:
Summary: The sigalgs implementation in t1_lib.c in OpenSSL 1.0.2 before 1.0.2a allows remote attackers to cause a denial of service (NULL pointer dereference and daemon crash) by using an invalid signature_algorithms extension in the ClientHello message during a renegotiation.
Commit Message:
|
Low
| 164,804
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
const GURL& base_url,
bool shared_worker_frontend,
bool v8_only_frontend,
const std::string& remote_frontend,
bool can_dock) {
if (base_url.SchemeIs("data"))
return base_url;
std::string frontend_url(
!remote_frontend.empty() ?
remote_frontend :
base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec());
std::string url_string(
frontend_url +
((frontend_url.find("?") == std::string::npos) ? "?" : "&"));
if (shared_worker_frontend)
url_string += "&isSharedWorker=true";
if (v8_only_frontend)
url_string += "&v8only=true";
if (remote_frontend.size()) {
url_string += "&remoteFrontend=true";
} else {
url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec();
}
if (can_dock)
url_string += "&can_dock=true";
return GURL(url_string);
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android insufficiently sanitized DevTools URLs, which allowed a remote attacker to read local files via a crafted HTML page.
Commit Message: [DevTools] Move sanitize url to devtools_ui.cc.
Compatibility script is not reliable enough.
BUG=653134
Review-Url: https://codereview.chromium.org/2403633002
Cr-Commit-Position: refs/heads/master@{#425814}
|
Medium
| 172,509
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: PHP_MINIT_FUNCTION(spl_directory)
{
REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions);
memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone;
spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast;
spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info;
spl_ce_SplFileInfo->serialize = zend_class_serialize_deny;
spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny;
REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions);
zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator);
REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator);
spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS);
spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions);
REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator);
memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers));
spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check;
#ifdef HAVE_GLOB
REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions);
REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable);
#endif
REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions);
REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator);
REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV);
REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions);
return SUCCESS;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Integer overflow in the SplFileObject::fread function in spl_directory.c in the SPL extension in PHP before 5.5.37 and 5.6.x before 5.6.23 allows remote attackers to cause a denial of service or possibly have unspecified other impact via a large integer argument, a related issue to CVE-2016-5096.
Commit Message: Fix bug #72262 - do not overflow int
|
Low
| 167,026
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: NO_INLINE JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a) {
assert(!a || jsvIsName(a));
JSP_ASSERT_MATCH(LEX_ARROW_FUNCTION);
funcVar = jspeAddNamedFunctionParameter(funcVar, a);
bool expressionOnly = lex->tk!='{';
jspeFunctionDefinitionInternal(funcVar, expressionOnly);
if (execInfo.thisVar) {
jsvObjectSetChild(funcVar, JSPARSE_FUNCTION_THIS_NAME, execInfo.thisVar);
}
return funcVar;
}
NO_INLINE JsVar *jspeExpressionOrArrowFunction() {
JsVar *a = 0;
JsVar *funcVar = 0;
bool allNames = true;
while (lex->tk!=')' && !JSP_SHOULDNT_PARSE) {
if (allNames && a) {
funcVar = jspeAddNamedFunctionParameter(funcVar, a);
}
jsvUnLock(a);
a = jspeAssignmentExpression();
if (!(jsvIsName(a) && jsvIsString(a))) allNames = false;
if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock2(a,funcVar), 0);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(a,funcVar), 0);
if (allNames && lex->tk==LEX_ARROW_FUNCTION) {
funcVar = jspeArrowFunction(funcVar, a);
jsvUnLock(a);
return funcVar;
} else {
jsvUnLock(funcVar);
return a;
}
}
NO_INLINE JsVar *jspeClassDefinition(bool parseNamedClass) {
JsVar *classFunction = 0;
JsVar *classPrototype = 0;
JsVar *classInternalName = 0;
bool actuallyCreateClass = JSP_SHOULD_EXECUTE;
if (actuallyCreateClass)
classFunction = jsvNewWithFlags(JSV_FUNCTION);
if (parseNamedClass && lex->tk==LEX_ID) {
if (classFunction)
classInternalName = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_ID);
}
if (classFunction) {
JsVar *prototypeName = jsvFindChildFromString(classFunction, JSPARSE_PROTOTYPE_VAR, true);
jspEnsureIsPrototype(classFunction, prototypeName); // make sure it's an object
classPrototype = jsvSkipName(prototypeName);
jsvUnLock(prototypeName);
}
if (lex->tk==LEX_R_EXTENDS) {
JSP_ASSERT_MATCH(LEX_R_EXTENDS);
JsVar *extendsFrom = actuallyCreateClass ? jsvSkipNameAndUnLock(jspGetNamedVariable(jslGetTokenValueAsString(lex))) : 0;
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock4(extendsFrom,classFunction,classInternalName,classPrototype),0);
if (classPrototype) {
if (jsvIsFunction(extendsFrom)) {
jsvObjectSetChild(classPrototype, JSPARSE_INHERITS_VAR, extendsFrom);
jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_CODE_NAME, jsvNewFromString("if(this.__proto__.__proto__)this.__proto__.__proto__.apply(this,arguments)"));
} else
jsExceptionHere(JSET_SYNTAXERROR, "'extends' argument should be a function, got %t", extendsFrom);
}
jsvUnLock(extendsFrom);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN('{',jsvUnLock3(classFunction,classInternalName,classPrototype),0);
while ((lex->tk==LEX_ID || lex->tk==LEX_R_STATIC) && !jspIsInterrupted()) {
bool isStatic = lex->tk==LEX_R_STATIC;
if (isStatic) JSP_ASSERT_MATCH(LEX_R_STATIC);
JsVar *funcName = jslGetTokenValueAsVar(lex);
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock3(classFunction,classInternalName,classPrototype),0);
JsVar *method = jspeFunctionDefinition(false);
if (classFunction && classPrototype) {
if (jsvIsStringEqual(funcName, "get") || jsvIsStringEqual(funcName, "set")) {
jsExceptionHere(JSET_SYNTAXERROR, "'get' and 'set' and not supported in Espruino");
} else if (jsvIsStringEqual(funcName, "constructor")) {
jswrap_function_replaceWith(classFunction, method);
} else {
funcName = jsvMakeIntoVariableName(funcName, 0);
jsvSetValueOfName(funcName, method);
jsvAddName(isStatic ? classFunction : classPrototype, funcName);
}
}
jsvUnLock2(method,funcName);
}
jsvUnLock(classPrototype);
if (classInternalName)
jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_NAME_NAME, classInternalName);
JSP_MATCH_WITH_CLEANUP_AND_RETURN('}',jsvUnLock(classFunction),0);
return classFunction;
}
#endif
NO_INLINE JsVar *jspeFactor() {
if (lex->tk==LEX_ID) {
JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex));
JSP_ASSERT_MATCH(LEX_ID);
#ifndef SAVE_ON_FLASH
if (lex->tk==LEX_TEMPLATE_LITERAL)
jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported");
else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) {
JsVar *funcVar = jspeArrowFunction(0,a);
jsvUnLock(a);
a=funcVar;
}
#endif
return a;
} else if (lex->tk==LEX_INT) {
JsVar *v = 0;
if (JSP_SHOULD_EXECUTE) {
v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex)));
}
JSP_ASSERT_MATCH(LEX_INT);
return v;
} else if (lex->tk==LEX_FLOAT) {
JsVar *v = 0;
if (JSP_SHOULD_EXECUTE) {
v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex)));
}
JSP_ASSERT_MATCH(LEX_FLOAT);
return v;
} else if (lex->tk=='(') {
JSP_ASSERT_MATCH('(');
if (!jspCheckStackPosition()) return 0;
#ifdef SAVE_ON_FLASH
JsVar *a = jspeExpression();
if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a);
return a;
#else
return jspeExpressionOrArrowFunction();
#endif
} else if (lex->tk==LEX_R_TRUE) {
JSP_ASSERT_MATCH(LEX_R_TRUE);
return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0;
} else if (lex->tk==LEX_R_FALSE) {
JSP_ASSERT_MATCH(LEX_R_FALSE);
return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0;
} else if (lex->tk==LEX_R_NULL) {
JSP_ASSERT_MATCH(LEX_R_NULL);
return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0;
} else if (lex->tk==LEX_R_UNDEFINED) {
JSP_ASSERT_MATCH(LEX_R_UNDEFINED);
return 0;
} else if (lex->tk==LEX_STR) {
JsVar *a = 0;
if (JSP_SHOULD_EXECUTE)
a = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_STR);
return a;
#ifndef SAVE_ON_FLASH
} else if (lex->tk==LEX_TEMPLATE_LITERAL) {
return jspeTemplateLiteral();
#endif
} else if (lex->tk==LEX_REGEX) {
JsVar *a = 0;
#ifdef SAVE_ON_FLASH
jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n");
#else
JsVar *regex = jslGetTokenValueAsVar(lex);
size_t regexEnd = 0, regexLen = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, regex, 0);
while (jsvStringIteratorHasChar(&it)) {
regexLen++;
if (jsvStringIteratorGetChar(&it)=='/')
regexEnd = regexLen;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
JsVar *flags = 0;
if (regexEnd < regexLen)
flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH);
JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2);
a = jswrap_regexp_constructor(regexSource, flags);
jsvUnLock3(regex, flags, regexSource);
#endif
JSP_ASSERT_MATCH(LEX_REGEX);
return a;
} else if (lex->tk=='{') {
if (!jspCheckStackPosition()) return 0;
return jspeFactorObject();
} else if (lex->tk=='[') {
if (!jspCheckStackPosition()) return 0;
return jspeFactorArray();
} else if (lex->tk==LEX_R_FUNCTION) {
if (!jspCheckStackPosition()) return 0;
JSP_ASSERT_MATCH(LEX_R_FUNCTION);
return jspeFunctionDefinition(true);
#ifndef SAVE_ON_FLASH
} else if (lex->tk==LEX_R_CLASS) {
if (!jspCheckStackPosition()) return 0;
JSP_ASSERT_MATCH(LEX_R_CLASS);
return jspeClassDefinition(true);
} else if (lex->tk==LEX_R_SUPER) {
JSP_ASSERT_MATCH(LEX_R_SUPER);
/* This is kind of nasty, since super appears to do
three different things.
* In the constructor it references the extended class's constructor
* in a method it references the constructor's prototype.
* in a static method it references the extended class's constructor (but this is different)
*/
if (jsvIsObject(execInfo.thisVar)) {
JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first
JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__
jsvUnLock(proto1);
if (!proto2) {
jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class");
return 0;
}
if (lex->tk=='(') return proto2; // eg. used in a constructor
JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0;
jsvUnLock(proto2);
return proto3;
} else if (jsvIsFunction(execInfo.thisVar)) {
JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0);
JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0;
jsvUnLock(proto1);
if (!proto2) {
jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class");
return 0;
}
return proto2;
}
jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class");
return 0;
#endif
} else if (lex->tk==LEX_R_THIS) {
JSP_ASSERT_MATCH(LEX_R_THIS);
return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root );
} else if (lex->tk==LEX_R_DELETE) {
if (!jspCheckStackPosition()) return 0;
return jspeFactorDelete();
} else if (lex->tk==LEX_R_TYPEOF) {
if (!jspCheckStackPosition()) return 0;
return jspeFactorTypeOf();
} else if (lex->tk==LEX_R_VOID) {
JSP_ASSERT_MATCH(LEX_R_VOID);
jsvUnLock(jspeUnaryExpression());
return 0;
}
JSP_MATCH(LEX_EOF);
jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n");
return 0;
}
NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) {
while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) {
int op = lex->tk;
JSP_ASSERT_MATCH(op);
if (JSP_SHOULD_EXECUTE) {
JsVar *one = jsvNewFromInteger(1);
JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number)
JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-');
jsvUnLock(one);
jspReplaceWith(a, res);
jsvUnLock(res);
jsvUnLock(a);
a = oldValue;
}
}
return a;
}
NO_INLINE JsVar *jspePostfixExpression() {
JsVar *a;
if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) {
int op = lex->tk;
JSP_ASSERT_MATCH(op);
a = jspePostfixExpression();
if (JSP_SHOULD_EXECUTE) {
JsVar *one = jsvNewFromInteger(1);
JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-');
jsvUnLock(one);
jspReplaceWith(a, res);
jsvUnLock(res);
}
} else
a = jspeFactorFunctionCall();
return __jspePostfixExpression(a);
}
NO_INLINE JsVar *jspeUnaryExpression() {
if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') {
short tk = lex->tk;
JSP_ASSERT_MATCH(tk);
if (!JSP_SHOULD_EXECUTE) {
return jspeUnaryExpression();
}
if (tk=='!') { // logical not
return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression())));
} else if (tk=='~') { // bitwise not
return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression())));
} else if (tk=='-') { // unary minus
return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped
} else if (tk=='+') { // unary plus (convert to number)
JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression());
JsVar *r = jsvAsNumber(v); // names already skipped
jsvUnLock(v);
return r;
}
assert(0);
return 0;
} else
return jspePostfixExpression();
}
unsigned int jspeGetBinaryExpressionPrecedence(int op) {
switch (op) {
case LEX_OROR: return 1; break;
case LEX_ANDAND: return 2; break;
case '|' : return 3; break;
case '^' : return 4; break;
case '&' : return 5; break;
case LEX_EQUAL:
case LEX_NEQUAL:
case LEX_TYPEEQUAL:
case LEX_NTYPEEQUAL: return 6;
case LEX_LEQUAL:
case LEX_GEQUAL:
case '<':
case '>':
case LEX_R_INSTANCEOF: return 7;
case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7;
case LEX_LSHIFT:
case LEX_RSHIFT:
case LEX_RSHIFTUNSIGNED: return 8;
case '+':
case '-': return 9;
case '*':
case '/':
case '%': return 10;
default: return 0;
}
}
NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) {
/* This one's a bit strange. Basically all the ops have their own precedence, it's not
* like & and | share the same precedence. We don't want to recurse for each one,
* so instead we do this.
*
* We deal with an expression in recursion ONLY if it's of higher precedence
* than the current one, otherwise we stick in the while loop.
*/
unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk);
while (precedence && precedence>lastPrecedence) {
int op = lex->tk;
JSP_ASSERT_MATCH(op);
if (op==LEX_ANDAND || op==LEX_OROR) {
bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a));
if ((!aValue && op==LEX_ANDAND) ||
(aValue && op==LEX_OROR)) {
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence));
JSP_RESTORE_EXECUTE();
} else {
jsvUnLock(a);
a = __jspeBinaryExpression(jspeUnaryExpression(),precedence);
}
} else { // else it's a more 'normal' logical expression - just use Maths
JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence);
if (JSP_SHOULD_EXECUTE) {
if (op==LEX_R_IN) {
JsVar *av = jsvSkipName(a); // needle
JsVar *bv = jsvSkipName(b); // haystack
if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values
av = jsvAsArrayIndexAndUnLock(av);
JsVar *varFound = jspGetVarNamedField( bv, av, true);
jsvUnLock(a);
a = jsvNewFromBool(varFound!=0);
jsvUnLock(varFound);
} else {// else it will be undefined
jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv);
jsvUnLock(a);
a = 0;
}
jsvUnLock2(av, bv);
} else if (op==LEX_R_INSTANCEOF) {
bool inst = false;
JsVar *av = jsvSkipName(a);
JsVar *bv = jsvSkipName(b);
if (!jsvIsFunction(bv)) {
jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv);
} else {
if (jsvIsObject(av) || jsvIsFunction(av)) {
JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false);
JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0);
while (proto) {
if (proto == bproto) inst=true;
JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0);
jsvUnLock(proto);
proto = childProto;
}
if (jspIsConstructor(bv, "Object")) inst = true;
jsvUnLock(bproto);
}
if (!inst) {
const char *name = jswGetBasicObjectName(av);
if (name) {
inst = jspIsConstructor(bv, name);
}
if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) &&
jspIsConstructor(bv, "Object"))
inst = true;
}
}
jsvUnLock3(av, bv, a);
a = jsvNewFromBool(inst);
} else { // --------------------------------------------- NORMAL
JsVar *res = jsvMathsOpSkipNames(a, b, op);
jsvUnLock(a); a = res;
}
}
jsvUnLock(b);
}
precedence = jspeGetBinaryExpressionPrecedence(lex->tk);
}
return a;
}
JsVar *jspeBinaryExpression() {
return __jspeBinaryExpression(jspeUnaryExpression(),0);
}
NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) {
if (lex->tk=='?') {
JSP_ASSERT_MATCH('?');
if (!JSP_SHOULD_EXECUTE) {
jsvUnLock(jspeAssignmentExpression());
JSP_MATCH(':');
jsvUnLock(jspeAssignmentExpression());
} else {
bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs));
jsvUnLock(lhs);
if (first) {
lhs = jspeAssignmentExpression();
JSP_MATCH(':');
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(jspeAssignmentExpression());
JSP_RESTORE_EXECUTE();
} else {
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(jspeAssignmentExpression());
JSP_RESTORE_EXECUTE();
JSP_MATCH(':');
lhs = jspeAssignmentExpression();
}
}
}
return lhs;
}
JsVar *jspeConditionalExpression() {
return __jspeConditionalExpression(jspeBinaryExpression());
}
NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) {
if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL ||
lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL ||
lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL ||
lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL ||
lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
JsVar *rhs;
int op = lex->tk;
JSP_ASSERT_MATCH(op);
rhs = jspeAssignmentExpression();
rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
if (JSP_SHOULD_EXECUTE && lhs) {
if (op=='=') {
/* If we're assigning to this and we don't have a parent,
* add it to the symbol table root */
if (!jsvGetRefs(lhs) && jsvIsName(lhs)) {
if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs))
jsvAddName(execInfo.root, lhs);
}
jspReplaceWith(lhs, rhs);
} else {
if (op==LEX_PLUSEQUAL) op='+';
else if (op==LEX_MINUSEQUAL) op='-';
else if (op==LEX_MULEQUAL) op='*';
else if (op==LEX_DIVEQUAL) op='/';
else if (op==LEX_MODEQUAL) op='%';
else if (op==LEX_ANDEQUAL) op='&';
else if (op==LEX_OREQUAL) op='|';
else if (op==LEX_XOREQUAL) op='^';
else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
if (op=='+' && jsvIsName(lhs)) {
JsVar *currentValue = jsvSkipName(lhs);
if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) {
/* A special case for string += where this is the only use of the string
* and we're not appending to ourselves. In this case we can do a
* simple append (rather than clone + append)*/
JsVar *str = jsvAsString(rhs, false);
jsvAppendStringVarComplete(currentValue, str);
jsvUnLock(str);
op = 0;
}
jsvUnLock(currentValue);
}
if (op) {
/* Fallback which does a proper add */
JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
jspReplaceWith(lhs, res);
jsvUnLock(res);
}
}
}
jsvUnLock(rhs);
}
return lhs;
}
JsVar *jspeAssignmentExpression() {
return __jspeAssignmentExpression(jspeConditionalExpression());
}
NO_INLINE JsVar *jspeExpression() {
while (!JSP_SHOULDNT_PARSE) {
JsVar *a = jspeAssignmentExpression();
if (lex->tk!=',') return a;
jsvUnLock(a);
JSP_ASSERT_MATCH(',');
}
return 0;
}
/** Parse a block `{ ... }` but assume brackets are already parsed */
NO_INLINE void jspeBlockNoBrackets() {
if (JSP_SHOULD_EXECUTE) {
while (lex->tk && lex->tk!='}') {
jsvUnLock(jspeStatement());
if (JSP_HAS_ERROR) {
if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) {
execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED);
JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0);
if (stackTrace) {
jsvAppendPrintf(stackTrace, "at ");
jspAppendStackTrace(stackTrace);
jsvUnLock(stackTrace);
}
}
}
if (JSP_SHOULDNT_PARSE)
return;
}
} else {
int brackets = 0;
while (lex->tk && (brackets || lex->tk != '}')) {
if (lex->tk == '{') brackets++;
if (lex->tk == '}') brackets--;
JSP_ASSERT_MATCH(lex->tk);
}
}
return;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Espruino before 1.99 allows attackers to cause a denial of service (application crash) with a user crafted input file via a Buffer Overflow during syntax parsing of *VOID* tokens in jsparse.c.
Commit Message: Fix stack overflow if void void void... is repeated many times (fix #1434)
|
Medium
| 169,213
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pmd_access_permitted(orig, write))
return 0;
if (pmd_devmap(orig))
return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
refs = 0;
page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pmd_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Vulnerability Type: Overflow
CWE ID: CWE-416
Summary: The Linux kernel before 5.1-rc5 allows page->_refcount reference count overflow, with resultant use-after-free issues, if about 140 GiB of RAM exists. This is related to fs/fuse/dev.c, fs/pipe.c, fs/splice.c, include/linux/mm.h, include/linux/pipe_fs_i.h, kernel/trace/trace.c, mm/gup.c, and mm/hugetlb.c. It can occur with FUSE requests.
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
|
Low
| 170,226
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: void handle_lddfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
unsigned long pc = regs->tpc;
unsigned long tstate = regs->tstate;
u32 insn;
u64 value;
u8 freg;
int flag;
struct fpustate *f = FPUSTATE;
if (tstate & TSTATE_PRIV)
die_if_kernel("lddfmna from kernel", regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
int asi = decode_asi(insn, regs);
u32 first, second;
int err;
if ((asi > ASI_SNFL) ||
(asi < ASI_P))
goto daex;
first = second = 0;
err = get_user(first, (u32 __user *)sfar);
if (!err)
err = get_user(second, (u32 __user *)(sfar + 4));
if (err) {
if (!(asi & 0x2))
goto daex;
first = second = 0;
}
save_and_clear_fpu();
freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
value = (((u64)first) << 32) | second;
if (asi & 0x8) /* Little */
value = __swab64p(&value);
flag = (freg < 32) ? FPRS_DL : FPRS_DU;
if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) {
current_thread_info()->fpsaved[0] = FPRS_FEF;
current_thread_info()->gsr[0] = 0;
}
if (!(current_thread_info()->fpsaved[0] & flag)) {
if (freg < 32)
memset(f->regs, 0, 32*sizeof(u32));
else
memset(f->regs+32, 0, 32*sizeof(u32));
}
*(u64 *)(f->regs + freg) = value;
current_thread_info()->fpsaved[0] |= flag;
} else {
daex:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, sfar, sfsr);
else
spitfire_data_access_exception(regs, sfsr, sfar);
return;
}
advance(regs);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-399
Summary: The Performance Events subsystem in the Linux kernel before 3.1 does not properly handle event overflows associated with PERF_COUNT_SW_CPU_CLOCK events, which allows local users to cause a denial of service (system hang) via a crafted application.
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
|
Low
| 165,808
|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
|
Code: parse_charstrings( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Int n, num_glyphs;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
num_glyphs = (FT_Int)T1_ToInt( parser );
if ( num_glyphs < 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* some fonts like Optima-Oblique not only define the /CharStrings */
/* array but access it also */
if ( num_glyphs == 0 || parser->root.error )
return;
/* initialize tables, leaving space for addition of .notdef, */
/* if necessary, and a few other glyphs to handle buggy */
/* fonts which have more glyphs than specified. */
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( !loader->num_glyphs )
{
error = psaux->ps_table_funcs->init(
code_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init(
name_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
}
n = 0;
for (;;)
{
FT_Long size;
FT_Byte* base;
/* the format is simple: */
/* `/glyphname' + binary data */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* we stop when we find a `def' or `end' keyword */
if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) )
{
if ( cur[0] == 'd' &&
cur[1] == 'e' &&
cur[2] == 'f' )
{
/* There are fonts which have this: */
/* */
/* /CharStrings 118 dict def */
/* Private begin */
/* CharStrings begin */
/* ... */
/* */
/* To catch this we ignore `def' if */
/* no charstring has actually been */
/* seen. */
if ( n )
break;
}
if ( cur[0] == 'e' &&
cur[1] == 'n' &&
cur[2] == 'd' )
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
if ( *cur == '/' )
{
FT_PtrDist len;
if ( cur + 1 >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( loader->num_glyphs )
continue;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
if ( face->type1.private_dict.lenIV >= 0 &&
n < num_glyphs + TABLE_EXTEND )
{
FT_Byte* temp;
if ( size <= face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( code_table, n,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( code_table, n, base, size );
if ( error )
goto Fail;
n++;
}
}
loader->num_glyphs = n;
/* if /.notdef is found but does not occupy index 0, do our magic. */
if ( notdef_found &&
ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) )
{
/* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */
/* name and code entries to swap_table. Then place notdef_index */
/* name and code entries into swap_table. Then swap name and code */
/* entries at indices notdef_index and 0 using values stored in */
/* swap_table. */
/* Index 0 name */
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
/* Index 0 code */
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
/* Index notdef_index name */
error = T1_Add_Table( swap_table, 2,
name_table->elements[notdef_index],
name_table->lengths [notdef_index] );
if ( error )
goto Fail;
/* Index notdef_index code */
error = T1_Add_Table( swap_table, 3,
code_table->elements[notdef_index],
code_table->lengths [notdef_index] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, notdef_index,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, notdef_index,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0,
swap_table->elements[2],
swap_table->lengths [2] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0,
swap_table->elements[3],
swap_table->lengths [3] );
if ( error )
goto Fail;
}
else if ( !notdef_found )
{
/* notdef_index is already 0, or /.notdef is undefined in */
/* charstrings dictionary. Worry about /.notdef undefined. */
/* We take index 0 and add it to the end of the table(s) */
/* and add our own /.notdef glyph to index 0. */
/* 0 333 hsbw endchar */
FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E };
char* notdef_name = (char *)".notdef";
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0, notdef_name, 8 );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0, notdef_glyph, 5 );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, n,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, n,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
/* we added a glyph. */
loader->num_glyphs += 1;
}
return;
Fail:
parser->root.error = error;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: FreeType before 2.5.4 does not check for the end of the data during certain parsing actions, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted Type42 font, related to type42/t42parse.c and type1/t1load.c.
Commit Message:
|
Medium
| 164,855
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.