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: void usage_exit() {
fprintf(stderr, "Usage: %s <infile> <outfile>\n", exec_name);
exit(EXIT_FAILURE);
}
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: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
|
Low
| 174,475
|
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 OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request,
ProfileIOData* io_data,
int child_id,
int route_id) {
std::string google_chrome_signin_value;
std::string google_accounts_signin_value;
request->GetResponseHeaderByName("Google-Chrome-SignIn",
&google_chrome_signin_value);
request->GetResponseHeaderByName("Google-Accounts-SignIn",
&google_accounts_signin_value);
if (!google_accounts_signin_value.empty() ||
!google_chrome_signin_value.empty()) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " g-a-s='" << google_accounts_signin_value << "'"
<< " g-c-s='" << google_chrome_signin_value << "'";
}
if (!gaia::IsGaiaSignonRealm(request->original_url().GetOrigin()))
return;
std::vector<std::pair<std::string, std::string> > pairs;
base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',',
&pairs);
std::string session_index;
std::string email;
for (size_t i = 0; i < pairs.size(); ++i) {
const std::pair<std::string, std::string>& pair = pairs[i];
const std::string& key = pair.first;
const std::string& value = pair.second;
if (key == "email") {
TrimString(value, "\"", &email);
} else if (key == "sessionindex") {
session_index = value;
}
}
if (!email.empty())
io_data->set_reverse_autologin_pending_email(email);
if (!email.empty() || !session_index.empty()) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " email=" << email
<< " sessionindex=" << session_index;
}
AutoAccept auto_accept = AUTO_ACCEPT_NONE;
signin::Source source = signin::SOURCE_UNKNOWN;
GURL continue_url;
std::vector<std::string> tokens;
base::SplitString(google_chrome_signin_value, ',', &tokens);
for (size_t i = 0; i < tokens.size(); ++i) {
const std::string& token = tokens[i];
if (token == "accepted") {
auto_accept = AUTO_ACCEPT_ACCEPTED;
} else if (token == "configure") {
auto_accept = AUTO_ACCEPT_CONFIGURE;
} else if (token == "rejected-for-profile") {
auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE;
}
}
source = GetSigninSource(request->url(), &continue_url);
if (source != signin::SOURCE_UNKNOWN)
auto_accept = AUTO_ACCEPT_EXPLICIT;
if (auto_accept != AUTO_ACCEPT_NONE) {
VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
<< " auto_accept=" << auto_accept;
}
if (session_index.empty() && email.empty() &&
auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) {
return;
}
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index,
email, auto_accept, source, continue_url, child_id, route_id));
}
Vulnerability Type:
CWE ID: CWE-287
Summary: The OneClickSigninHelper::ShowInfoBarIfPossible function in browser/ui/sync/one_click_signin_helper.cc in Google Chrome before 31.0.1650.63 uses an incorrect URL during realm validation, which allows remote attackers to conduct session fixation attacks and hijack web sessions by triggering improper sync after a 302 (aka Found) HTTP status code.
Commit Message: During redirects in the one click sign in flow, check the current URL
instead of original URL to validate gaia http headers.
BUG=307159
Review URL: https://codereview.chromium.org/77343002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@236563 0039d316-1c4b-4281-b951-d872f2087c98
|
Medium
| 171,136
|
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 ImageResource::IsAccessAllowed(
const SecurityOrigin* security_origin,
ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin
does_current_frame_has_single_security_origin) const {
if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque)
return false;
if (does_current_frame_has_single_security_origin !=
ImageResourceInfo::kHasSingleSecurityOrigin)
return false;
if (IsSameOriginOrCORSSuccessful())
return true;
return !security_origin->TaintsCanvas(GetResponse().Url());
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Lack of CORS checking by ResourceFetcher/ResourceLoader in Blink in Google Chrome prior to 65.0.3325.146 allowed a remote attacker to leak cross-origin data via a crafted HTML page.
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <hiroshige@chromium.org>
Reviewed-by: Kouhei Ueno <kouhei@chromium.org>
Reviewed-by: Yutaka Hirano <yhirano@chromium.org>
Reviewed-by: Takeshi Yoshino <tyoshino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#535176}
|
Medium
| 172,888
|
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 encrypted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct encrypted_key_payload *epayload = key->payload.data[0];
struct encrypted_key_payload *new_epayload;
char *buf;
char *new_master_desc = NULL;
const char *format = NULL;
size_t datalen = prep->datalen;
int ret = 0;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
return -ENOKEY;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
buf = kmalloc(datalen + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[datalen] = 0;
memcpy(buf, prep->data, datalen);
ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
if (ret < 0)
goto out;
ret = valid_master_desc(new_master_desc, epayload->master_desc);
if (ret < 0)
goto out;
new_epayload = encrypted_key_alloc(key, epayload->format,
new_master_desc, epayload->datalen);
if (IS_ERR(new_epayload)) {
ret = PTR_ERR(new_epayload);
goto out;
}
__ekey_init(new_epayload, epayload->format, new_master_desc,
epayload->datalen);
memcpy(new_epayload->iv, epayload->iv, ivsize);
memcpy(new_epayload->payload_data, epayload->payload_data,
epayload->payload_datalen);
rcu_assign_keypointer(key, new_epayload);
call_rcu(&epayload->rcu, encrypted_rcu_free);
out:
kzfree(buf);
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The KEYS subsystem in the Linux kernel before 4.13.10 does not correctly synchronize the actions of updating versus finding a key in the *negative* state to avoid a race condition, which allows local users to cause a denial of service or possibly have unspecified other impact via crafted system calls.
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: stable@vger.kernel.org # v4.4+
Reported-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Reviewed-by: Eric Biggers <ebiggers@google.com>
|
Low
| 167,694
|
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: char *X509_NAME_oneline(X509_NAME *a, char *buf, int len)
{
X509_NAME_ENTRY *ne;
int i;
int n, lold, l, l1, l2, num, j, type;
const char *s;
char *p;
unsigned char *q;
BUF_MEM *b = NULL;
static const char hex[17] = "0123456789ABCDEF";
int gs_doit[4];
char tmp_buf[80];
#ifdef CHARSET_EBCDIC
char ebcdic_buf[1024];
#endif
if (buf == NULL) {
if ((b = BUF_MEM_new()) == NULL)
goto err;
if (!BUF_MEM_grow(b, 200))
goto err;
b->data[0] = '\0';
len = 200;
} else if (len == 0) {
return NULL;
}
if (a == NULL) {
if (b) {
buf = b->data;
OPENSSL_free(b);
}
strncpy(buf, "NO X509_NAME", len);
buf[len - 1] = '\0';
return buf;
}
len--; /* space for '\0' */
l = 0;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
ne = sk_X509_NAME_ENTRY_value(a->entries, i);
n = OBJ_obj2nid(ne->object);
if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object);
s = tmp_buf;
}
l1 = strlen(s);
type = ne->value->type;
num = ne->value->length;
if (num > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
q = ne->value->data;
#ifdef CHARSET_EBCDIC
if (type == V_ASN1_GENERALSTRING ||
type == V_ASN1_VISIBLESTRING ||
type == V_ASN1_PRINTABLESTRING ||
type == V_ASN1_TELETEXSTRING ||
type == V_ASN1_VISIBLESTRING || type == V_ASN1_IA5STRING) {
ascii2ebcdic(ebcdic_buf, q, (num > sizeof ebcdic_buf)
? sizeof ebcdic_buf : num);
q = ebcdic_buf;
}
#endif
if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) {
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0;
for (j = 0; j < num; j++)
if (q[j] != 0)
gs_doit[j & 3] = 1;
if (gs_doit[0] | gs_doit[1] | gs_doit[2])
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
else {
gs_doit[0] = gs_doit[1] = gs_doit[2] = 0;
gs_doit[3] = 1;
}
} else
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
for (l2 = j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
l2++;
#ifndef CHARSET_EBCDIC
if ((q[j] < ' ') || (q[j] > '~'))
l2 += 3;
#else
if ((os_toascii[q[j]] < os_toascii[' ']) ||
(os_toascii[q[j]] > os_toascii['~']))
l2 += 3;
#endif
}
lold = l;
l += 1 + l1 + 1 + l2;
if (l > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
if (b != NULL) {
if (!BUF_MEM_grow(b, l + 1))
goto err;
p = &(b->data[lold]);
} else if (l > len) {
break;
} else
p = &(buf[lold]);
*(p++) = '/';
memcpy(p, s, (unsigned int)l1);
p += l1;
*(p++) = '=';
#ifndef CHARSET_EBCDIC /* q was assigned above already. */
q = ne->value->data;
#endif
for (j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
#ifndef CHARSET_EBCDIC
n = q[j];
if ((n < ' ') || (n > '~')) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = n;
#else
n = os_toascii[q[j]];
if ((n < os_toascii[' ']) || (n > os_toascii['~'])) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = q[j];
#endif
}
*p = '\0';
}
if (b != NULL) {
p = b->data;
OPENSSL_free(b);
} else
p = buf;
if (i == 0)
*p = '\0';
return (p);
err:
X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE);
end:
BUF_MEM_free(b);
return (NULL);
}
Vulnerability Type: DoS Overflow +Info
CWE ID: CWE-119
Summary: The X509_NAME_oneline function in crypto/x509/x509_obj.c in OpenSSL before 1.0.1t and 1.0.2 before 1.0.2h allows remote attackers to obtain sensitive information from process stack memory or cause a denial of service (buffer over-read) via crafted EBCDIC ASN.1 data.
Commit Message:
|
Low
| 165,207
|
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 TabContentsContainerGtk::DetachTab(TabContents* tab) {
gfx::NativeView widget = tab->web_contents()->GetNativeView();
if (widget) {
GtkWidget* parent = gtk_widget_get_parent(widget);
if (parent) {
DCHECK_EQ(parent, expanded_);
gtk_container_remove(GTK_CONTAINER(expanded_), widget);
}
}
}
Vulnerability Type:
CWE ID: CWE-20
Summary: The hyphenation functionality in Google Chrome before 24.0.1312.52 does not properly validate file names, which has unspecified impact and attack vectors.
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 171,515
|
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 SoftVPXEncoder::onQueueFilled(OMX_U32 portIndex) {
if (mCodecContext == NULL) {
if (OK != initEncoder()) {
ALOGE("Failed to initialize encoder");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
}
vpx_codec_err_t codec_return;
List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex);
while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) {
BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader;
BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader;
if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
inputBufferInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inputBufferHeader);
outputBufferHeader->nFilledLen = 0;
outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
outputBufferInfo->mOwnedByUs = false;
notifyFillBufferDone(outputBufferHeader);
return;
}
const uint8_t *source =
inputBufferHeader->pBuffer + inputBufferHeader->nOffset;
size_t frameSize = mWidth * mHeight * 3 / 2;
if (mInputDataIsMeta) {
source = extractGraphicBuffer(
mConversionBuffer, frameSize,
source, inputBufferHeader->nFilledLen,
mWidth, mHeight);
if (source == NULL) {
ALOGE("Unable to extract gralloc buffer in metadata mode");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
} else {
if (inputBufferHeader->nFilledLen < frameSize) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
} else if (inputBufferHeader->nFilledLen > frameSize) {
ALOGW("Input buffer contains too many pixels");
}
if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) {
ConvertYUV420SemiPlanarToYUV420Planar(
source, mConversionBuffer, mWidth, mHeight);
source = mConversionBuffer;
}
}
vpx_image_t raw_frame;
vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight,
kInputBufferAlignment, (uint8_t *)source);
vpx_enc_frame_flags_t flags = 0;
if (mTemporalPatternLength > 0) {
flags = getEncodeFlags();
}
if (mKeyFrameRequested) {
flags |= VPX_EFLAG_FORCE_KF;
mKeyFrameRequested = false;
}
if (mBitrateUpdated) {
mCodecConfiguration->rc_target_bitrate = mBitrate/1000;
vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext,
mCodecConfiguration);
if (res != VPX_CODEC_OK) {
ALOGE("vp8 encoder failed to update bitrate: %s",
vpx_codec_err_to_string(res));
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
}
mBitrateUpdated = false;
}
uint32_t frameDuration;
if (inputBufferHeader->nTimeStamp > mLastTimestamp) {
frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp);
} else {
frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate);
}
mLastTimestamp = inputBufferHeader->nTimeStamp;
codec_return = vpx_codec_encode(
mCodecContext,
&raw_frame,
inputBufferHeader->nTimeStamp, // in timebase units
frameDuration, // frame duration in timebase units
flags, // frame flags
VPX_DL_REALTIME); // encoding deadline
if (codec_return != VPX_CODEC_OK) {
ALOGE("vpx encoder failed to encode frame");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
vpx_codec_iter_t encoded_packet_iterator = NULL;
const vpx_codec_cx_pkt_t* encoded_packet;
while ((encoded_packet = vpx_codec_get_cx_data(
mCodecContext, &encoded_packet_iterator))) {
if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) {
outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts;
outputBufferHeader->nFlags = 0;
if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY)
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME;
outputBufferHeader->nOffset = 0;
outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz;
if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
memcpy(outputBufferHeader->pBuffer,
encoded_packet->data.frame.buf,
encoded_packet->data.frame.sz);
outputBufferInfo->mOwnedByUs = false;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
notifyFillBufferDone(outputBufferHeader);
}
}
inputBufferInfo->mOwnedByUs = false;
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
notifyEmptyBufferDone(inputBufferHeader);
}
}
Vulnerability Type: Exec Code +Priv
CWE ID:
Summary: An elevation of privilege vulnerability in libstagefright in Mediaserver could enable a local malicious application to execute arbitrary code within the context of a privileged process. This issue is rated as High because it could be used to gain local access to elevated capabilities, which are not normally accessible to a third-party application. Product: Android. Versions: 4.4.4, 5.0.2, 5.1.1, 6.0, 6.0.1, 7.0, 7.1.1. Android ID: A-34749392.
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
|
Medium
| 174,012
|
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: gimp_write_and_read_file (Gimp *gimp,
gboolean with_unusual_stuff,
gboolean compat_paths,
gboolean use_gimp_2_8_features)
{
GimpImage *image;
GimpImage *loaded_image;
GimpPlugInProcedure *proc;
gchar *filename;
GFile *file;
/* Create the image */
image = gimp_create_mainimage (gimp,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Assert valid state */
gimp_assert_mainimage (image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Write to file */
filename = g_build_filename (g_get_tmp_dir (), "gimp-test.xcf", NULL);
file = g_file_new_for_path (filename);
g_free (filename);
proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager,
GIMP_FILE_PROCEDURE_GROUP_SAVE,
file,
NULL /*error*/);
file_save (gimp,
image,
NULL /*progress*/,
file,
proc,
GIMP_RUN_NONINTERACTIVE,
FALSE /*change_saved_state*/,
FALSE /*export_backward*/,
FALSE /*export_forward*/,
NULL /*error*/);
/* Load from file */
loaded_image = gimp_test_load_image (image->gimp, file);
/* Assert on the loaded file. If success, it means that there is no
* significant information loss when we wrote the image to a file
* and loaded it again
*/
gimp_assert_mainimage (loaded_image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
g_file_delete (file, NULL, NULL);
g_object_unref (file);
}
Vulnerability Type:
CWE ID: CWE-20
Summary: GIMP through 2.10.2 makes g_get_tmp_dir calls to establish temporary filenames, which may result in a filename that already exists, as demonstrated by the gimp_write_and_read_file function in app/tests/test-xcf.c. This might be leveraged by attackers to overwrite files or read file content that was intended to be private.
Commit Message: Issue #1689: create unique temporary file with g_file_open_tmp().
Not sure this is really solving the issue reported, which is that
`g_get_tmp_dir()` uses environment variables (yet as g_file_open_tmp()
uses g_get_tmp_dir()…). But at least g_file_open_tmp() should create
unique temporary files, which prevents overriding existing files (which
is most likely the only real attack possible here, or at least the only
one I can think of unless some weird vulnerabilities exist in glib).
|
Low
| 169,187
|
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 v8::Handle<v8::Value> excitingFunctionCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestActiveDOMObject.excitingFunction");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder());
if (!V8BindingSecurity::canAccessFrame(V8BindingState::Only(), imp->frame(), true))
return v8::Handle<v8::Value>();
EXCEPTION_BLOCK(Node*, nextChild, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->excitingFunction(nextChild);
return v8::Handle<v8::Value>();
}
Vulnerability Type:
CWE ID:
Summary: The browser native UI in Google Chrome before 17.0.963.83 does not require user confirmation before an unpacked extension installation, which allows user-assisted remote attackers to have an unspecified impact via a crafted extension.
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
Medium
| 171,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 void nfs4_open_confirm_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (!data->rpc_done)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.open_flags);
out_free:
nfs4_opendata_put(data);
}
Vulnerability Type: DoS
CWE ID:
Summary: The encode_share_access function in fs/nfs/nfs4xdr.c in the Linux kernel before 2.6.29 allows local users to cause a denial of service (BUG and system crash) by using the mknod system call with a pathname on an NFSv4 filesystem.
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
|
Low
| 165,694
|
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: WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog(
WebContents* initiator) {
base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true);
ConstrainedWebDialogDelegate* web_dialog_delegate =
ShowConstrainedWebDialog(initiator->GetBrowserContext(),
new PrintPreviewDialogDelegate(initiator),
initiator);
WebContents* preview_dialog = web_dialog_delegate->GetWebContents();
GURL print_url(chrome::kChromeUIPrintURL);
content::HostZoomMap::Get(preview_dialog->GetSiteInstance())
->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0);
PrintViewManager::CreateForWebContents(preview_dialog);
extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
preview_dialog);
preview_dialog_map_[preview_dialog] = initiator;
waiting_for_new_preview_page_ = true;
task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog);
AddObservers(initiator);
AddObservers(preview_dialog);
return preview_dialog;
}
Vulnerability Type: +Info
CWE ID: CWE-254
Summary: The FrameFetchContext::updateTimingInfoForIFrameNavigation function in core/loader/FrameFetchContext.cpp in Blink, as used in Google Chrome before 45.0.2454.85, does not properly restrict the availability of IFRAME Resource Timing API times, which allows remote attackers to obtain sensitive information via crafted JavaScript code that leverages a history.back call.
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
TBR=jzfeng@chromium.org
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <weili@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Cr-Commit-Position: refs/heads/master@{#511616}
|
Low
| 171,887
|
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 assoc_array_gc(struct assoc_array *array,
const struct assoc_array_ops *ops,
bool (*iterator)(void *object, void *iterator_data),
void *iterator_data)
{
struct assoc_array_shortcut *shortcut, *new_s;
struct assoc_array_node *node, *new_n;
struct assoc_array_edit *edit;
struct assoc_array_ptr *cursor, *ptr;
struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
unsigned long nr_leaves_on_tree;
int keylen, slot, nr_free, next_slot, i;
pr_devel("-->%s()\n", __func__);
if (!array->root)
return 0;
edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
if (!edit)
return -ENOMEM;
edit->array = array;
edit->ops = ops;
edit->ops_for_excised_subtree = ops;
edit->set[0].ptr = &array->root;
edit->excised_subtree = array->root;
new_root = new_parent = NULL;
new_ptr_pp = &new_root;
cursor = array->root;
descend:
/* If this point is a shortcut, then we need to duplicate it and
* advance the target cursor.
*/
if (assoc_array_ptr_is_shortcut(cursor)) {
shortcut = assoc_array_ptr_to_shortcut(cursor);
keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s = kmalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s)
goto enomem;
pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
memcpy(new_s, shortcut, (sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long)));
new_s->back_pointer = new_parent;
new_s->parent_slot = shortcut->parent_slot;
*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
new_ptr_pp = &new_s->next_node;
cursor = shortcut->next_node;
}
/* Duplicate the node at this position */
node = assoc_array_ptr_to_node(cursor);
new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n)
goto enomem;
pr_devel("dup node %p -> %p\n", node, new_n);
new_n->back_pointer = new_parent;
new_n->parent_slot = node->parent_slot;
*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
new_ptr_pp = NULL;
slot = 0;
continue_node:
/* Filter across any leaves and gc any subtrees */
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = node->slots[slot];
if (!ptr)
continue;
if (assoc_array_ptr_is_leaf(ptr)) {
if (iterator(assoc_array_ptr_to_leaf(ptr),
iterator_data))
/* The iterator will have done any reference
* counting on the object for us.
*/
new_n->slots[slot] = ptr;
continue;
}
new_ptr_pp = &new_n->slots[slot];
cursor = ptr;
goto descend;
}
pr_devel("-- compress node %p --\n", new_n);
/* Count up the number of empty slots in this node and work out the
* subtree leaf count.
*/
new_n->nr_leaves_on_branch = 0;
nr_free = 0;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = new_n->slots[slot];
if (!ptr)
nr_free++;
else if (assoc_array_ptr_is_leaf(ptr))
new_n->nr_leaves_on_branch++;
}
pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
/* See what we can fold in */
next_slot = 0;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
struct assoc_array_shortcut *s;
struct assoc_array_node *child;
ptr = new_n->slots[slot];
if (!ptr || assoc_array_ptr_is_leaf(ptr))
continue;
s = NULL;
if (assoc_array_ptr_is_shortcut(ptr)) {
s = assoc_array_ptr_to_shortcut(ptr);
ptr = s->next_node;
}
child = assoc_array_ptr_to_node(ptr);
new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
if (child->nr_leaves_on_branch <= nr_free + 1) {
/* Fold the child node into this one */
pr_devel("[%d] fold node %lu/%d [nx %d]\n",
slot, child->nr_leaves_on_branch, nr_free + 1,
next_slot);
/* We would already have reaped an intervening shortcut
* on the way back up the tree.
*/
BUG_ON(s);
new_n->slots[slot] = NULL;
nr_free++;
if (slot < next_slot)
next_slot = slot;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
struct assoc_array_ptr *p = child->slots[i];
if (!p)
continue;
BUG_ON(assoc_array_ptr_is_meta(p));
while (new_n->slots[next_slot])
next_slot++;
BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
new_n->slots[next_slot++] = p;
nr_free--;
}
kfree(child);
} else {
pr_devel("[%d] retain node %lu/%d [nx %d]\n",
slot, child->nr_leaves_on_branch, nr_free + 1,
next_slot);
}
}
pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
nr_leaves_on_tree = new_n->nr_leaves_on_branch;
/* Excise this node if it is singly occupied by a shortcut */
if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
if ((ptr = new_n->slots[slot]))
break;
if (assoc_array_ptr_is_meta(ptr) &&
assoc_array_ptr_is_shortcut(ptr)) {
pr_devel("excise node %p with 1 shortcut\n", new_n);
new_s = assoc_array_ptr_to_shortcut(ptr);
new_parent = new_n->back_pointer;
slot = new_n->parent_slot;
kfree(new_n);
if (!new_parent) {
new_s->back_pointer = NULL;
new_s->parent_slot = 0;
new_root = ptr;
goto gc_complete;
}
if (assoc_array_ptr_is_shortcut(new_parent)) {
/* We can discard any preceding shortcut also */
struct assoc_array_shortcut *s =
assoc_array_ptr_to_shortcut(new_parent);
pr_devel("excise preceding shortcut\n");
new_parent = new_s->back_pointer = s->back_pointer;
slot = new_s->parent_slot = s->parent_slot;
kfree(s);
if (!new_parent) {
new_s->back_pointer = NULL;
new_s->parent_slot = 0;
new_root = ptr;
goto gc_complete;
}
}
new_s->back_pointer = new_parent;
new_s->parent_slot = slot;
new_n = assoc_array_ptr_to_node(new_parent);
new_n->slots[slot] = ptr;
goto ascend_old_tree;
}
}
/* Excise any shortcuts we might encounter that point to nodes that
* only contain leaves.
*/
ptr = new_n->back_pointer;
if (!ptr)
goto gc_complete;
if (assoc_array_ptr_is_shortcut(ptr)) {
new_s = assoc_array_ptr_to_shortcut(ptr);
new_parent = new_s->back_pointer;
slot = new_s->parent_slot;
if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
struct assoc_array_node *n;
pr_devel("excise shortcut\n");
new_n->back_pointer = new_parent;
new_n->parent_slot = slot;
kfree(new_s);
if (!new_parent) {
new_root = assoc_array_node_to_ptr(new_n);
goto gc_complete;
}
n = assoc_array_ptr_to_node(new_parent);
n->slots[slot] = assoc_array_node_to_ptr(new_n);
}
} else {
new_parent = ptr;
}
new_n = assoc_array_ptr_to_node(new_parent);
ascend_old_tree:
ptr = node->back_pointer;
if (assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
slot = shortcut->parent_slot;
cursor = shortcut->back_pointer;
} else {
slot = node->parent_slot;
cursor = ptr;
}
BUG_ON(!ptr);
node = assoc_array_ptr_to_node(cursor);
slot++;
goto continue_node;
gc_complete:
edit->set[0].to = new_root;
assoc_array_apply_edit(edit);
array->nr_leaves_on_tree = nr_leaves_on_tree;
return 0;
enomem:
pr_devel("enomem\n");
assoc_array_destroy_subtree(new_root, edit->ops);
kfree(edit);
return -ENOMEM;
}
Vulnerability Type: DoS
CWE ID:
Summary: The assoc_array_gc function in the associative-array implementation in lib/assoc_array.c in the Linux kernel before 3.16.3 does not properly implement garbage collection, which allows local users to cause a denial of service (NULL pointer dereference and system crash) or possibly have unspecified other impact via multiple *keyctl newring* operations followed by a *keyctl timeout* operation.
Commit Message: KEYS: Fix termination condition in assoc array garbage collection
This fixes CVE-2014-3631.
It is possible for an associative array to end up with a shortcut node at the
root of the tree if there are more than fan-out leaves in the tree, but they
all crowd into the same slot in the lowest level (ie. they all have the same
first nibble of their index keys).
When assoc_array_gc() returns back up the tree after scanning some leaves, it
can fall off of the root and crash because it assumes that the back pointer
from a shortcut (after label ascend_old_tree) must point to a normal node -
which isn't true of a shortcut node at the root.
Should we find we're ascending rootwards over a shortcut, we should check to
see if the backpointer is zero - and if it is, we have completed the scan.
This particular bug cannot occur if the root node is not a shortcut - ie. if
you have fewer than 17 keys in a keyring or if you have at least two keys that
sit into separate slots (eg. a keyring and a non keyring).
This can be reproduced by:
ring=`keyctl newring bar @s`
for ((i=1; i<=18; i++)); do last_key=`keyctl newring foo$i $ring`; done
keyctl timeout $last_key 2
Doing this:
echo 3 >/proc/sys/kernel/keys/gc_delay
first will speed things up.
If we do fall off of the top of the tree, we get the following oops:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000018
IP: [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540
PGD dae15067 PUD cfc24067 PMD 0
Oops: 0000 [#1] SMP
Modules linked in: xt_nat xt_mark nf_conntrack_netbios_ns nf_conntrack_broadcast ip6t_rpfilter ip6t_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_ni
CPU: 0 PID: 26011 Comm: kworker/0:1 Not tainted 3.14.9-200.fc20.x86_64 #1
Hardware name: Bochs Bochs, BIOS Bochs 01/01/2011
Workqueue: events key_garbage_collector
task: ffff8800918bd580 ti: ffff8800aac14000 task.ti: ffff8800aac14000
RIP: 0010:[<ffffffff8136cea7>] [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540
RSP: 0018:ffff8800aac15d40 EFLAGS: 00010206
RAX: 0000000000000000 RBX: 0000000000000000 RCX: ffff8800aaecacc0
RDX: ffff8800daecf440 RSI: 0000000000000001 RDI: ffff8800aadc2bc0
RBP: ffff8800aac15da8 R08: 0000000000000001 R09: 0000000000000003
R10: ffffffff8136ccc7 R11: 0000000000000000 R12: 0000000000000000
R13: 0000000000000000 R14: 0000000000000070 R15: 0000000000000001
FS: 0000000000000000(0000) GS:ffff88011fc00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 0000000000000018 CR3: 00000000db10d000 CR4: 00000000000006f0
Stack:
ffff8800aac15d50 0000000000000011 ffff8800aac15db8 ffffffff812e2a70
ffff880091a00600 0000000000000000 ffff8800aadc2bc3 00000000cd42c987
ffff88003702df20 ffff88003702dfa0 0000000053b65c09 ffff8800aac15fd8
Call Trace:
[<ffffffff812e2a70>] ? keyring_detect_cycle_iterator+0x30/0x30
[<ffffffff812e3e75>] keyring_gc+0x75/0x80
[<ffffffff812e1424>] key_garbage_collector+0x154/0x3c0
[<ffffffff810a67b6>] process_one_work+0x176/0x430
[<ffffffff810a744b>] worker_thread+0x11b/0x3a0
[<ffffffff810a7330>] ? rescuer_thread+0x3b0/0x3b0
[<ffffffff810ae1a8>] kthread+0xd8/0xf0
[<ffffffff810ae0d0>] ? insert_kthread_work+0x40/0x40
[<ffffffff816ffb7c>] ret_from_fork+0x7c/0xb0
[<ffffffff810ae0d0>] ? insert_kthread_work+0x40/0x40
Code: 08 4c 8b 22 0f 84 bf 00 00 00 41 83 c7 01 49 83 e4 fc 41 83 ff 0f 4c 89 65 c0 0f 8f 5a fe ff ff 48 8b 45 c0 4d 63 cf 49 83 c1 02 <4e> 8b 34 c8 4d 85 f6 0f 84 be 00 00 00 41 f6 c6 01 0f 84 92
RIP [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540
RSP <ffff8800aac15d40>
CR2: 0000000000000018
---[ end trace 1129028a088c0cbd ]---
Signed-off-by: David Howells <dhowells@redhat.com>
Acked-by: Don Zickus <dzickus@redhat.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>
|
Low
| 166,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: image_transform_png_set_expand_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
* depth is at least 8 already.
*/
return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
}
Vulnerability Type: +Priv
CWE ID:
Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085.
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
|
Low
| 173,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: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
: AbstractMetadataProvider(e),
m_validate(XMLHelper::getAttrBool(e, false, validate)),
m_id(XMLHelper::getAttrString(e, "Dynamic", id)),
m_lock(RWLock::create()),
m_refreshDelayFactor(0.75),
m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)),
m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration)),
m_shutdown(false),
m_cleanupInterval(XMLHelper::getAttrInt(e, 1800, cleanupInterval)),
m_cleanupTimeout(XMLHelper::getAttrInt(e, 1800, cleanupTimeout)),
m_cleanup_wait(nullptr), m_cleanup_thread(nullptr)
{
if (m_minCacheDuration > m_maxCacheDuration) {
Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
"minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it"
);
m_minCacheDuration = m_maxCacheDuration;
}
const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr;
if (delay && *delay) {
auto_ptr_char temp(delay);
m_refreshDelayFactor = atof(temp.get());
if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
"invalid refreshDelayFactor setting, using default"
);
m_refreshDelayFactor = 0.75;
}
}
if (m_cleanupInterval > 0) {
if (m_cleanupTimeout < 0)
m_cleanupTimeout = 0;
m_cleanup_wait = CondWait::create();
m_cleanup_thread = Thread::create(&cleanup_fn, this);
}
}
Vulnerability Type:
CWE ID: CWE-347
Summary: The DynamicMetadataProvider class in saml/saml2/metadata/impl/DynamicMetadataProvider.cpp in OpenSAML-C in OpenSAML before 2.6.1 fails to properly configure itself with the MetadataFilter plugins and does not perform critical security checks such as signature verification, enforcement of validity periods, and other checks specific to deployments, aka CPPOST-105.
Commit Message:
|
Medium
| 164,622
|
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_METHOD(Phar, createDefaultStub)
{
char *index = NULL, *webindex = NULL, *error;
zend_string *stub;
size_t index_len = 0, webindex_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
return;
}
stub = phar_create_default_stub(index, webindex, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
return;
}
RETURN_NEW_STR(stub);
}
Vulnerability Type: Exec Code
CWE ID: CWE-20
Summary: The Phar extension in PHP before 5.5.34, 5.6.x before 5.6.20, and 7.x before 7.0.5 allows remote attackers to execute arbitrary code via a crafted filename, as demonstrated by mishandling of \0 characters by the phar_analyze_path function in ext/phar/phar.c.
Commit Message:
|
Low
| 165,057
|
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: AudioTrack::AudioTrack(
Segment* pSegment,
long long element_start,
long long element_size) :
Track(pSegment, element_start, element_size)
{
}
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,239
|
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 NavigationControllerImpl::RendererDidNavigate(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
LoadCommittedDetails* details,
bool is_navigation_within_page,
NavigationHandleImpl* navigation_handle) {
is_initial_navigation_ = false;
bool overriding_user_agent_changed = false;
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->GetURL();
details->previous_entry_index = GetLastCommittedEntryIndex();
if (pending_entry_ &&
pending_entry_->GetIsOverridingUserAgent() !=
GetLastCommittedEntry()->GetIsOverridingUserAgent())
overriding_user_agent_changed = true;
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
bool was_restored = false;
DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
pending_entry_->restore_type() != RestoreType::NONE);
if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) {
pending_entry_->set_restore_type(RestoreType::NONE);
was_restored = true;
}
details->did_replace_entry = params.should_replace_current_entry;
details->type = ClassifyNavigation(rfh, params);
details->is_same_document = is_navigation_within_page;
if (PendingEntryMatchesHandle(navigation_handle)) {
if (pending_entry_->reload_type() != ReloadType::NONE) {
last_committed_reload_type_ = pending_entry_->reload_type();
last_committed_reload_time_ =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
} else if (!pending_entry_->is_renderer_initiated() ||
params.gesture == NavigationGestureUser) {
last_committed_reload_type_ = ReloadType::NONE;
last_committed_reload_time_ = base::Time();
}
}
switch (details->type) {
case NAVIGATION_TYPE_NEW_PAGE:
RendererDidNavigateToNewPage(rfh, params, details->is_same_document,
details->did_replace_entry,
navigation_handle);
break;
case NAVIGATION_TYPE_EXISTING_PAGE:
details->did_replace_entry = details->is_same_document;
RendererDidNavigateToExistingPage(rfh, params, details->is_same_document,
was_restored, navigation_handle);
break;
case NAVIGATION_TYPE_SAME_PAGE:
RendererDidNavigateToSamePage(rfh, params, navigation_handle);
break;
case NAVIGATION_TYPE_NEW_SUBFRAME:
RendererDidNavigateNewSubframe(rfh, params, details->is_same_document,
details->did_replace_entry);
break;
case NAVIGATION_TYPE_AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(rfh, params)) {
NotifyEntryChanged(GetLastCommittedEntry());
return false;
}
break;
case NAVIGATION_TYPE_NAV_IGNORE:
if (pending_entry_) {
DiscardNonCommittedEntries();
delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
return false;
default:
NOTREACHED();
}
base::Time timestamp =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DVLOG(1) << "Navigation finished at (smoothed) timestamp "
<< timestamp.ToInternalValue();
DiscardNonCommittedEntriesInternal();
DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
NavigationEntryImpl* active_entry = GetLastCommittedEntry();
active_entry->SetTimestamp(timestamp);
active_entry->SetHttpStatusCode(params.http_status_code);
FrameNavigationEntry* frame_entry =
active_entry->GetFrameEntry(rfh->frame_tree_node());
if (frame_entry) {
frame_entry->SetPageState(params.page_state);
frame_entry->set_redirect_chain(params.redirects);
}
if (!rfh->GetParent() &&
IsBlockedNavigation(navigation_handle->GetNetErrorCode())) {
DCHECK(params.url_is_unreachable);
active_entry->SetURL(GURL(url::kAboutBlankURL));
active_entry->SetVirtualURL(params.url);
if (frame_entry) {
frame_entry->SetPageState(
PageState::CreateFromURL(active_entry->GetURL()));
}
}
size_t redirect_chain_size = 0;
for (size_t i = 0; i < params.redirects.size(); ++i) {
redirect_chain_size += params.redirects[i].spec().length();
}
UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
active_entry->ResetForCommit(frame_entry);
if (!rfh->GetParent())
CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
active_entry->SetBindings(rfh->GetEnabledBindings());
details->entry = active_entry;
details->is_main_frame = !rfh->GetParent();
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details);
if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
navigation_handle->GetNetErrorCode() == net::OK) {
UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus",
!!active_entry->GetSSL().certificate);
}
if (overriding_user_agent_changed)
delegate_->UpdateOverridingUserAgent();
int nav_entry_id = active_entry->GetUniqueID();
for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes())
node->current_frame_host()->set_nav_entry_id(nav_entry_id);
return true;
}
Vulnerability Type:
CWE ID:
Summary: Using an ID that can be controlled by a compromised renderer which allows any frame to overwrite the page_state of any other frame in the same process in Navigation in Google Chrome on Chrome OS prior to 62.0.3202.74 allowed a remote attacker who had compromised the renderer process to potentially perform a sandbox escape via a crafted HTML page.
Commit Message: Don't update PageState for a SiteInstance mismatch.
BUG=766262
TEST=See bug for repro.
Change-Id: Ifb087b687acd40d8963ef436c9ea82ca2d960117
Reviewed-on: https://chromium-review.googlesource.com/674808
Commit-Queue: Charlie Reis (OOO until 9/25) <creis@chromium.org>
Reviewed-by: Łukasz Anforowicz <lukasza@chromium.org>
Cr-Commit-Position: refs/heads/master@{#503297}
|
???
| 173,259
|
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: xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
return (1);
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The NFS parser in tcpdump before 4.9.2 has a buffer over-read in print-nfs.c:xid_map_enter().
Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
|
Low
| 167,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: int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
{
unsigned short type;
unsigned short size;
unsigned short len;
unsigned char *data = *p;
int renegotiate_seen = 0;
int sigalg_seen = 0;
s->servername_done = 0;
s->tlsext_status_type = -1;
#ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
#endif
#ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
#endif
#ifndef OPENSSL_NO_EC
if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
ssl_check_for_safari(s, data, d, n);
#endif /* !OPENSSL_NO_EC */
if (data >= (d+n-2))
goto ri_check;
n2s(data,len);
if (data > (d+n-len))
goto ri_check;
while (data <= (d+n-4))
{
n2s(data,type);
n2s(data,size);
if (data+size > (d+n))
goto ri_check;
#if 0
fprintf(stderr,"Received extension type %d size %d\n",type,size);
#endif
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 0, type, data, size,
s->tlsext_debug_arg);
/* The servername extension is treated as follows:
- Only the hostname type is supported with a maximum length of 255.
- The servername is rejected if too long or if it contains zeros,
in which case an fatal alert is generated.
- The servername field is maintained together with the session cache.
- When a session is resumed, the servername call back invoked in order
to allow the application to position itself to the right context.
- The servername is acknowledged if it is new for a session or when
it is identical to a previously used for the same session.
Applications can control the behaviour. They can at any time
set a 'desirable' servername for a new SSL object. This can be the
case for example with HTTPS when a Host: header field is received and
a renegotiation is requested. In this case, a possible servername
presented in the new client hello is only acknowledged if it matches
the value of the Host: field.
- Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
if they provide for changing an explicit servername context for the session,
i.e. when the session has been established with a servername extension.
- On session reconnect, the servername extension may be absent.
*/
if (type == TLSEXT_TYPE_server_name)
{
unsigned char *sdata;
int servname_type;
int dsize;
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(data,dsize);
size -= 2;
if (dsize > size )
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sdata = data;
while (dsize > 3)
{
servname_type = *(sdata++);
n2s(sdata,len);
dsize -= 3;
if (len > dsize)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->servername_done == 0)
switch (servname_type)
{
case TLSEXT_NAMETYPE_host_name:
if (!s->hit)
{
if(s->session->tlsext_hostname)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (len > TLSEXT_MAXLEN_host_name)
{
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->session->tlsext_hostname, sdata, len);
s->session->tlsext_hostname[len]='\0';
if (strlen(s->session->tlsext_hostname) != len) {
OPENSSL_free(s->session->tlsext_hostname);
s->session->tlsext_hostname = NULL;
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
s->servername_done = 1;
}
else
s->servername_done = s->session->tlsext_hostname
&& strlen(s->session->tlsext_hostname) == len
&& strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
break;
default:
break;
}
dsize -= len;
}
if (dsize != 0)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
#ifndef OPENSSL_NO_SRP
else if (type == TLSEXT_TYPE_srp)
{
if (size <= 0 || ((len = data[0])) != (size -1))
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->srp_ctx.login != NULL)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
return -1;
memcpy(s->srp_ctx.login, &data[1], len);
s->srp_ctx.login[len]='\0';
if (strlen(s->srp_ctx.login) != len)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats)
{
unsigned char *sdata = data;
int ecpointformatlist_length = *(sdata++);
if (ecpointformatlist_length != size - 1)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (!s->hit)
{
if(s->session->tlsext_ecpointformatlist)
{
OPENSSL_free(s->session->tlsext_ecpointformatlist);
s->session->tlsext_ecpointformatlist = NULL;
}
s->session->tlsext_ecpointformatlist_length = 0;
if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
}
#if 0
fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
sdata = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
fprintf(stderr,"%i ",*(sdata++));
fprintf(stderr,"\n");
#endif
}
else if (type == TLSEXT_TYPE_elliptic_curves)
{
unsigned char *sdata = data;
int ellipticcurvelist_length = (*(sdata++) << 8);
ellipticcurvelist_length += (*(sdata++));
if (ellipticcurvelist_length != size - 2 ||
ellipticcurvelist_length < 1)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (!s->hit)
{
if(s->session->tlsext_ellipticcurvelist)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
s->session->tlsext_ellipticcurvelist_length = 0;
if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
}
#if 0
fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
sdata = s->session->tlsext_ellipticcurvelist;
for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
fprintf(stderr,"%i ",*(sdata++));
fprintf(stderr,"\n");
#endif
}
#endif /* OPENSSL_NO_EC */
#ifdef TLSEXT_TYPE_opaque_prf_input
else if (type == TLSEXT_TYPE_opaque_prf_input &&
s->version != DTLS1_VERSION)
{
unsigned char *sdata = data;
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input_len != size - 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
OPENSSL_free(s->s3->client_opaque_prf_input);
if (s->s3->client_opaque_prf_input_len == 0)
s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
else
s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
#endif
else if (type == TLSEXT_TYPE_session_ticket)
{
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
else if (type == TLSEXT_TYPE_renegotiate)
{
if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
return 0;
renegotiate_seen = 1;
}
else if (type == TLSEXT_TYPE_signature_algorithms)
{
int dsize;
if (sigalg_seen || size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sigalg_seen = 1;
n2s(data,dsize);
size -= 2;
if (dsize != size || dsize & 1)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!tls1_process_sigalgs(s, data, dsize))
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
else if (type == TLSEXT_TYPE_status_request &&
s->version != DTLS1_VERSION)
{
if (size < 5)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
s->tlsext_status_type = *data++;
size--;
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
{
const unsigned char *sdata;
int dsize;
/* Read in responder_id_list */
n2s(data,dsize);
size -= 2;
if (dsize > size )
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
while (dsize > 0)
{
OCSP_RESPID *id;
int idsize;
if (dsize < 4)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(data, idsize);
dsize -= 2 + idsize;
size -= 2 + idsize;
if (dsize < 0)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sdata = data;
data += idsize;
id = d2i_OCSP_RESPID(NULL,
&sdata, idsize);
if (!id)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (data != sdata)
{
OCSP_RESPID_free(id);
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!s->tlsext_ocsp_ids
&& !(s->tlsext_ocsp_ids =
sk_OCSP_RESPID_new_null()))
{
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
if (!sk_OCSP_RESPID_push(
s->tlsext_ocsp_ids, id))
{
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
/* Read in request_extensions */
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(data,dsize);
size -= 2;
if (dsize != size)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sdata = data;
if (dsize > 0)
{
if (s->tlsext_ocsp_exts)
{
sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
X509_EXTENSION_free);
}
s->tlsext_ocsp_exts =
d2i_X509_EXTENSIONS(NULL,
&sdata, dsize);
if (!s->tlsext_ocsp_exts
|| (data + dsize != sdata))
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
}
/* We don't know what to do with any other type
* so ignore it.
*/
else
s->tlsext_status_type = -1;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (type == TLSEXT_TYPE_heartbeat)
{
switch(data[0])
{
case 0x01: /* Client allows us to send HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
break;
case 0x02: /* Client doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
break;
default: *al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0)
{
/* We shouldn't accept this extension on a
* renegotiation.
*
* s->new_session will be set on renegotiation, but we
* probably shouldn't rely that it couldn't be set on
* the initial renegotation too in certain cases (when
* there's some other reason to disallow resuming an
* earlier session -- the current code won't be doing
* anything like that, but this might change).
* A valid sign that there's been a previous handshake
* in this connection is if s->s3->tmp.finish_md_len >
* 0. (We are talking about a check that will happen
* in the Hello protocol round, well before a new
* Finished message could have been computed.) */
s->s3->next_proto_neg_seen = 1;
}
#endif
/* session ticket processed earlier */
#ifndef OPENSSL_NO_SRTP
else if (type == TLSEXT_TYPE_use_srtp)
{
if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
al))
}
#endif
data+=size;
}
*p = data;
ri_check:
/* Need RI if renegotiating */
if (!renegotiate_seen && s->renegotiate &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: Memory leak in d1_srtp.c in the DTLS SRTP extension in OpenSSL 1.0.1 before 1.0.1j allows remote attackers to cause a denial of service (memory consumption) via a crafted handshake message.
Commit Message:
|
Medium
| 165,171
|
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: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
{
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The BEEP parser in tcpdump before 4.9.2 has a buffer over-read in print-beep.c:l_strnstart().
Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
|
Low
| 167,885
|
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 PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
#if defined(ENABLE_BASIC_PRINTING)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
#endif // ENABLE_BASIC_PRINTING
IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
SetScriptedPrintBlocked)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple use-after-free vulnerabilities in the PrintWebViewHelper class in components/printing/renderer/print_web_view_helper.cc in Google Chrome before 45.0.2454.85 allow user-assisted remote attackers to cause a denial of service or possibly have unspecified other impact by triggering nested IPC messages during preparation for printing, as demonstrated by messages associated with PDF documents in conjunction with messages about printer capabilities.
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
|
Low
| 171,872
|
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 UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId,
wStream* s)
{
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp,
cbChId,
ChannelId);
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Vulnerability Type:
CWE ID:
Summary: FreeRDP FreeRDP 2.0.0-rc3 released version before commit 205c612820dac644d665b5bb1cdf437dc5ca01e3 contains a Other/Unknown vulnerability in channels/drdynvc/client/drdynvc_main.c, drdynvc_process_capability_request that can result in The RDP server can read the client's memory.. This attack appear to be exploitable via RDPClient must connect the rdp server with echo option. This vulnerability appears to have been fixed in after commit 205c612820dac644d665b5bb1cdf437dc5ca01e3.
Commit Message: Fix for #4866: Added additional length checks
|
Low
| 168,937
|
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: PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
if (!element || !element->isHTMLElement()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
RefPtr<DocumentFragment> fragment = createDocumentFragmentForElement(markup, toElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted);
if (!fragment) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return fragment.release();
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: Google Chrome before 13.0.782.107 does not prevent calls to functions in other frames, which allows remote attackers to bypass intended access restrictions via a crafted web site, related to a *cross-frame function leak.*
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
Medium
| 170,434
|
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 WebGL2RenderingContextBase::deleteVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost() || !vertex_array)
return;
if (!vertex_array->IsDefaultObject() &&
vertex_array == bound_vertex_array_object_)
SetBoundVertexArrayObject(nullptr);
vertex_array->DeleteObject(ContextGL());
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: Insufficient data validation in WebGL in Google Chrome prior to 68.0.3440.75 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <kainino@chromium.org>
Reviewed-by: Antoine Labour <piman@chromium.org>
Commit-Queue: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#565016}
|
Medium
| 173,124
|
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 CSPSource::schemeMatches(const KURL& url) const
{
if (m_scheme.isEmpty())
return m_policy->protocolMatchesSelf(url);
return equalIgnoringCase(url.protocol(), m_scheme);
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The CSPSource::schemeMatches function in WebKit/Source/core/frame/csp/CSPSource.cpp in the Content Security Policy (CSP) implementation in Blink, as used in Google Chrome before 48.0.2564.82, does not apply http policies to https URLs and does not apply ws policies to wss URLs, which makes it easier for remote attackers to determine whether a specific HSTS web site has been visited by reading a CSP report.
Commit Message: CSP: Source expressions can no longer lock sites into insecurity.
CSP's matching algorithm has been updated to make clever folks like Yan
slightly less able to gather data on user's behavior based on CSP
reports[1]. This matches Firefox's existing behavior (they apparently
changed this behavior a few months ago, via a happy accident[2]), and
mitigates the CSP-variant of Sniffly[3].
On the dashboard at https://www.chromestatus.com/feature/6653486812889088.
[1]: https://github.com/w3c/webappsec-csp/commit/0e81d81b64c42ca3c81c048161162b9697ff7b60
[2]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218524#c2
[3]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218778#c7
BUG=544765,558232
Review URL: https://codereview.chromium.org/1455973003
Cr-Commit-Position: refs/heads/master@{#360562}
|
Medium
| 172,237
|
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 GLES2DecoderImpl::SimulateAttrib0(
const char* function_name, GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return true;
}
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
GLuint num_vertices = max_vertex_accessed + 1;
GLuint size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)),
&size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
PerformanceWarning(
"Attribute 0 is disabled. This has signficant performance penalty");
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_;
if (new_buffer) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
}
if (new_buffer ||
(attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3])))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
if (info->divisor())
glVertexAttribDivisorANGLE(0, 0);
*simulated = true;
return true;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-189
Summary: Integer overflow in the WebGL implementation in Google Chrome before 22.0.1229.79 on Mac OS X allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 170,750
|
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 transport_connect_nla(rdpTransport* transport)
{
freerdp* instance;
rdpSettings* settings;
if (transport->layer == TRANSPORT_LAYER_TSG)
return TRUE;
if (!transport_connect_tls(transport))
return FALSE;
/* Network Level Authentication */
if (transport->settings->Authentication != TRUE)
return TRUE;
settings = transport->settings;
instance = (freerdp*) settings->instance;
if (transport->credssp == NULL)
transport->credssp = credssp_new(instance, transport, settings);
if (credssp_authenticate(transport->credssp) < 0)
{
if (!connectErrorCode)
connectErrorCode = AUTHENTICATIONERROR;
fprintf(stderr, "Authentication failure, check credentials.\n"
"If credentials are valid, the NTLMSSP implementation may be to blame.\n");
credssp_free(transport->credssp);
return FALSE;
}
credssp_free(transport->credssp);
return TRUE;
}
Vulnerability Type: DoS
CWE ID: CWE-476
Summary: FreeRDP before 1.1.0-beta+2013071101 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) by disconnecting before authentication has finished.
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
|
Low
| 167,602
|
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 __net_exit sctp_net_exit(struct net *net)
{
/* Free the local address list */
sctp_free_addr_wq(net);
sctp_free_local_addr_list(net);
/* Free the control endpoint. */
inet_ctl_sock_destroy(net->sctp.ctl_sock);
sctp_dbg_objcnt_exit(net);
sctp_proc_exit(net);
cleanup_sctp_mibs(net);
sctp_sysctl_net_unregister(net);
}
Vulnerability Type: DoS Overflow Mem. Corr.
CWE ID: CWE-119
Summary: The sctp_init function in net/sctp/protocol.c in the Linux kernel before 4.2.3 has an incorrect sequence of protocol-initialization steps, which allows local users to cause a denial of service (panic or memory corruption) by creating SCTP sockets before all of the steps have finished.
Commit Message: sctp: fix race on protocol/netns initialization
Consider sctp module is unloaded and is being requested because an user
is creating a sctp socket.
During initialization, sctp will add the new protocol type and then
initialize pernet subsys:
status = sctp_v4_protosw_init();
if (status)
goto err_protosw_init;
status = sctp_v6_protosw_init();
if (status)
goto err_v6_protosw_init;
status = register_pernet_subsys(&sctp_net_ops);
The problem is that after those calls to sctp_v{4,6}_protosw_init(), it
is possible for userspace to create SCTP sockets like if the module is
already fully loaded. If that happens, one of the possible effects is
that we will have readers for net->sctp.local_addr_list list earlier
than expected and sctp_net_init() does not take precautions while
dealing with that list, leading to a potential panic but not limited to
that, as sctp_sock_init() will copy a bunch of blank/partially
initialized values from net->sctp.
The race happens like this:
CPU 0 | CPU 1
socket() |
__sock_create | socket()
inet_create | __sock_create
list_for_each_entry_rcu( |
answer, &inetsw[sock->type], |
list) { | inet_create
/* no hits */ |
if (unlikely(err)) { |
... |
request_module() |
/* socket creation is blocked |
* the module is fully loaded |
*/ |
sctp_init |
sctp_v4_protosw_init |
inet_register_protosw |
list_add_rcu(&p->list, |
last_perm); |
| list_for_each_entry_rcu(
| answer, &inetsw[sock->type],
sctp_v6_protosw_init | list) {
| /* hit, so assumes protocol
| * is already loaded
| */
| /* socket creation continues
| * before netns is initialized
| */
register_pernet_subsys |
Simply inverting the initialization order between
register_pernet_subsys() and sctp_v4_protosw_init() is not possible
because register_pernet_subsys() will create a control sctp socket, so
the protocol must be already visible by then. Deferring the socket
creation to a work-queue is not good specially because we loose the
ability to handle its errors.
So, as suggested by Vlad, the fix is to split netns initialization in
two moments: defaults and control socket, so that the defaults are
already loaded by when we register the protocol, while control socket
initialization is kept at the same moment it is today.
Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace")
Signed-off-by: Vlad Yasevich <vyasevich@gmail.com>
Signed-off-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Medium
| 166,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 PageRequestSummary::UpdateOrAddToOrigins(
const content::mojom::ResourceLoadInfo& resource_load_info) {
for (const auto& redirect_info : resource_load_info.redirect_info_chain)
UpdateOrAddToOrigins(redirect_info->url, redirect_info->network_info);
UpdateOrAddToOrigins(resource_load_info.url, resource_load_info.network_info);
}
Vulnerability Type:
CWE ID: CWE-125
Summary: Insufficient validation of untrusted input in Skia in Google Chrome prior to 59.0.3071.86 for Linux, Windows, and Mac, and 59.0.3071.92 for Android, allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page.
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
|
Medium
| 172,367
|
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 long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct ion_client *client = filp->private_data;
struct ion_device *dev = client->dev;
struct ion_handle *cleanup_handle = NULL;
int ret = 0;
unsigned int dir;
union {
struct ion_fd_data fd;
struct ion_allocation_data allocation;
struct ion_handle_data handle;
struct ion_custom_data custom;
} data;
dir = ion_ioctl_dir(cmd);
if (_IOC_SIZE(cmd) > sizeof(data))
return -EINVAL;
if (dir & _IOC_WRITE)
if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd)))
return -EFAULT;
switch (cmd) {
case ION_IOC_ALLOC:
{
struct ion_handle *handle;
handle = ion_alloc(client, data.allocation.len,
data.allocation.align,
data.allocation.heap_id_mask,
data.allocation.flags);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.allocation.handle = handle->id;
cleanup_handle = handle;
break;
}
case ION_IOC_FREE:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
ion_free(client, handle);
ion_handle_put(handle);
break;
}
case ION_IOC_SHARE:
case ION_IOC_MAP:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.fd.fd = ion_share_dma_buf_fd(client, handle);
ion_handle_put(handle);
if (data.fd.fd < 0)
ret = data.fd.fd;
break;
}
case ION_IOC_IMPORT:
{
struct ion_handle *handle;
handle = ion_import_dma_buf_fd(client, data.fd.fd);
if (IS_ERR(handle))
ret = PTR_ERR(handle);
else
data.handle.handle = handle->id;
break;
}
case ION_IOC_SYNC:
{
ret = ion_sync_for_device(client, data.fd.fd);
break;
}
case ION_IOC_CUSTOM:
{
if (!dev->custom_ioctl)
return -ENOTTY;
ret = dev->custom_ioctl(client, data.custom.cmd,
data.custom.arg);
break;
}
default:
return -ENOTTY;
}
if (dir & _IOC_READ) {
if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) {
if (cleanup_handle)
ion_free(client, cleanup_handle);
return -EFAULT;
}
}
return ret;
}
Vulnerability Type: DoS +Priv
CWE ID: CWE-416
Summary: Race condition in the ion_ioctl function in drivers/staging/android/ion/ion.c in the Linux kernel before 4.6 allows local users to gain privileges or cause a denial of service (use-after-free) by calling ION_IOC_FREE on two CPUs at the same time.
Commit Message: staging/android/ion : fix a race condition in the ion driver
There is a use-after-free problem in the ion driver.
This is caused by a race condition in the ion_ioctl()
function.
A handle has ref count of 1 and two tasks on different
cpus calls ION_IOC_FREE simultaneously.
cpu 0 cpu 1
-------------------------------------------------------
ion_handle_get_by_id()
(ref == 2)
ion_handle_get_by_id()
(ref == 3)
ion_free()
(ref == 2)
ion_handle_put()
(ref == 1)
ion_free()
(ref == 0 so ion_handle_destroy() is
called
and the handle is freed.)
ion_handle_put() is called and it
decreases the slub's next free pointer
The problem is detected as an unaligned access in the
spin lock functions since it uses load exclusive
instruction. In some cases it corrupts the slub's
free pointer which causes a mis-aligned access to the
next free pointer.(kmalloc returns a pointer like
ffffc0745b4580aa). And it causes lots of other
hard-to-debug problems.
This symptom is caused since the first member in the
ion_handle structure is the reference count and the
ion driver decrements the reference after it has been
freed.
To fix this problem client->lock mutex is extended
to protect all the codes that uses the handle.
Signed-off-by: Eun Taik Lee <eun.taik.lee@samsung.com>
Reviewed-by: Laura Abbott <labbott@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
|
Medium
| 166,899
|
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 MSLStartElement(void *context,const xmlChar *tag,
const xmlChar **attributes)
{
AffineMatrix
affine,
current;
ChannelType
channel;
char
key[MaxTextExtent],
*value;
const char
*attribute,
*keyword;
double
angle;
DrawInfo
*draw_info;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*image;
int
flags;
ssize_t
option,
j,
n,
x,
y;
MSLInfo
*msl_info;
RectangleInfo
geometry;
register ssize_t
i;
size_t
height,
width;
/*
Called when an opening tag has been processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.startElement(%s",tag);
exception=AcquireExceptionInfo();
msl_info=(MSLInfo *) context;
n=msl_info->n;
keyword=(const char *) NULL;
value=(char *) NULL;
SetGeometryInfo(&geometry_info);
(void) ResetMagickMemory(&geometry,0,sizeof(geometry));
channel=DefaultChannels;
switch (*tag)
{
case 'A':
case 'a':
{
if (LocaleCompare((const char *) tag,"add-noise") == 0)
{
Image
*noise_image;
NoiseType
noise;
/*
Add noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
noise=UniformNoise;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(keyword,"noise") == 0)
{
option=ParseCommandOption(MagickNoiseOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
noise=(NoiseType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
noise_image=AddNoiseImageChannel(msl_info->image[n],channel,noise,
&msl_info->image[n]->exception);
if (noise_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=noise_image;
break;
}
if (LocaleCompare((const char *) tag,"annotate") == 0)
{
char
text[MaxTextExtent];
/*
Annotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=tan(DegreesToRadians(fmod((double) angle,
360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=tan(DegreesToRadians(fmod((double) angle,
360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
CloneString(&draw_info->text,value);
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
(void) AnnotateImage(msl_info->image[n],draw_info);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"append") == 0)
{
Image
*append_image;
MagickBooleanType
stack;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
stack=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'S':
case 's':
{
if (LocaleCompare(keyword,"stack") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
stack=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
append_image=AppendImages(msl_info->image[n],stack,
&msl_info->image[n]->exception);
if (append_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=append_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
break;
}
case 'B':
case 'b':
{
if (LocaleCompare((const char *) tag,"blur") == 0)
{
Image
*blur_image;
/*
Blur image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
blur_image=BlurImageChannel(msl_info->image[n],channel,
geometry_info.rho,geometry_info.sigma,
&msl_info->image[n]->exception);
if (blur_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=blur_image;
break;
}
if (LocaleCompare((const char *) tag,"border") == 0)
{
Image
*border_image;
/*
Border image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
msl_info->image[n]->compose=(CompositeOperator) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->border_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
border_image=BorderImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (border_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=border_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'C':
case 'c':
{
if (LocaleCompare((const char *) tag,"colorize") == 0)
{
char
opacity[MaxTextExtent];
Image
*colorize_image;
PixelPacket
target;
/*
Add noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
target=msl_info->image[n]->background_color;
(void) CopyMagickString(opacity,"100",MaxTextExtent);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&target,
&msl_info->image[n]->exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
(void) CopyMagickString(opacity,value,MaxTextExtent);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
colorize_image=ColorizeImage(msl_info->image[n],opacity,target,
&msl_info->image[n]->exception);
if (colorize_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=colorize_image;
break;
}
if (LocaleCompare((const char *) tag, "charcoal") == 0)
{
double radius = 0.0,
sigma = 1.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/*
NOTE: charcoal can have no attributes, since we use all the defaults!
*/
if (attributes != (const xmlChar **) NULL)
{
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
radius=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
sigma = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
}
/*
charcoal image.
*/
{
Image
*newImage;
newImage=CharcoalImage(msl_info->image[n],radius,sigma,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
if (LocaleCompare((const char *) tag,"chop") == 0)
{
Image
*chop_image;
/*
Chop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
chop_image=ChopImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (chop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=chop_image;
break;
}
if (LocaleCompare((const char *) tag,"color-floodfill") == 0)
{
PaintMethod
paint_method;
MagickPixelPacket
target;
/*
Color floodfill image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
SetGeometry(msl_info->image[n],&geometry);
paint_method=FloodfillMethod;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryMagickColor(value,&target,exception);
paint_method=FillToBorderMethod;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FloodfillPaintImage(msl_info->image[n],DefaultChannels,
draw_info,&target,geometry.x,geometry.y,
paint_method == FloodfillMethod ? MagickFalse : MagickTrue);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"comment") == 0)
break;
if (LocaleCompare((const char *) tag,"composite") == 0)
{
char
composite_geometry[MaxTextExtent];
CompositeOperator
compose;
Image
*composite_image,
*rotate_image;
PixelPacket
target;
/*
Composite image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
composite_image=NewImageList();
compose=OverCompositeOp;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
compose=(CompositeOperator) option;
break;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
composite_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
break;
}
}
if (composite_image == (Image *) NULL)
break;
rotate_image=NewImageList();
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blend") == 0)
{
(void) SetImageArtifact(composite_image,
"compose:args",value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
if (LocaleCompare(keyword, "color") == 0)
{
(void) QueryColorDatabase(value,
&composite_image->background_color,exception);
break;
}
if (LocaleCompare(keyword,"compose") == 0)
break;
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
msl_info->image[n]->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
break;
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"mask") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(value,value) == 0))
{
SetImageType(composite_image,TrueColorMatteType);
(void) CompositeImage(composite_image,
CopyOpacityCompositeOp,msl_info->image[j],0,0);
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
ssize_t
opacity,
y;
register ssize_t
x;
register PixelPacket
*q;
CacheView
*composite_view;
opacity=QuantumRange-StringToLong(value);
if (compose != DissolveCompositeOp)
{
(void) SetImageOpacity(composite_image,(Quantum)
opacity);
break;
}
(void) SetImageArtifact(msl_info->image[n],
"compose:args",value);
if (composite_image->matte != MagickTrue)
(void) SetImageOpacity(composite_image,OpaqueOpacity);
composite_view=AcquireAuthenticCacheView(composite_image,
exception);
for (y=0; y < (ssize_t) composite_image->rows ; y++)
{
q=GetCacheViewAuthenticPixels(composite_view,0,y,
(ssize_t) composite_image->columns,1,exception);
for (x=0; x < (ssize_t) composite_image->columns; x++)
{
if (q->opacity == OpaqueOpacity)
q->opacity=ClampToQuantum(opacity);
q++;
}
if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse)
break;
}
composite_view=DestroyCacheView(composite_view);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
rotate_image=RotateImage(composite_image,
StringToDouble(value,(char **) NULL),exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"tile") == 0)
{
MagickBooleanType
tile;
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
tile=(MagickBooleanType) option;
(void) tile;
if (rotate_image != (Image *) NULL)
(void) SetImageArtifact(rotate_image,
"compose:outside-overlay","false");
else
(void) SetImageArtifact(composite_image,
"compose:outside-overlay","false");
image=msl_info->image[n];
height=composite_image->rows;
width=composite_image->columns;
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height)
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width)
{
if (rotate_image != (Image *) NULL)
(void) CompositeImage(image,compose,rotate_image,
x,y);
else
(void) CompositeImage(image,compose,
composite_image,x,y);
}
if (rotate_image != (Image *) NULL)
rotate_image=DestroyImage(rotate_image);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
image=msl_info->image[n];
(void) FormatLocaleString(composite_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,
(double) composite_image->rows,(double) geometry.x,(double)
geometry.y);
flags=ParseGravityGeometry(image,composite_geometry,&geometry,
exception);
if (rotate_image == (Image *) NULL)
CompositeImageChannel(image,channel,compose,composite_image,
geometry.x,geometry.y);
else
{
/*
Rotate image.
*/
geometry.x-=(ssize_t) (rotate_image->columns-
composite_image->columns)/2;
geometry.y-=(ssize_t) (rotate_image->rows-composite_image->rows)/2;
CompositeImageChannel(image,channel,compose,rotate_image,
geometry.x,geometry.y);
rotate_image=DestroyImage(rotate_image);
}
composite_image=DestroyImage(composite_image);
break;
}
if (LocaleCompare((const char *) tag,"contrast") == 0)
{
MagickBooleanType
sharpen;
/*
Contrast image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
sharpen=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sharpen") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
sharpen=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) ContrastImage(msl_info->image[n],sharpen);
break;
}
if (LocaleCompare((const char *) tag,"crop") == 0)
{
Image
*crop_image;
/*
Crop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGravityGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
crop_image=CropImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (crop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=crop_image;
break;
}
if (LocaleCompare((const char *) tag,"cycle-colormap") == 0)
{
ssize_t
display;
/*
Cycle-colormap image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
display=0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"display") == 0)
{
display=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) CycleColormapImage(msl_info->image[n],display);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'D':
case 'd':
{
if (LocaleCompare((const char *) tag,"despeckle") == 0)
{
Image
*despeckle_image;
/*
Despeckle image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
despeckle_image=DespeckleImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (despeckle_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=despeckle_image;
break;
}
if (LocaleCompare((const char *) tag,"display") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) DisplayImages(msl_info->image_info[n],msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"draw") == 0)
{
char
text[MaxTextExtent];
/*
Annotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"points") == 0)
{
if (LocaleCompare(draw_info->primitive,"path") == 0)
{
(void) ConcatenateString(&draw_info->primitive," '");
ConcatenateString(&draw_info->primitive,value);
(void) ConcatenateString(&draw_info->primitive,"'");
}
else
{
(void) ConcatenateString(&draw_info->primitive," ");
ConcatenateString(&draw_info->primitive,value);
}
break;
}
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"primitive") == 0)
{
CloneString(&draw_info->primitive,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
(void) ConcatenateString(&draw_info->primitive," '");
(void) ConcatenateString(&draw_info->primitive,value);
(void) ConcatenateString(&draw_info->primitive,"'");
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
(void) DrawImage(msl_info->image[n],draw_info);
draw_info=DestroyDrawInfo(draw_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'E':
case 'e':
{
if (LocaleCompare((const char *) tag,"edge") == 0)
{
Image
*edge_image;
/*
Edge image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
edge_image=EdgeImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (edge_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=edge_image;
break;
}
if (LocaleCompare((const char *) tag,"emboss") == 0)
{
Image
*emboss_image;
/*
Emboss image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (emboss_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=emboss_image;
break;
}
if (LocaleCompare((const char *) tag,"enhance") == 0)
{
Image
*enhance_image;
/*
Enhance image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
enhance_image=EnhanceImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (enhance_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=enhance_image;
break;
}
if (LocaleCompare((const char *) tag,"equalize") == 0)
{
/*
Equalize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) EqualizeImage(msl_info->image[n]);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'F':
case 'f':
{
if (LocaleCompare((const char *) tag, "flatten") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/* no attributes here */
/* process the image */
{
Image
*newImage;
newImage=MergeImageLayers(msl_info->image[n],FlattenLayer,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
if (LocaleCompare((const char *) tag,"flip") == 0)
{
Image
*flip_image;
/*
Flip image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
flip_image=FlipImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (flip_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=flip_image;
break;
}
if (LocaleCompare((const char *) tag,"flop") == 0)
{
Image
*flop_image;
/*
Flop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
flop_image=FlopImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (flop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=flop_image;
break;
}
if (LocaleCompare((const char *) tag,"frame") == 0)
{
FrameInfo
frame_info;
Image
*frame_image;
/*
Frame image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
(void) ResetMagickMemory(&frame_info,0,sizeof(frame_info));
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
msl_info->image[n]->compose=(CompositeOperator) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->matte_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
frame_info.width=geometry.width;
frame_info.height=geometry.height;
frame_info.outer_bevel=geometry.x;
frame_info.inner_bevel=geometry.y;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
frame_info.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"inner") == 0)
{
frame_info.inner_bevel=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"outer") == 0)
{
frame_info.outer_bevel=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
frame_info.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
frame_info.x=(ssize_t) frame_info.width;
frame_info.y=(ssize_t) frame_info.height;
frame_info.width=msl_info->image[n]->columns+2*frame_info.x;
frame_info.height=msl_info->image[n]->rows+2*frame_info.y;
frame_image=FrameImage(msl_info->image[n],&frame_info,
&msl_info->image[n]->exception);
if (frame_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=frame_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) tag,"gamma") == 0)
{
char
gamma[MaxTextExtent];
MagickPixelPacket
pixel;
/*
Gamma image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
channel=UndefinedChannel;
pixel.red=0.0;
pixel.green=0.0;
pixel.blue=0.0;
*gamma='\0';
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blue") == 0)
{
pixel.blue=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
(void) CopyMagickString(gamma,value,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"green") == 0)
{
pixel.green=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"red") == 0)
{
pixel.red=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
if (*gamma == '\0')
(void) FormatLocaleString(gamma,MaxTextExtent,"%g,%g,%g",
(double) pixel.red,(double) pixel.green,(double) pixel.blue);
switch (channel)
{
default:
{
(void) GammaImage(msl_info->image[n],gamma);
break;
}
case RedChannel:
{
(void) GammaImageChannel(msl_info->image[n],RedChannel,pixel.red);
break;
}
case GreenChannel:
{
(void) GammaImageChannel(msl_info->image[n],GreenChannel,
pixel.green);
break;
}
case BlueChannel:
{
(void) GammaImageChannel(msl_info->image[n],BlueChannel,
pixel.blue);
break;
}
}
break;
}
else if (LocaleCompare((const char *) tag,"get") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,(const char *) attributes[i]);
(void) CopyMagickString(key,value,MaxTextExtent);
switch (*keyword)
{
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
(double) msl_info->image[n]->rows);
(void) SetImageProperty(msl_info->attributes[n],key,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
(double) msl_info->image[n]->columns);
(void) SetImageProperty(msl_info->attributes[n],key,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
else if (LocaleCompare((const char *) tag, "group") == 0)
{
msl_info->number_groups++;
msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory(
msl_info->group_info,msl_info->number_groups+1UL,
sizeof(*msl_info->group_info));
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) tag,"image") == 0)
{
MSLPushImage(msl_info,(Image *) NULL);
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"color") == 0)
{
Image
*next_image;
(void) CopyMagickString(msl_info->image_info[n]->filename,
"xc:",MaxTextExtent);
(void) ConcatenateMagickString(msl_info->image_info[n]->
filename,value,MaxTextExtent);
next_image=ReadImage(msl_info->image_info[n],exception);
CatchException(exception);
if (next_image == (Image *) NULL)
continue;
if (msl_info->image[n] == (Image *) NULL)
msl_info->image[n]=next_image;
else
{
register Image
*p;
/*
Link image into image list.
*/
p=msl_info->image[n];
while (p->next != (Image *) NULL)
p=GetNextImageInList(p);
next_image->previous=p;
p->next=next_image;
}
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"implode") == 0)
{
Image
*implode_image;
/*
Implode image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"amount") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (implode_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=implode_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) tag,"label") == 0)
break;
if (LocaleCompare((const char *) tag, "level") == 0)
{
double
levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,(const char *) attributes[i]);
(void) CopyMagickString(key,value,MaxTextExtent);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"black") == 0)
{
levelBlack = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
levelGamma = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"white") == 0)
{
levelWhite = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/* process image */
{
char level[MaxTextExtent + 1];
(void) FormatLocaleString(level,MaxTextExtent,"%3.6f/%3.6f/%3.6f/",
levelBlack,levelGamma,levelWhite);
LevelImage ( msl_info->image[n], level );
break;
}
}
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) tag,"magnify") == 0)
{
Image
*magnify_image;
/*
Magnify image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
magnify_image=MagnifyImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (magnify_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=magnify_image;
break;
}
if (LocaleCompare((const char *) tag,"map") == 0)
{
Image
*affinity_image;
MagickBooleanType
dither;
QuantizeInfo
*quantize_info;
/*
Map image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
affinity_image=NewImageList();
dither=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"dither") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
dither=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
affinity_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]);
quantize_info->dither=dither;
(void) RemapImages(quantize_info,msl_info->image[n],
affinity_image);
quantize_info=DestroyQuantizeInfo(quantize_info);
affinity_image=DestroyImage(affinity_image);
break;
}
if (LocaleCompare((const char *) tag,"matte-floodfill") == 0)
{
double
opacity;
MagickPixelPacket
target;
PaintMethod
paint_method;
/*
Matte floodfill image.
*/
opacity=0.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
paint_method=FloodfillMethod;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryMagickColor(value,&target,exception);
paint_method=FillToBorderMethod;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
opacity=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
draw_info->fill.opacity=ClampToQuantum(opacity);
(void) FloodfillPaintImage(msl_info->image[n],OpacityChannel,
draw_info,&target,geometry.x,geometry.y,
paint_method == FloodfillMethod ? MagickFalse : MagickTrue);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"median-filter") == 0)
{
Image
*median_image;
/*
Median-filter image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
median_image=StatisticImage(msl_info->image[n],MedianStatistic,
(size_t) geometry_info.rho,(size_t) geometry_info.sigma,
&msl_info->image[n]->exception);
if (median_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=median_image;
break;
}
if (LocaleCompare((const char *) tag,"minify") == 0)
{
Image
*minify_image;
/*
Minify image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
minify_image=MinifyImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (minify_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=minify_image;
break;
}
if (LocaleCompare((const char *) tag,"msl") == 0 )
break;
if (LocaleCompare((const char *) tag,"modulate") == 0)
{
char
modulate[MaxTextExtent];
/*
Modulate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=100.0;
geometry_info.sigma=100.0;
geometry_info.xi=100.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blackness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"brightness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"factor") == 0)
{
flags=ParseGeometry(value,&geometry_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"hue") == 0)
{
geometry_info.xi=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(keyword,"lightness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"saturation") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"whiteness") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(modulate,MaxTextExtent,"%g,%g,%g",
geometry_info.rho,geometry_info.sigma,geometry_info.xi);
(void) ModulateImage(msl_info->image[n],modulate);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'N':
case 'n':
{
if (LocaleCompare((const char *) tag,"negate") == 0)
{
MagickBooleanType
gray;
/*
Negate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
gray=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gray") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
gray=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) NegateImageChannel(msl_info->image[n],channel,gray);
break;
}
if (LocaleCompare((const char *) tag,"normalize") == 0)
{
/*
Normalize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) NormalizeImageChannel(msl_info->image[n],channel);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'O':
case 'o':
{
if (LocaleCompare((const char *) tag,"oil-paint") == 0)
{
Image
*paint_image;
/*
Oil-paint image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (paint_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=paint_image;
break;
}
if (LocaleCompare((const char *) tag,"opaque") == 0)
{
MagickPixelPacket
fill_color,
target;
/*
Opaque image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
(void) QueryMagickColor("none",&target,exception);
(void) QueryMagickColor("none",&fill_color,exception);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryMagickColor(value,&fill_color,exception);
break;
}
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) OpaquePaintImageChannel(msl_info->image[n],channel,
&target,&fill_color,MagickFalse);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'P':
case 'p':
{
if (LocaleCompare((const char *) tag,"print") == 0)
{
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"output") == 0)
{
(void) FormatLocaleFile(stdout,"%s",value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag, "profile") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
const char
*name;
const StringInfo
*profile;
Image
*profile_image;
ImageInfo
*profile_info;
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
if (*keyword == '!')
{
/*
Remove a profile from the image.
*/
(void) ProfileImage(msl_info->image[n],keyword,
(const unsigned char *) NULL,0,MagickTrue);
continue;
}
/*
Associate a profile with the image.
*/
profile_info=CloneImageInfo(msl_info->image_info[n]);
profile=GetImageProfile(msl_info->image[n],"iptc");
if (profile != (StringInfo *) NULL)
profile_info->profile=(void *) CloneStringInfo(profile);
profile_image=GetImageCache(profile_info,keyword,exception);
profile_info=DestroyImageInfo(profile_info);
if (profile_image == (Image *) NULL)
{
char
name[MaxTextExtent],
filename[MaxTextExtent];
register char
*p;
StringInfo
*profile;
(void) CopyMagickString(filename,keyword,MaxTextExtent);
(void) CopyMagickString(name,keyword,MaxTextExtent);
for (p=filename; *p != '\0'; p++)
if ((*p == ':') && (IsPathDirectory(keyword) < 0) &&
(IsPathAccessible(keyword) == MagickFalse))
{
register char
*q;
/*
Look for profile name (e.g. name:profile).
*/
(void) CopyMagickString(name,filename,(size_t)
(p-filename+1));
for (q=filename; *q != '\0'; q++)
*q=(*++p);
break;
}
profile=FileToStringInfo(filename,~0UL,exception);
if (profile != (StringInfo *) NULL)
{
(void) ProfileImage(msl_info->image[n],name,
GetStringInfoDatum(profile),(size_t)
GetStringInfoLength(profile),MagickFalse);
profile=DestroyStringInfo(profile);
}
continue;
}
ResetImageProfileIterator(profile_image);
name=GetNextImageProfile(profile_image);
while (name != (const char *) NULL)
{
profile=GetImageProfile(profile_image,name);
if (profile != (StringInfo *) NULL)
(void) ProfileImage(msl_info->image[n],name,
GetStringInfoDatum(profile),(size_t)
GetStringInfoLength(profile),MagickFalse);
name=GetNextImageProfile(profile_image);
}
profile_image=DestroyImage(profile_image);
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'Q':
case 'q':
{
if (LocaleCompare((const char *) tag,"quantize") == 0)
{
QuantizeInfo
quantize_info;
/*
Quantize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
GetQuantizeInfo(&quantize_info);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"colors") == 0)
{
quantize_info.number_colors=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
option=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,
"UnrecognizedColorspaceType",value);
quantize_info.colorspace=(ColorspaceType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"dither") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
quantize_info.dither=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"measure") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
quantize_info.measure_error=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"treedepth") == 0)
{
quantize_info.tree_depth=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) QuantizeImage(&quantize_info,msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"query-font-metrics") == 0)
{
char
text[MaxTextExtent];
MagickBooleanType
status;
TypeMetric
metrics;
/*
Query font metrics.
*/
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
CloneString(&draw_info->text,value);
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics);
if (status != MagickFalse)
{
Image
*image;
image=msl_info->attributes[n];
FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x",
"%g",metrics.pixels_per_em.x);
FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y",
"%g",metrics.pixels_per_em.y);
FormatImageProperty(image,"msl:font-metrics.ascent","%g",
metrics.ascent);
FormatImageProperty(image,"msl:font-metrics.descent","%g",
metrics.descent);
FormatImageProperty(image,"msl:font-metrics.width","%g",
metrics.width);
FormatImageProperty(image,"msl:font-metrics.height","%g",
metrics.height);
FormatImageProperty(image,"msl:font-metrics.max_advance","%g",
metrics.max_advance);
FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g",
metrics.bounds.x1);
FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g",
metrics.bounds.y1);
FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g",
metrics.bounds.x2);
FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g",
metrics.bounds.y2);
FormatImageProperty(image,"msl:font-metrics.origin.x","%g",
metrics.origin.x);
FormatImageProperty(image,"msl:font-metrics.origin.y","%g",
metrics.origin.y);
}
draw_info=DestroyDrawInfo(draw_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'R':
case 'r':
{
if (LocaleCompare((const char *) tag,"raise") == 0)
{
MagickBooleanType
raise;
/*
Raise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
raise=MagickFalse;
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"raise") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
raise=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) RaiseImage(msl_info->image[n],&geometry,raise);
break;
}
if (LocaleCompare((const char *) tag,"read") == 0)
{
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filename") == 0)
{
Image
*image;
(void) CopyMagickString(msl_info->image_info[n]->filename,
value,MaxTextExtent);
image=ReadImage(msl_info->image_info[n],exception);
CatchException(exception);
if (image == (Image *) NULL)
continue;
AppendImageToList(&msl_info->image[n],image);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"reduce-noise") == 0)
{
Image
*paint_image;
/*
Reduce-noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic,
(size_t) geometry_info.rho,(size_t) geometry_info.sigma,
&msl_info->image[n]->exception);
if (paint_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=paint_image;
break;
}
else if (LocaleCompare((const char *) tag,"repage") == 0)
{
/* init the values */
width=msl_info->image[n]->page.width;
height=msl_info->image[n]->page.height;
x=msl_info->image[n]->page.x;
y=msl_info->image[n]->page.y;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
int
flags;
RectangleInfo
geometry;
flags=ParseAbsoluteGeometry(value,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
width=geometry.width;
height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
x+=geometry.x;
if ((flags & YValue) != 0)
y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
x=geometry.x;
if ((width == 0) && (geometry.x > 0))
width=msl_info->image[n]->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
y=geometry.y;
if ((height == 0) && (geometry.y > 0))
height=msl_info->image[n]->rows+geometry.y;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
height = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
width = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
x = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
y = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
msl_info->image[n]->page.width=width;
msl_info->image[n]->page.height=height;
msl_info->image[n]->page.x=x;
msl_info->image[n]->page.y=y;
break;
}
else if (LocaleCompare((const char *) tag,"resample") == 0)
{
double
x_resolution,
y_resolution;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
x_resolution=DefaultResolution;
y_resolution=DefaultResolution;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'b':
{
if (LocaleCompare(keyword,"blur") == 0)
{
msl_info->image[n]->blur=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
ssize_t
flags;
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma*=geometry_info.rho;
x_resolution=geometry_info.rho;
y_resolution=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x-resolution") == 0)
{
x_resolution=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y-resolution") == 0)
{
y_resolution=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
Resample image.
*/
{
double
factor;
Image
*resample_image;
factor=1.0;
if (msl_info->image[n]->units == PixelsPerCentimeterResolution)
factor=2.54;
width=(size_t) (x_resolution*msl_info->image[n]->columns/
(factor*(msl_info->image[n]->x_resolution == 0.0 ? DefaultResolution :
msl_info->image[n]->x_resolution))+0.5);
height=(size_t) (y_resolution*msl_info->image[n]->rows/
(factor*(msl_info->image[n]->y_resolution == 0.0 ? DefaultResolution :
msl_info->image[n]->y_resolution))+0.5);
resample_image=ResizeImage(msl_info->image[n],width,height,
msl_info->image[n]->filter,msl_info->image[n]->blur,
&msl_info->image[n]->exception);
if (resample_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=resample_image;
}
break;
}
if (LocaleCompare((const char *) tag,"resize") == 0)
{
double
blur;
FilterTypes
filter;
Image
*resize_image;
/*
Resize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
filter=UndefinedFilter;
blur=1.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filter") == 0)
{
option=ParseCommandOption(MagickFilterOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
filter=(FilterTypes) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"support") == 0)
{
blur=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
resize_image=ResizeImage(msl_info->image[n],geometry.width,
geometry.height,filter,blur,&msl_info->image[n]->exception);
if (resize_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=resize_image;
break;
}
if (LocaleCompare((const char *) tag,"roll") == 0)
{
Image
*roll_image;
/*
Roll image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y,
&msl_info->image[n]->exception);
if (roll_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=roll_image;
break;
}
else if (LocaleCompare((const char *) tag,"roll") == 0)
{
/* init the values */
width=msl_info->image[n]->columns;
height=msl_info->image[n]->rows;
x = y = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
(void) ParseMetaGeometry(value,&x,&y,&width,&height);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
x = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
y = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
newImage=RollImage(msl_info->image[n], x, y, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
if (LocaleCompare((const char *) tag,"rotate") == 0)
{
Image
*rotate_image;
/*
Rotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
rotate_image=RotateImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (rotate_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=rotate_image;
break;
}
else if (LocaleCompare((const char *) tag,"rotate") == 0)
{
/* init the values */
double degrees = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
degrees = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
newImage=RotateImage(msl_info->image[n], degrees, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'S':
case 's':
{
if (LocaleCompare((const char *) tag,"sample") == 0)
{
Image
*sample_image;
/*
Sample image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
sample_image=SampleImage(msl_info->image[n],geometry.width,
geometry.height,&msl_info->image[n]->exception);
if (sample_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=sample_image;
break;
}
if (LocaleCompare((const char *) tag,"scale") == 0)
{
Image
*scale_image;
/*
Scale image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
scale_image=ScaleImage(msl_info->image[n],geometry.width,
geometry.height,&msl_info->image[n]->exception);
if (scale_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=scale_image;
break;
}
if (LocaleCompare((const char *) tag,"segment") == 0)
{
ColorspaceType
colorspace;
MagickBooleanType
verbose;
/*
Segment image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=1.0;
geometry_info.sigma=1.5;
colorspace=sRGBColorspace;
verbose=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"cluster-threshold") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
option=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,
"UnrecognizedColorspaceType",value);
colorspace=(ColorspaceType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.5;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"smoothing-threshold") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SegmentImage(msl_info->image[n],colorspace,verbose,
geometry_info.rho,geometry_info.sigma);
break;
}
else if (LocaleCompare((const char *) tag, "set") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"clip-mask") == 0)
{
for (j=0; j < msl_info->n; j++)
{
const char
*property;
property=GetImageProperty(msl_info->attributes[j],"id");
if (LocaleCompare(property,value) == 0)
{
SetImageMask(msl_info->image[n],msl_info->image[j]);
break;
}
}
break;
}
if (LocaleCompare(keyword,"clip-path") == 0)
{
for (j=0; j < msl_info->n; j++)
{
const char
*property;
property=GetImageProperty(msl_info->attributes[j],"id");
if (LocaleCompare(property,value) == 0)
{
SetImageClipMask(msl_info->image[n],msl_info->image[j]);
break;
}
}
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=(ColorspaceType) ParseCommandOption(
MagickColorspaceOptions,MagickFalse,value);
if (colorspace < 0)
ThrowMSLException(OptionError,"UnrecognizedColorspace",
value);
(void) TransformImageColorspace(msl_info->image[n],
(ColorspaceType) colorspace);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
flags=ParseGeometry(value,&geometry_info);
msl_info->image[n]->x_resolution=geometry_info.rho;
msl_info->image[n]->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
msl_info->image[n]->y_resolution=
msl_info->image[n]->x_resolution;
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword, "opacity") == 0)
{
ssize_t opac = OpaqueOpacity,
len = (ssize_t) strlen( value );
if (value[len-1] == '%') {
char tmp[100];
(void) CopyMagickString(tmp,value,len);
opac = StringToLong( tmp );
opac = (int)(QuantumRange * ((float)opac/100));
} else
opac = StringToLong( value );
(void) SetImageOpacity( msl_info->image[n], (Quantum) opac );
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword, "page") == 0)
{
char
page[MaxTextExtent];
const char
*image_option;
MagickStatusType
flags;
RectangleInfo
geometry;
(void) ResetMagickMemory(&geometry,0,sizeof(geometry));
image_option=GetImageArtifact(msl_info->image[n],"page");
if (image_option != (const char *) NULL)
flags=ParseAbsoluteGeometry(image_option,&geometry);
flags=ParseAbsoluteGeometry(value,&geometry);
(void) FormatLocaleString(page,MaxTextExtent,"%.20gx%.20g",
(double) geometry.width,(double) geometry.height);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
(void) FormatLocaleString(page,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,
(double) geometry.height,(double) geometry.x,(double)
geometry.y);
(void) SetImageOption(msl_info->image_info[n],keyword,page);
msl_info->image_info[n]->page=GetPageGeometry(page);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"shade") == 0)
{
Image
*shade_image;
MagickBooleanType
gray;
/*
Shade image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
gray=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"azimuth") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"elevation") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
if (LocaleCompare(keyword,"gray") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
gray=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (shade_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shade_image;
break;
}
if (LocaleCompare((const char *) tag,"shadow") == 0)
{
Image
*shadow_image;
/*
Shear image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
geometry_info.rho=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry_info.xi=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry_info.psi=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5),(ssize_t)
ceil(geometry_info.psi-0.5),&msl_info->image[n]->exception);
if (shadow_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shadow_image;
break;
}
if (LocaleCompare((const char *) tag,"sharpen") == 0)
{
double radius = 0.0,
sigma = 1.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/*
NOTE: sharpen can have no attributes, since we use all the defaults!
*/
if (attributes != (const xmlChar **) NULL)
{
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'R':
case 'r':
{
if (LocaleCompare(keyword, "radius") == 0)
{
radius = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
sigma = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
}
/*
sharpen image.
*/
{
Image
*newImage;
newImage=SharpenImage(msl_info->image[n],radius,sigma,&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
else if (LocaleCompare((const char *) tag,"shave") == 0)
{
/* init the values */
width = height = 0;
x = y = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
(void) ParseMetaGeometry(value,&x,&y,&width,&height);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
height = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
width = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
RectangleInfo
rectInfo;
rectInfo.height = height;
rectInfo.width = width;
rectInfo.x = x;
rectInfo.y = y;
newImage=ShaveImage(msl_info->image[n], &rectInfo,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
if (LocaleCompare((const char *) tag,"shear") == 0)
{
Image
*shear_image;
/*
Shear image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->background_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shear_image=ShearImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (shear_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shear_image;
break;
}
if (LocaleCompare((const char *) tag,"signature") == 0)
{
/*
Signature image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SignatureImage(msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"solarize") == 0)
{
/*
Solarize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=QuantumRange/2.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"threshold") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SolarizeImage(msl_info->image[n],geometry_info.rho);
break;
}
if (LocaleCompare((const char *) tag,"spread") == 0)
{
Image
*spread_image;
/*
Spread image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
spread_image=SpreadImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (spread_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=spread_image;
break;
}
else if (LocaleCompare((const char *) tag,"stegano") == 0)
{
Image *
watermark = (Image*) NULL;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
{
for (j=0; j<msl_info->n;j++)
{
const char *
theAttr = GetImageProperty(msl_info->attributes[j], "id");
if (theAttr && LocaleCompare(theAttr, value) == 0)
{
watermark = msl_info->image[j];
break;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
if ( watermark != (Image*) NULL )
{
Image
*newImage;
newImage=SteganoImage(msl_info->image[n], watermark, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
} else
ThrowMSLException(OptionError,"MissingWatermarkImage",keyword);
}
else if (LocaleCompare((const char *) tag,"stereo") == 0)
{
Image *
stereoImage = (Image*) NULL;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
{
for (j=0; j<msl_info->n;j++)
{
const char *
theAttr = GetImageProperty(msl_info->attributes[j], "id");
if (theAttr && LocaleCompare(theAttr, value) == 0)
{
stereoImage = msl_info->image[j];
break;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
if ( stereoImage != (Image*) NULL )
{
Image
*newImage;
newImage=StereoImage(msl_info->image[n], stereoImage, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
} else
ThrowMSLException(OptionError,"Missing stereo image",keyword);
}
if (LocaleCompare((const char *) tag,"strip") == 0)
{
/*
Strip image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
(void) StripImage(msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"swap") == 0)
{
Image
*p,
*q,
*swap;
ssize_t
index,
swap_index;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
index=(-1);
swap_index=(-2);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"indexes") == 0)
{
flags=ParseGeometry(value,&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) == 0)
swap_index=(ssize_t) geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
/*
Swap images.
*/
p=GetImageFromList(msl_info->image[n],index);
q=GetImageFromList(msl_info->image[n],swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag);
break;
}
swap=CloneImage(p,0,0,MagickTrue,&p->exception);
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,&q->exception));
ReplaceImageInList(&q,swap);
msl_info->image[n]=GetFirstImageInList(q);
break;
}
if (LocaleCompare((const char *) tag,"swirl") == 0)
{
Image
*swirl_image;
/*
Swirl image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (swirl_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=swirl_image;
break;
}
if (LocaleCompare((const char *) tag,"sync") == 0)
{
/*
Sync image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SyncImage(msl_info->image[n]);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'T':
case 't':
{
if (LocaleCompare((const char *) tag,"map") == 0)
{
Image
*texture_image;
/*
Texture image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
texture_image=NewImageList();
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
texture_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) TextureImage(msl_info->image[n],texture_image);
texture_image=DestroyImage(texture_image);
break;
}
else if (LocaleCompare((const char *) tag,"threshold") == 0)
{
/* init the values */
double threshold = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'T':
case 't':
{
if (LocaleCompare(keyword,"threshold") == 0)
{
threshold = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
BilevelImageChannel(msl_info->image[n],
(ChannelType) ((ssize_t) (CompositeChannels &~ (ssize_t) OpacityChannel)),
threshold);
break;
}
}
else if (LocaleCompare((const char *) tag, "transparent") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"color") == 0)
{
MagickPixelPacket
target;
(void) QueryMagickColor(value,&target,exception);
(void) TransparentPaintImage(msl_info->image[n],&target,
TransparentOpacity,MagickFalse);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
else if (LocaleCompare((const char *) tag, "trim") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
/* no attributes here */
/* process the image */
{
Image
*newImage;
RectangleInfo
rectInfo;
/* all zeros on a crop == trim edges! */
rectInfo.height = rectInfo.width = 0;
rectInfo.x = rectInfo.y = 0;
newImage=CropImage(msl_info->image[n],&rectInfo, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'W':
case 'w':
{
if (LocaleCompare((const char *) tag,"write") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filename") == 0)
{
(void) CopyMagickString(msl_info->image[n]->filename,value,
MaxTextExtent);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
/* process */
{
*msl_info->image_info[n]->magick='\0';
(void) WriteImage(msl_info->image_info[n], msl_info->image[n]);
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
break;
}
}
if ( value != NULL )
value=DestroyString(value);
exception=DestroyExceptionInfo(exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," )");
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The MSL interpreter in ImageMagick before 6.9.6-4 allows remote attackers to cause a denial of service (segmentation fault and application crash) via a crafted XML file.
Commit Message: Prevent fault in MSL interpreter
|
Medium
| 168,537
|
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: std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
auto border = std::make_unique<views::BubbleBorder>(
views::BubbleBorder::NONE, views::BubbleBorder::SMALL_SHADOW,
SK_ColorWHITE);
border->SetCornerRadius(GetCornerRadius());
border->set_md_shadow_elevation(
ChromeLayoutProvider::Get()->GetShadowElevationMetric(
views::EMPHASIS_MEDIUM));
return border;
}
Vulnerability Type:
CWE ID: CWE-416
Summary: Blink in Google Chrome prior to 54.0.2840.59 for Windows, Mac, and Linux; 54.0.2840.85 for Android incorrectly allowed reentrance of FrameView::updateLifecyclePhasesInternal(), which allowed a remote attacker to perform an out of bounds memory read via crafted HTML pages.
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <rkaplow@chromium.org>
Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org>
Reviewed-by: Fabio Tirelo <ftirelo@chromium.org>
Reviewed-by: Tommy Martino <tmartino@chromium.org>
Commit-Queue: Mathieu Perreault <mathp@chromium.org>
Cr-Commit-Position: refs/heads/master@{#621360}
|
Medium
| 172,094
|
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 ChromeMockRenderThread::OnUpdatePrintSettings(
int document_cookie,
const base::DictionaryValue& job_settings,
PrintMsg_PrintPages_Params* params) {
std::string dummy_string;
int margins_type = 0;
if (!job_settings.GetBoolean(printing::kSettingLandscape, NULL) ||
!job_settings.GetBoolean(printing::kSettingCollate, NULL) ||
!job_settings.GetInteger(printing::kSettingColor, NULL) ||
!job_settings.GetBoolean(printing::kSettingPrintToPDF, NULL) ||
!job_settings.GetBoolean(printing::kIsFirstRequest, NULL) ||
!job_settings.GetString(printing::kSettingDeviceName, &dummy_string) ||
!job_settings.GetInteger(printing::kSettingDuplexMode, NULL) ||
!job_settings.GetInteger(printing::kSettingCopies, NULL) ||
!job_settings.GetString(printing::kPreviewUIAddr, &dummy_string) ||
!job_settings.GetInteger(printing::kPreviewRequestID, NULL) ||
!job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) {
return;
}
if (printer_.get()) {
const ListValue* page_range_array;
printing::PageRanges new_ranges;
if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) {
for (size_t index = 0; index < page_range_array->GetSize(); ++index) {
const base::DictionaryValue* dict;
if (!page_range_array->GetDictionary(index, &dict))
continue;
printing::PageRange range;
if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) ||
!dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) {
continue;
}
range.from--;
range.to--;
new_ranges.push_back(range);
}
}
std::vector<int> pages(printing::PageRange::GetPages(new_ranges));
printer_->UpdateSettings(document_cookie, params, pages, margins_type);
}
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The IPC implementation in Google Chrome before 22.0.1229.79 allows attackers to obtain potentially sensitive information about memory addresses via unspecified vectors.
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 170,854
|
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 PermissionsRequestFunction::RunImpl() {
if (!user_gesture() && !ignore_user_gesture_for_tests) {
error_ = kUserGestureRequiredError;
return false;
}
scoped_ptr<Request::Params> params(Request::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
requested_permissions_ =
helpers::UnpackPermissionSet(params->permissions, &error_);
if (!requested_permissions_.get())
return false;
extensions::ExtensionPrefs* prefs =
profile()->GetExtensionService()->extension_prefs();
APIPermissionSet apis = requested_permissions_->apis();
for (APIPermissionSet::const_iterator i = apis.begin();
i != apis.end(); ++i) {
if (!i->info()->supports_optional()) {
error_ = ErrorUtils::FormatErrorMessage(
kNotWhitelistedError, i->name());
return false;
}
}
scoped_refptr<extensions::PermissionSet>
manifest_required_requested_permissions =
PermissionSet::ExcludeNotInManifestPermissions(
requested_permissions_.get());
if (!GetExtension()->optional_permission_set()->Contains(
*manifest_required_requested_permissions)) {
error_ = kNotInOptionalPermissionsError;
results_ = Request::Results::Create(false);
return false;
}
scoped_refptr<const PermissionSet> granted =
prefs->GetGrantedPermissions(GetExtension()->id());
if (granted.get() && granted->Contains(*requested_permissions_)) {
PermissionsUpdater perms_updater(profile());
perms_updater.AddPermissions(GetExtension(), requested_permissions_.get());
results_ = Request::Results::Create(true);
SendResponse(true);
return true;
}
requested_permissions_ = PermissionSet::CreateDifference(
requested_permissions_.get(), granted.get());
AddRef(); // Balanced in InstallUIProceed() / InstallUIAbort().
bool has_no_warnings = requested_permissions_->GetWarningMessages(
GetExtension()->GetType()).empty();
if (auto_confirm_for_tests == PROCEED || has_no_warnings) {
InstallUIProceed();
} else if (auto_confirm_for_tests == ABORT) {
InstallUIAbort(true);
} else {
CHECK_EQ(DO_NOT_SKIP, auto_confirm_for_tests);
install_ui_.reset(new ExtensionInstallPrompt(GetAssociatedWebContents()));
install_ui_->ConfirmPermissions(
this, GetExtension(), requested_permissions_.get());
}
return true;
}
Vulnerability Type:
CWE ID: CWE-264
Summary: The extension functionality in Google Chrome before 26.0.1410.43 does not verify that use of the permissions API is consistent with file permissions, which has unspecified impact and attack vectors.
Commit Message: Check prefs before allowing extension file access in the permissions API.
R=mpcomplete@chromium.org
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 171,444
|
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 CSSStyleSheet::CanAccessRules() const {
if (enable_rule_access_for_inspector_)
return true;
if (is_inline_stylesheet_)
return true;
KURL base_url = contents_->BaseURL();
if (base_url.IsEmpty())
return true;
Document* document = OwnerDocument();
if (!document)
return true;
if (document->GetSecurityOrigin()->CanReadContent(base_url))
return true;
if (allow_rule_access_from_origin_ &&
document->GetSecurityOrigin()->CanAccess(
allow_rule_access_from_origin_.get())) {
return true;
}
return false;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Insufficient origin checks for CSS content in Blink in Google Chrome prior to 68.0.3440.75 allowed a remote attacker to leak cross-origin data via a crafted HTML page.
Commit Message: Disallow access to opaque CSS responses.
Bug: 848786
Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec
Reviewed-on: https://chromium-review.googlesource.com/1088335
Reviewed-by: Kouhei Ueno <kouhei@chromium.org>
Commit-Queue: Matt Falkenhagen <falken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#565537}
|
Medium
| 173,153
|
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: PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
: PrintingContext(app_locale) {
#else
: PrintingContext(app_locale),
print_dialog_(NULL) {
#endif
}
PrintingContextCairo::~PrintingContextCairo() {
ReleaseContext();
#if !defined(OS_CHROMEOS)
if (print_dialog_)
print_dialog_->ReleaseDialog();
#endif
}
#if !defined(OS_CHROMEOS)
void PrintingContextCairo::SetCreatePrintDialogFunction(
PrintDialogGtkInterface* (*create_dialog_func)(
PrintingContextCairo* context)) {
DCHECK(create_dialog_func);
DCHECK(!create_dialog_func_);
create_dialog_func_ = create_dialog_func;
}
void PrintingContextCairo::PrintDocument(const Metafile* metafile) {
DCHECK(print_dialog_);
DCHECK(metafile);
print_dialog_->PrintDocument(metafile, document_name_);
}
#endif // !defined(OS_CHROMEOS)
void PrintingContextCairo::AskUserForSettings(
gfx::NativeView parent_view,
int max_pages,
bool has_selection,
PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
callback->Run(OK);
#else
print_dialog_->ShowDialog(callback);
#endif // defined(OS_CHROMEOS)
}
PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
DCHECK(!in_print_job_);
ResetSettings();
#if defined(OS_CHROMEOS)
int dpi = 300;
gfx::Size physical_size_device_units;
gfx::Rect printable_area_device_units;
int32_t width = 0;
int32_t height = 0;
UErrorCode error = U_ZERO_ERROR;
ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
if (error != U_ZERO_ERROR) {
LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
<< error;
width = static_cast<int>(8.5 * dpi);
height = static_cast<int>(11 * dpi);
} else {
width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
}
physical_size_device_units.SetSize(width, height);
printable_area_device_units.SetRect(
static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
height - (PrintSettingsInitializerGtk::kTopMarginInInch +
PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);
settings_.set_dpi(dpi);
settings_.SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
#else
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
print_dialog_->UseDefaultSettings();
#endif // defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
PrintingContext::Result PrintingContextCairo::InitWithSettings(
const PrintSettings& settings) {
DCHECK(!in_print_job_);
settings_ = settings;
return OK;
}
PrintingContext::Result PrintingContextCairo::NewDocument(
const string16& document_name) {
DCHECK(!in_print_job_);
in_print_job_ = true;
#if !defined(OS_CHROMEOS)
document_name_ = document_name;
#endif // !defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::NewPage() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::PageDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::DocumentDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
ResetSettings();
return OK;
}
void PrintingContextCairo::Cancel() {
abort_printing_ = true;
in_print_job_ = false;
}
void PrintingContextCairo::ReleaseContext() {
}
gfx::NativeDrawingContext PrintingContextCairo::context() const {
return NULL;
}
} // namespace printing
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 15.0.874.120 allows user-assisted remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to editing.
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
|
Medium
| 170,266
|
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 struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,
struct nfs4_state_owner *sp, int flags,
const struct iattr *attrs)
{
struct dentry *parent = dget_parent(path->dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);
if (p->o_arg.seqid == NULL)
goto err_free;
p->path.mnt = mntget(path->mnt);
p->path.dentry = dget(path->dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags,
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id = sp->so_owner_id.id;
p->o_arg.name = &p->path.dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (flags & O_EXCL) {
u32 *s = (u32 *) p->o_arg.u.verifier.data;
s[0] = jiffies;
s[1] = current->pid;
} else if (flags & O_CREAT) {
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
}
Vulnerability Type: DoS
CWE ID:
Summary: The encode_share_access function in fs/nfs/nfs4xdr.c in the Linux kernel before 2.6.29 allows local users to cause a denial of service (BUG and system crash) by using the mknod system call with a pathname on an NFSv4 filesystem.
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
|
Low
| 165,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: void BluetoothDeviceChromeOS::RequestPasskey(
const dbus::ObjectPath& device_path,
const PasskeyCallback& callback) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": RequestPasskey";
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_REQUEST_PASSKEY,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
DCHECK(passkey_callback_.is_null());
passkey_callback_ = callback;
pairing_delegate_->RequestPasskey(this);
pairing_delegate_used_ = true;
}
Vulnerability Type:
CWE ID:
Summary: Google Chrome before 28.0.1500.71 does not properly prevent pop-under windows, which allows remote attackers to have an unspecified impact via a crafted web site.
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 171,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: image_transform_png_set_@_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
this->next->mod(this->next, that, pp, display);
}
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,601
|
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_METHOD(Phar, webPhar)
{
zval *mimeoverride = NULL, *rewrite = NULL;
char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0;
char *fname, *path_info, *mime_type = NULL, *entry, *pt;
const char *basename;
int fname_len, entry_len, code, index_php_len = 0, not_cgi;
phar_archive_data *phar = NULL;
phar_entry_info *info = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
fname = (char*)zend_get_executed_filename(TSRMLS_C);
fname_len = strlen(fname);
if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
return;
}
/* retrieve requested file within phar */
if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) {
return;
}
#ifdef PHP_WIN32
fname = estrndup(fname, fname_len);
phar_unixify_path_separators(fname, fname_len);
#endif
basename = zend_memrchr(fname, '/', fname_len);
if (!basename) {
basename = fname;
} else {
++basename;
}
if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) {
if (PG(http_globals)[TRACK_VARS_SERVER]) {
HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
zval **z_script_name, **z_path_info;
if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) ||
IS_STRING != Z_TYPE_PP(z_script_name) ||
!strstr(Z_STRVAL_PP(z_script_name), basename)) {
return;
}
if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) &&
IS_STRING == Z_TYPE_PP(z_path_info)) {
entry_len = Z_STRLEN_PP(z_path_info);
entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len);
path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1);
memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1);
free_pathinfo = 1;
} else {
entry_len = 0;
entry = estrndup("", 0);
path_info = Z_STRVAL_PP(z_script_name);
}
pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
} else {
char *testit;
testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
if (!(pt = strstr(testit, basename))) {
efree(testit);
return;
}
path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
if (path_info) {
entry = path_info;
entry_len = strlen(entry);
spprintf(&path_info, 0, "%s%s", testit, path_info);
free_pathinfo = 1;
} else {
path_info = testit;
free_pathinfo = 1;
entry = estrndup("", 0);
entry_len = 0;
}
pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
}
not_cgi = 0;
} else {
path_info = SG(request_info).request_uri;
if (!(pt = strstr(path_info, basename))) {
/* this can happen with rewrite rules - and we have no idea what to do then, so return */
return;
}
entry_len = strlen(path_info);
entry_len -= (pt - path_info) + (fname_len - (basename - fname));
entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
not_cgi = 1;
}
if (rewrite) {
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *params, *retval_ptr, **zp[1];
MAKE_STD_ZVAL(params);
ZVAL_STRINGL(params, entry, entry_len, 1);
zp[0] = ¶ms;
#if PHP_VERSION_ID < 50300
if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) {
#else
if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) {
#endif
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback");
if (free_pathinfo) {
efree(path_info);
}
return;
}
fci.param_count = 1;
fci.params = zp;
#if PHP_VERSION_ID < 50300
++(params->refcount);
#else
Z_ADDREF_P(params);
#endif
fci.retval_ptr_ptr = &retval_ptr;
if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) {
if (!EG(exception)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback");
}
if (free_pathinfo) {
efree(path_info);
}
return;
}
if (!fci.retval_ptr_ptr || !retval_ptr) {
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
switch (Z_TYPE_P(retval_ptr)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(retval_ptr TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
efree(entry);
if (fci.retval_ptr_ptr != &retval_ptr) {
entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr));
entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr);
} else {
entry = Z_STRVAL_P(retval_ptr);
entry_len = Z_STRLEN_P(retval_ptr);
}
break;
case IS_BOOL:
phar_do_403(entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
return;
default:
efree(retval_ptr);
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
}
if (entry_len) {
phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC);
}
if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
efree(entry);
/* direct request */
if (index_php_len) {
entry = index_php;
entry_len = index_php_len;
if (entry[0] != '/') {
spprintf(&entry, 0, "/%s", index_php);
++entry_len;
}
} else {
/* assume "index.php" is starting point */
entry = estrndup("/index.php", sizeof("/index.php"));
entry_len = sizeof("/index.php")-1;
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
} else {
char *tmp = NULL, sa = '\0';
sapi_header_line ctr = {0};
ctr.response_code = 301;
ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
ctr.line = "HTTP/1.1 301 Moved Permanently";
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
if (not_cgi) {
tmp = strstr(path_info, basename) + fname_len;
sa = *tmp;
*tmp = '\0';
}
ctr.response_code = 0;
if (path_info[strlen(path_info)-1] == '/') {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
} else {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
}
if (not_cgi) {
*tmp = sa;
}
if (free_pathinfo) {
efree(path_info);
}
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
sapi_send_headers(TSRMLS_C);
efree(ctr.line);
zend_bailout();
}
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
#ifdef PHP_WIN32
efree(fname);
#endif
zend_bailout();
}
if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
const char *ext = zend_memrchr(entry, '.', entry_len);
zval **val;
if (ext) {
++ext;
if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) {
switch (Z_TYPE_PP(val)) {
case IS_LONG:
if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) {
mime_type = "";
code = Z_LVAL_PP(val);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
break;
case IS_STRING:
mime_type = Z_STRVAL_PP(val);
code = PHAR_MIME_OTHER;
break;
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
}
}
}
if (!mime_type) {
code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC);
}
ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC);
}
/* }}} */
/* {{{ proto void Phar::mungServer(array munglist)
* Defines a list of up to 4 $_SERVER variables that should be modified for execution
* to mask the presence of the phar archive. This should be used in conjunction with
* Phar::webPhar(), and has no effect otherwise
* SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
*/
PHP_METHOD(Phar, mungServer)
{
zval *mungvalues;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) {
return;
}
if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
phar_request_initialize(TSRMLS_C);
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) {
zval **data = NULL;
if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()");
return;
}
if (Z_TYPE_PP(data) != IS_STRING) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF;
}
if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) {
if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI;
}
if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME;
}
}
if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME;
}
}
}
/* }}} */
/* {{{ proto void Phar::interceptFileFuncs()
* instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
* and return stat on files within the phar for relative paths
*
* Once called, this cannot be reversed, and continue until the end of the request.
*
* This allows legacy scripts to be pharred unmodified
*/
PHP_METHOD(Phar, interceptFileFuncs)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phar_intercept_functions(TSRMLS_C);
}
/* }}} */
/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
* Return a stub that can be used to run a phar-based archive without the phar extension
* indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
* is the web startup filename, and also defaults to "index.php"
*/
PHP_METHOD(Phar, createDefaultStub)
{
char *index = NULL, *webindex = NULL, *stub, *error;
int index_len = 0, webindex_len = 0;
size_t stub_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
return;
}
stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
return;
}
RETURN_STRINGL(stub, stub_len, 0);
}
/* }}} */
/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
* Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar, mapPhar)
{
char *alias = NULL, *error;
int alias_len = 0;
long dataoffset = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
* Loads any phar archive with an alias */
PHP_METHOD(Phar, loadPhar)
{
char *fname, *alias = NULL, *error;
int fname_len, alias_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto string Phar::apiVersion()
* Returns the api version */
PHP_METHOD(Phar, apiVersion)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1);
}
/* }}}*/
/* {{{ proto bool Phar::canCompress([int method])
* Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar, canCompress)
{
long method = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
switch (method) {
case PHAR_ENT_COMPRESSED_GZ:
if (PHAR_G(has_zlib)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
case PHAR_ENT_COMPRESSED_BZ2:
if (PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
default:
if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
}
/* }}} */
/* {{{ proto bool Phar::canWrite()
* Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar, canWrite)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(!PHAR_G(readonly));
}
/* }}} */
/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
* Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar, isValidPharFilename)
{
char *fname;
const char *ext_str;
int fname_len, ext_len, is_executable;
zend_bool executable = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) {
return;
}
is_executable = executable;
RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS);
}
/* }}} */
#if HAVE_SPL
/**
* from spl_directory
*/
static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar = (phar_archive_data *) object->oth;
if (!phar->is_persistent) {
phar_archive_delref(phar TSRMLS_CC);
}
object->oth = NULL;
}
/* }}} */
/**
* from spl_directory
*/
static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
}
/* }}} */
static spl_other_handler phar_spl_foreign_handler = {
phar_spl_foreign_dtor,
phar_spl_foreign_clone
};
#endif /* HAVE_SPL */
/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]])
* Construct a Phar archive object
*
* proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
* Construct a PharData archive object
*
* This function is used as the constructor for both the Phar and PharData
* classes, hence the two prototypes above.
*/
PHP_METHOD(Phar, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
/* }}} */
/* {{{ proto array Phar::getSupportedSignatures()
* Return array of supported signature types
*/
PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
/* }}} */
/* {{{ proto array Phar::getSupportedCompression()
* Return array of supported comparession algorithms
*/
PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
/* }}} */
/* {{{ proto array Phar::unlinkArchive(string archive)
* Completely remove a phar archive from memory and disk
*/
PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
int fname_len, zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename(TSRMLS_C);
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar TSRMLS_CC);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
/* }}} */
#if HAVE_SPL
#define PHAR_ARCHIVE_OBJECT() \
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
if (!phar_obj->arc.archive) { \
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
"Cannot call method on an uninitialized Phar object"); \
return; \
}
/* {{{ proto void Phar::__destruct()
* if persistent, remove from the cache
*/
PHP_METHOD(Phar, __destruct)
{
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) {
zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive));
}
}
/* }}} */
struct _phar_t {
phar_archive_object *p;
zend_class_entry *c;
char *b;
uint l;
zval *ret;
int count;
php_stream *fp;
};
static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */
{
zval **value;
zend_uchar key_type;
zend_bool close_fp = 1;
ulong int_key;
struct _phar_t *p_obj = (struct _phar_t*) puser;
uint str_key_len, base_len = p_obj->l, fname_len;
phar_entry_data *data;
php_stream *fp;
size_t contents_len;
char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL;
phar_zstr key;
char *str_key;
zend_class_entry *ce = p_obj->c;
phar_archive_object *phar_obj = p_obj->p;
char *str = "[stream]";
iter->funcs->get_current_data(iter, &value TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (!value) {
/* failure in get_current_data */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (Z_TYPE_PP(value)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(*(value) TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
break;
case IS_RESOURCE:
php_stream_from_zval_no_verify(fp, value);
if (!fp) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') {
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
close_fp = 0;
opened = (char *) estrndup(str, sizeof("[stream]") - 1);
goto after_open_fp;
case IS_OBJECT:
if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) {
char *test = NULL;
zval dummy;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC);
if (!base_len) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (intern->type) {
case SPL_FS_DIR:
#if PHP_VERSION_ID >= 60000
test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s;
#elif PHP_VERSION_ID >= 50300
test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC);
#else
test = intern->path;
#endif
fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC);
if (Z_BVAL(dummy)) {
/* ignore directories */
efree(fname);
return ZEND_HASH_APPLY_KEEP;
}
test = expand_filepath(fname, NULL TSRMLS_CC);
efree(fname);
if (test) {
fname = test;
fname_len = strlen(fname);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
save = fname;
goto phar_spl_fileinfo;
case SPL_FS_INFO:
case SPL_FS_FILE:
#if PHP_VERSION_ID >= 60000
if (intern->file_name_type == IS_UNICODE) {
zval zv;
INIT_ZVAL(zv);
Z_UNIVAL(zv) = intern->file_name;
Z_UNILEN(zv) = intern->file_name_len;
Z_TYPE(zv) = IS_UNICODE;
zval_copy_ctor(&zv);
zval_unicode_to_string(&zv TSRMLS_CC);
fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC);
ezfree(Z_UNIVAL(zv));
} else {
fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC);
}
#else
fname = expand_filepath(intern->file_name, NULL TSRMLS_CC);
#endif
if (!fname) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
fname_len = strlen(fname);
save = fname;
goto phar_spl_fileinfo;
}
}
/* fall-through */
default:
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
fname = Z_STRVAL_PP(value);
fname_len = Z_STRLEN_PP(value);
phar_spl_fileinfo:
if (base_len) {
temp = expand_filepath(base, NULL TSRMLS_CC);
if (!temp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
if (save) {
efree(save);
}
return ZEND_HASH_APPLY_STOP;
}
base = temp;
base_len = strlen(base);
if (strstr(fname, base)) {
str_key_len = fname_len - base_len;
if (str_key_len <= 0) {
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_KEEP;
}
str_key = fname + base_len;
if (*str_key == '/' || *str_key == '\\') {
str_key++;
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base);
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
} else {
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') str_key_len--;
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
/* try to open source file, then create internal phar file and copy contents */
fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
if (!fp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
after_open_fp:
if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
/* silently skip any files that would be added to the magic .phar directory */
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
if (opened) {
efree(opened);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_KEEP;
}
if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error);
efree(error);
if (save) {
efree(save);
}
if (opened) {
efree(opened);
}
if (temp) {
efree(temp);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_STOP;
} else {
if (error) {
efree(error);
}
/* convert to PHAR_UFP */
if (data->internal_file->fp_type == PHAR_MOD) {
php_stream_close(data->internal_file->fp);
}
data->internal_file->fp = NULL;
data->internal_file->fp_type = PHAR_UFP;
data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
data->fp = NULL;
phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
php_stream_tell(p_obj->fp) - data->internal_file->offset;
}
if (close_fp) {
php_stream_close(fp);
}
add_assoc_string(p_obj->ret, str_key, opened, 0);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
phar_entry_delref(data TSRMLS_CC);
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
* Construct a phar archive from an existing directory, recursively.
* Optional second parameter is a regular expression for filtering directory contents.
*
* Return value is an array mapping phar index to actual files added.
*/
PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
* Construct a phar archive from an iterator. The iterator must return a series of strings
* that are full paths to files that should be added to the phar. The iterator key should
* be the path that the file will have within the phar archive.
*
* If base directory is specified, then the key will be ignored, and instead the portion of
* the current value minus the base directory will be used
*
* Returned is an array mapping phar index to actual file added
*/
PHP_METHOD(Phar, buildFromIterator)
{
zval *obj;
char *error;
uint base_len = 0;
char *base = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
array_init(return_value);
pass.c = Z_OBJCE_P(obj);
pass.p = phar_obj;
pass.b = base;
pass.l = base_len;
pass.ret = return_value;
pass.count = 0;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto int Phar::count()
* Returns the number of entries in the Phar archive
*/
PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
/* }}} */
/* {{{ proto bool Phar::isFileFormat(int format)
* Returns true if the phar archive is based on the tar/zip/phar file format depending
* on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
*/
PHP_METHOD(Phar, isFileFormat)
{
long type;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) {
RETURN_FALSE;
}
switch (type) {
case PHAR_FORMAT_TAR:
RETURN_BOOL(phar_obj->arc.archive->is_tar);
case PHAR_FORMAT_ZIP:
RETURN_BOOL(phar_obj->arc.archive->is_zip);
case PHAR_FORMAT_PHAR:
RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip);
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified");
}
}
/* }}} */
static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
{
char *error;
off_t offset;
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
}
return FAILURE;
}
/* copy old contents in entirety */
phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC);
offset = php_stream_tell(fp);
link = phar_get_link_source(entry TSRMLS_CC);
if (!link) {
link = entry;
}
if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
return FAILURE;
}
if (entry->fp_type == PHAR_MOD) {
/* save for potential restore on error */
entry->cfp = entry->fp;
entry->fp = NULL;
}
/* set new location of file contents */
entry->fp_type = PHAR_FP;
entry->offset = offset;
return SUCCESS;
}
/* }}} */
static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
efree(oldpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry, newentry;
zval *ret;
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
/* set whole-archive compression and type from parameter */
phar->flags = flags;
phar->is_data = source->is_data;
switch (convert) {
case PHAR_FORMAT_TAR:
phar->is_tar = 1;
break;
case PHAR_FORMAT_ZIP:
phar->is_zip = 1;
break;
default:
phar->is_data = 0;
break;
}
zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_init(&phar->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&phar->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
phar->fp = php_stream_fopen_tmpfile();
if (phar->fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file");
return NULL;
}
phar->fname = source->fname;
phar->fname_len = source->fname_len;
phar->is_temporary_alias = source->is_temporary_alias;
phar->alias = source->alias;
if (source->metadata) {
zval *t;
t = source->metadata;
ALLOC_ZVAL(phar->metadata);
*phar->metadata = *t;
zval_copy_ctor(phar->metadata);
#if PHP_VERSION_ID < 50300
phar->metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(phar->metadata, 1);
#endif
phar->metadata_len = 0;
}
/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) {
if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\"", source->fname);
return NULL;
}
newentry = *entry;
if (newentry.link) {
newentry.link = estrdup(newentry.link);
goto no_copy;
}
if (newentry.tmp) {
newentry.tmp = estrdup(newentry.tmp);
goto no_copy;
}
newentry.metadata_str.c = 0;
if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
/* exception already thrown */
return NULL;
}
no_copy:
newentry.filename = estrndup(newentry.filename, newentry.filename_len);
if (newentry.metadata) {
zval *t;
t = newentry.metadata;
ALLOC_ZVAL(newentry.metadata);
*newentry.metadata = *t;
zval_copy_ctor(newentry.metadata);
#if PHP_VERSION_ID < 50300
newentry.metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(newentry.metadata, 1);
#endif
newentry.metadata_str.c = NULL;
newentry.metadata_str.len = 0;
}
newentry.is_zip = phar->is_zip;
newentry.is_tar = phar->is_tar;
if (newentry.is_tar) {
newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
}
newentry.is_modified = 1;
newentry.phar = phar;
newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
phar_set_inode(&newentry TSRMLS_CC);
zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC);
}
if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) {
return ret;
} else {
zend_hash_destroy(&(phar->manifest));
zend_hash_destroy(&(phar->mounted_dirs));
zend_hash_destroy(&(phar->virtual_dirs));
php_stream_close(phar->fp);
efree(phar->fname);
efree(phar);
return NULL;
/* }}} */
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The phar_convert_to_other function in ext/phar/phar_object.c in PHP before 5.4.43, 5.5.x before 5.5.27, and 5.6.x before 5.6.11 does not validate a file pointer before a close operation, which allows remote attackers to cause a denial of service (segmentation fault) or possibly have unspecified other impact via a crafted TAR archive that is mishandled in a Phar::convertToData call.
Commit Message:
|
Low
| 165,290
|
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 ati_remote2_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct usb_host_interface *alt = interface->cur_altsetting;
struct ati_remote2 *ar2;
int r;
if (alt->desc.bInterfaceNumber)
return -ENODEV;
ar2 = kzalloc(sizeof (struct ati_remote2), GFP_KERNEL);
if (!ar2)
return -ENOMEM;
ar2->udev = udev;
ar2->intf[0] = interface;
ar2->ep[0] = &alt->endpoint[0].desc;
ar2->intf[1] = usb_ifnum_to_if(udev, 1);
r = usb_driver_claim_interface(&ati_remote2_driver, ar2->intf[1], ar2);
if (r)
goto fail1;
alt = ar2->intf[1]->cur_altsetting;
ar2->ep[1] = &alt->endpoint[0].desc;
r = ati_remote2_urb_init(ar2);
if (r)
goto fail2;
ar2->channel_mask = channel_mask;
ar2->mode_mask = mode_mask;
r = ati_remote2_setup(ar2, ar2->channel_mask);
if (r)
goto fail2;
usb_make_path(udev, ar2->phys, sizeof(ar2->phys));
strlcat(ar2->phys, "/input0", sizeof(ar2->phys));
strlcat(ar2->name, "ATI Remote Wonder II", sizeof(ar2->name));
r = sysfs_create_group(&udev->dev.kobj, &ati_remote2_attr_group);
if (r)
goto fail2;
r = ati_remote2_input_init(ar2);
if (r)
goto fail3;
usb_set_intfdata(interface, ar2);
interface->needs_remote_wakeup = 1;
return 0;
fail3:
sysfs_remove_group(&udev->dev.kobj, &ati_remote2_attr_group);
fail2:
ati_remote2_urb_cleanup(ar2);
usb_driver_release_interface(&ati_remote2_driver, ar2->intf[1]);
fail1:
kfree(ar2);
return r;
}
Vulnerability Type: DoS
CWE ID:
Summary: The ati_remote2_probe function in drivers/input/misc/ati_remote2.c in the Linux kernel before 4.5.1 allows physically proximate attackers to cause a denial of service (NULL pointer dereference and system crash) via a crafted endpoints value in a USB device descriptor.
Commit Message: Input: ati_remote2 - fix crashes on detecting device with invalid descriptor
The ati_remote2 driver expects at least two interfaces with one
endpoint each. If given malicious descriptor that specify one
interface or no endpoints, it will crash in the probe function.
Ensure there is at least two interfaces and one endpoint for each
interface before using it.
The full disclosure: http://seclists.org/bugtraq/2016/Mar/90
Reported-by: Ralf Spenneberg <ralf@spenneberg.net>
Signed-off-by: Vladis Dronov <vdronov@redhat.com>
Cc: stable@vger.kernel.org
Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
|
Low
| 167,433
|
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 Instance::HandleInputEvent(const pp::InputEvent& event) {
pp::InputEvent event_device_res(event);
{
pp::MouseInputEvent mouse_event(event);
if (!mouse_event.is_null()) {
pp::Point point = mouse_event.GetPosition();
pp::Point movement = mouse_event.GetMovement();
ScalePoint(device_scale_, &point);
ScalePoint(device_scale_, &movement);
mouse_event = pp::MouseInputEvent(
this,
event.GetType(),
event.GetTimeStamp(),
event.GetModifiers(),
mouse_event.GetButton(),
point,
mouse_event.GetClickCount(),
movement);
event_device_res = mouse_event;
}
}
if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) {
pp::MouseInputEvent mouse_event(event_device_res);
pp::Point pos = mouse_event.GetPosition();
EnableAutoscroll(pos);
UpdateCursor(CalculateAutoscroll(pos));
return true;
} else {
DisableAutoscroll();
}
#ifdef ENABLE_THUMBNAILS
if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE)
thumbnails_.SlideOut();
if (thumbnails_.HandleEvent(event_device_res))
return true;
#endif
if (toolbar_->HandleEvent(event_device_res))
return true;
#ifdef ENABLE_THUMBNAILS
if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) {
pp::MouseInputEvent mouse_event(event);
pp::Point pt = mouse_event.GetPosition();
pp::Rect v_scrollbar_rc;
v_scrollbar_->GetLocation(&v_scrollbar_rc);
if (v_scrollbar_rc.Contains(pt) &&
(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) {
thumbnails_.SlideIn();
}
if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() &&
!(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) &&
!thumbnails_.rect().Contains(pt)) {
thumbnails_.SlideOut();
}
}
#endif
pp::InputEvent offset_event(event_device_res);
bool try_engine_first = true;
switch (offset_event.GetType()) {
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
case PP_INPUTEVENT_TYPE_MOUSEUP:
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
case PP_INPUTEVENT_TYPE_MOUSEENTER:
case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
pp::MouseInputEvent mouse_event(event_device_res);
pp::MouseInputEvent mouse_event_dip(event);
pp::Point point = mouse_event.GetPosition();
point.set_x(point.x() - available_area_.x());
offset_event = pp::MouseInputEvent(
this,
event.GetType(),
event.GetTimeStamp(),
event.GetModifiers(),
mouse_event.GetButton(),
point,
mouse_event.GetClickCount(),
mouse_event.GetMovement());
if (!engine_->IsSelecting()) {
if (!IsOverlayScrollbar() &&
!available_area_.Contains(mouse_event.GetPosition())) {
try_engine_first = false;
} else if (IsOverlayScrollbar()) {
pp::Rect temp;
if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) &&
temp.Contains(mouse_event_dip.GetPosition())) ||
(h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) &&
temp.Contains(mouse_event_dip.GetPosition()))) {
try_engine_first = false;
}
}
}
break;
}
default:
break;
}
if (try_engine_first && engine_->HandleEvent(offset_event))
return true;
if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
pp::KeyboardInputEvent keyboard_event(event);
bool no_h_scrollbar = !h_scrollbar_.get();
uint32_t key_code = keyboard_event.GetKeyCode();
bool page_down = no_h_scrollbar && key_code == ui::VKEY_RIGHT;
bool page_up = no_h_scrollbar && key_code == ui::VKEY_LEFT;
if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
bool has_shift =
keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY;
bool key_is_space = key_code == ui::VKEY_SPACE;
page_down |= key_is_space || key_code == ui::VKEY_NEXT;
page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR);
}
if (page_down) {
int page = engine_->GetFirstVisiblePage();
if (engine_->GetPageRect(page).bottom() * zoom_ <=
v_scrollbar_->GetValue())
page++;
ScrollToPage(page + 1);
UpdateCursor(PP_CURSORTYPE_POINTER);
return true;
} else if (page_up) {
int page = engine_->GetFirstVisiblePage();
if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue())
page--;
ScrollToPage(page);
UpdateCursor(PP_CURSORTYPE_POINTER);
return true;
}
}
if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) {
UpdateCursor(PP_CURSORTYPE_POINTER);
return true;
}
if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) {
UpdateCursor(PP_CURSORTYPE_POINTER);
return true;
}
if (timer_pending_ &&
(event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP ||
event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) {
timer_factory_.CancelAll();
timer_pending_ = false;
} else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
engine_->IsSelecting()) {
bool set_timer = false;
pp::MouseInputEvent mouse_event(event);
if (v_scrollbar_.get() &&
(mouse_event.GetPosition().y() <= 0 ||
mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) {
v_scrollbar_->ScrollBy(
PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1);
set_timer = true;
}
if (h_scrollbar_.get() &&
(mouse_event.GetPosition().x() <= 0 ||
mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) {
h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE,
mouse_event.GetPosition().x() >= 0 ? 1: -1);
set_timer = true;
}
if (set_timer) {
last_mouse_event_ = pp::MouseInputEvent(event);
pp::CompletionCallback callback =
timer_factory_.NewCallback(&Instance::OnTimerFired);
pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback);
timer_pending_ = true;
}
}
if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN &&
event.GetModifiers() & kDefaultKeyModifier) {
pp::KeyboardInputEvent keyboard_event(event);
switch (keyboard_event.GetKeyCode()) {
case 'A':
engine_->SelectAll();
return true;
}
}
return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The Instance::HandleInputEvent function in pdf/instance.cc in the PDFium component in Google Chrome before 38.0.2125.101 interprets a certain -1 value as an index instead of a no-visible-page error code, which allows remote attackers to cause a denial of service (out-of-bounds read) via unspecified vectors.
Commit Message: Let PDFium handle event when there is not yet a visible page.
Speculative fix for 415307. CF will confirm.
The stack trace for that bug indicates an attempt to index by -1, which is consistent with no visible page.
BUG=415307
Review URL: https://codereview.chromium.org/560133004
Cr-Commit-Position: refs/heads/master@{#295421}
|
Low
| 171,640
|
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 Browser::SetWebContentsBlocked(content::WebContents* web_contents,
bool blocked) {
int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
if (index == TabStripModel::kNoTab) {
return;
}
tab_strip_model_->SetTabBlocked(index, blocked);
bool browser_active = BrowserList::GetInstance()->GetLastActive() == this;
bool contents_is_active =
tab_strip_model_->GetActiveWebContents() == web_contents;
if (!blocked && contents_is_active && browser_active)
web_contents->Focus();
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Incorrect dialog placement in Cast UI in Google Chrome prior to 70.0.3538.67 allowed a remote attacker to obscure the full screen warning via a crafted HTML page.
Commit Message: If a dialog is shown, drop fullscreen.
BUG=875066, 817809, 792876, 812769, 813815
TEST=included
Change-Id: Ic3d697fa3c4b01f5d7fea77391857177ada660db
Reviewed-on: https://chromium-review.googlesource.com/1185208
Reviewed-by: Sidney San Martín <sdy@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#586418}
|
Medium
| 172,664
|
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 PHP_MINIT_FUNCTION(zip)
{
#ifdef PHP_ZIP_USE_OO
zend_class_entry ce;
memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
zip_object_handlers.clone_obj = NULL;
zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr;
zip_object_handlers.get_properties = php_zip_get_properties;
zip_object_handlers.read_property = php_zip_read_property;
zip_object_handlers.has_property = php_zip_has_property;
INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions);
ce.create_object = php_zip_object_new;
zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1);
php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC);
REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE);
REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL);
REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS);
REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR);
REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED);
REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT);
REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4);
REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA);
REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77);
REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD);
/* Error code */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */
REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */
php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper TSRMLS_CC);
#endif
le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number);
le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number);
return SUCCESS;
}
Vulnerability Type: DoS Exec Code
CWE ID: CWE-416
Summary: php_zip.c in the zip extension in PHP before 5.5.37, 5.6.x before 5.6.23, and 7.x before 7.0.8 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to execute arbitrary code or cause a denial of service (use-after-free and application crash) via crafted serialized data containing a ZipArchive object.
Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize
|
Low
| 167,023
|
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: cifs_find_smb_ses(struct TCP_Server_Info *server, char *username)
{
struct list_head *tmp;
struct cifsSesInfo *ses;
write_lock(&cifs_tcp_ses_lock);
list_for_each(tmp, &server->smb_ses_list) {
ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list);
if (strncmp(ses->userName, username, MAX_USERNAME_SIZE))
continue;
++ses->ses_count;
write_unlock(&cifs_tcp_ses_lock);
return ses;
}
write_unlock(&cifs_tcp_ses_lock);
return NULL;
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The cifs_find_smb_ses function in fs/cifs/connect.c in the Linux kernel before 2.6.36 does not properly determine the associations between users and sessions, which allows local users to bypass CIFS share authentication by leveraging a mount of a share by a different user.
Commit Message: cifs: clean up cifs_find_smb_ses (try #2)
This patch replaces the earlier patch by the same name. The only
difference is that MAX_PASSWORD_SIZE has been increased to attempt to
match the limits that windows enforces.
Do a better job of matching sessions by authtype. Matching by username
for a Kerberos session is incorrect, and anonymous sessions need special
handling.
Also, in the case where we do match by username, we also need to match
by password. That ensures that someone else doesn't "borrow" an existing
session without needing to know the password.
Finally, passwords can be longer than 16 bytes. Bump MAX_PASSWORD_SIZE
to 512 to match the size that the userspace mount helper allows.
Signed-off-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Steve French <sfrench@us.ibm.com>
|
Medium
| 166,229
|
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 fe_netjoin_deinit(void)
{
while (joinservers != NULL)
netjoin_server_remove(joinservers->data);
if (join_tag != -1) {
g_source_remove(join_tag);
signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting);
}
signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
signal_remove("message quit", (SIGNAL_FUNC) msg_quit);
signal_remove("message join", (SIGNAL_FUNC) msg_join);
signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode);
}
Vulnerability Type: DoS Exec Code
CWE ID: CWE-416
Summary: The netjoin processing in Irssi 1.x before 1.0.2 allows attackers to cause a denial of service (use-after-free) and possibly execute arbitrary code via unspecified vectors.
Commit Message: Merge branch 'netjoin-timeout' into 'master'
fe-netjoin: remove irc servers on "server disconnected" signal
Closes #7
See merge request !10
|
Low
| 168,290
|
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: tt_cmap12_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_groups;
if ( table + 16 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 4;
length = TT_NEXT_ULONG( p );
p = table + 12;
p = table + 12;
num_groups = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 16 + 12 * num_groups )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
for ( n = 0; n < num_groups; n++ )
{
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
last = end;
}
}
Vulnerability Type: Exec Code Overflow
CWE ID: CWE-189
Summary: Multiple integer overflows in FreeType 2.3.9 and earlier allow remote attackers to execute arbitrary code via vectors related to large values in certain inputs in (1) smooth/ftsmooth.c, (2) sfnt/ttcmap.c, and (3) cff/cffload.c.
Commit Message:
|
Low
| 164,740
|
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 detect_allow_debuggers(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--allow-debuggers") == 0) {
arg_allow_debuggers = 1;
break;
}
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--", 2) != 0)
break;
}
}
Vulnerability Type: Bypass
CWE ID:
Summary: Firejail before 0.9.44.4, when running on a Linux kernel before 4.8, allows context-dependent attackers to bypass a seccomp-based sandbox protection mechanism via the --allow-debuggers argument.
Commit Message: security fix
|
Medium
| 168,419
|
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: InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath)
: InstallVerifyFrame_Base(NULL, wxID_ANY, _T(""))
{
mConfig = Config::GetConfig();
prepareDialog();
int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME;
wxProgressDialog lPrepareProgress(_("Preparing"),
_("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags);
BZip lBZip(lDmodFilePath);
mTarFilePath = lBZip.Extract(&lPrepareProgress);
if (mTarFilePath.Len() != 0)
{
Tar lTar(mTarFilePath);
lTar.ReadHeaders();
wxString lDmodDescription = lTar.getmDmodDescription();
"\n"
"The D-Mod will be installed in subdirectory '%s'."),
lTar.getInstalledDmodDirectory().c_str());
}
else
{
int lBreakChar = lDmodDescription.Find( '\r' );
if ( lBreakChar <= 0 )
{
lBreakChar = lDmodDescription.Find( '\n' );
}
mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 );
this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName);
}
mDmodDescription->SetValue(lDmodDescription);
mInstallButton->Enable(true);
}
Vulnerability Type: Dir. Trav.
CWE ID: CWE-22
Summary: Directory traversal issues in the D-Mod extractor in DFArc and DFArc2 (as well as in RTsoft's Dink Smallwood HD / ProtonSDK version) before 3.14 allow an attacker to overwrite arbitrary files on the user's system.
Commit Message:
|
Low
| 165,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: bool MockContentSettingsClient::allowAutoplay(bool default_value) {
return default_value || flags_->autoplay_allowed();
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The SkBitmap::ReadRawPixels function in core/SkBitmap.cpp in the filters implementation in Skia, as used in Google Chrome before 41.0.2272.76, allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger an out-of-bounds write operation.
Commit Message: [Blink>Media] Allow autoplay muted on Android by default
There was a mistake causing autoplay muted is shipped on Android
but it will be disabled if the chromium embedder doesn't specify
content setting for "AllowAutoplay" preference. This CL makes the
AllowAutoplay preference true by default so that it is allowed by
embedders (including AndroidWebView) unless they explicitly
disable it.
Intent to ship:
https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ
BUG=689018
Review-Url: https://codereview.chromium.org/2677173002
Cr-Commit-Position: refs/heads/master@{#448423}
|
Low
| 172,015
|
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: zsethalftone5(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
uint count;
gs_halftone_component *phtc = 0;
gs_halftone_component *pc;
int code = 0;
int j;
bool have_default;
gs_halftone *pht = 0;
gx_device_halftone *pdht = 0;
ref sprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
ref tprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
gs_memory_t *mem;
uint edepth = ref_stack_count(&e_stack);
int npop = 2;
int dict_enum = dict_first(op);
ref rvalue[2];
int cname, colorant_number;
byte * pname;
uint name_size;
int halftonetype, type = 0;
gs_gstate *pgs = igs;
int space_index = r_space_index(op - 1);
mem = (gs_memory_t *) idmemory->spaces_indexed[space_index];
* the device color space, so we need to mark them
* with a different internal halftone type.
*/
code = dict_int_param(op - 1, "HalftoneType", 1, 100, 0, &type);
if (code < 0)
return code;
halftonetype = (type == 2 || type == 4)
? ht_type_multiple_colorscreen
: ht_type_multiple;
/* Count how many components that we will actually use. */
have_default = false;
for (count = 0; ;) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
else if (colorant_number == GX_DEVICE_COLOR_MAX_COMPONENTS) {
/* If here then we have the "Default" component */
if (have_default)
return_error(gs_error_rangecheck);
have_default = true;
}
count++;
/*
* Check to see if we have already reached the legal number of
* components.
*/
if (count > GS_CLIENT_COLOR_MAX_COMPONENTS + 1) {
code = gs_note_error(gs_error_rangecheck);
break;
}
}
if (count == 0 || (halftonetype == ht_type_multiple && ! have_default))
code = gs_note_error(gs_error_rangecheck);
if (code >= 0) {
check_estack(5); /* for sampling Type 1 screens */
refset_null(sprocs, count);
refset_null(tprocs, count);
rc_alloc_struct_0(pht, gs_halftone, &st_halftone,
imemory, pht = 0, ".sethalftone5");
phtc = gs_alloc_struct_array(mem, count, gs_halftone_component,
&st_ht_component_element,
".sethalftone5");
rc_alloc_struct_0(pdht, gx_device_halftone, &st_device_halftone,
imemory, pdht = 0, ".sethalftone5");
if (pht == 0 || phtc == 0 || pdht == 0) {
j = 0; /* Quiet the compiler:
gs_note_error isn't necessarily identity,
so j could be left ununitialized. */
code = gs_note_error(gs_error_VMerror);
}
}
if (code >= 0) {
dict_enum = dict_first(op);
for (j = 0, pc = phtc; ;) {
int type;
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue; /* Do not use this component */
pc->cname = cname;
pc->comp_number = colorant_number;
/* Now process the component dictionary */
check_dict_read(rvalue[1]);
if (dict_int_param(&rvalue[1], "HalftoneType", 1, 7, 0, &type) < 0) {
code = gs_note_error(gs_error_typecheck);
break;
}
switch (type) {
default:
code = gs_note_error(gs_error_rangecheck);
break;
case 1:
code = dict_spot_params(&rvalue[1], &pc->params.spot,
sprocs + j, tprocs + j, mem);
pc->params.spot.screen.spot_function = spot1_dummy;
pc->type = ht_type_spot;
break;
case 3:
code = dict_threshold_params(&rvalue[1], &pc->params.threshold,
tprocs + j);
pc->type = ht_type_threshold;
break;
case 7:
code = dict_threshold2_params(&rvalue[1], &pc->params.threshold2,
tprocs + j, imemory);
pc->type = ht_type_threshold2;
break;
}
if (code < 0)
break;
pc++;
j++;
}
}
if (code >= 0) {
pht->type = halftonetype;
pht->params.multiple.components = phtc;
pht->params.multiple.num_comp = j;
pht->params.multiple.get_colorname_string = gs_get_colorname_string;
code = gs_sethalftone_prepare(igs, pht, pdht);
}
if (code >= 0) {
/*
* Put the actual frequency and angle in the spot function component dictionaries.
*/
dict_enum = dict_first(op);
for (pc = phtc; ; ) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/* Verify that we have a valid component */
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component and verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
if (pc->type == ht_type_spot) {
code = dict_spot_results(i_ctx_p, &rvalue[1], &pc->params.spot);
if (code < 0)
break;
}
pc++;
}
}
if (code >= 0) {
/*
* Schedule the sampling of any Type 1 screens,
* and any (Type 1 or Type 3) TransferFunctions.
* Save the stack depths in case we have to back out.
*/
uint odepth = ref_stack_count(&o_stack);
ref odict, odict5;
odict = op[-1];
odict5 = *op;
pop(2);
op = osp;
esp += 5;
make_mark_estack(esp - 4, es_other, sethalftone_cleanup);
esp[-3] = odict;
make_istruct(esp - 2, 0, pht);
make_istruct(esp - 1, 0, pdht);
make_op_estack(esp, sethalftone_finish);
for (j = 0; j < count; j++) {
gx_ht_order *porder = NULL;
if (pdht->components == 0)
porder = &pdht->order;
else {
/* Find the component in pdht that matches component j in
the pht; gs_sethalftone_prepare() may permute these. */
int k;
int comp_number = phtc[j].comp_number;
for (k = 0; k < count; k++) {
if (pdht->components[k].comp_number == comp_number) {
porder = &pdht->components[k].corder;
break;
}
}
}
switch (phtc[j].type) {
case ht_type_spot:
code = zscreen_enum_init(i_ctx_p, porder,
&phtc[j].params.spot.screen,
&sprocs[j], 0, 0, space_index);
if (code < 0)
break;
/* falls through */
case ht_type_threshold:
if (!r_has_type(tprocs + j, t__invalid)) {
/* Schedule TransferFunction sampling. */
/****** check_xstack IS WRONG ******/
check_ostack(zcolor_remap_one_ostack);
check_estack(zcolor_remap_one_estack);
code = zcolor_remap_one(i_ctx_p, tprocs + j,
porder->transfer, igs,
zcolor_remap_one_finish);
op = osp;
}
break;
default: /* not possible here, but to keep */
/* the compilers happy.... */
;
}
if (code < 0) { /* Restore the stack. */
ref_stack_pop_to(&o_stack, odepth);
ref_stack_pop_to(&e_stack, edepth);
op = osp;
op[-1] = odict;
*op = odict5;
break;
}
npop = 0;
}
}
if (code < 0) {
gs_free_object(mem, pdht, ".sethalftone5");
gs_free_object(mem, phtc, ".sethalftone5");
gs_free_object(mem, pht, ".sethalftone5");
return code;
}
pop(npop);
return (ref_stack_count(&e_stack) > edepth ? o_push_estack : 0);
}
Vulnerability Type: DoS Exec Code
CWE ID: CWE-704
Summary: The .sethalftone5 function in psi/zht2.c in Ghostscript before 9.21 allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted Postscript document that calls .sethalftone5 with an empty operand stack.
Commit Message:
|
Medium
| 165,263
|
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: struct sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
newsk->sk_write_space = sk_stream_write_space;
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
Vulnerability Type: DoS
CWE ID: CWE-415
Summary: The inet_csk_clone_lock function in net/ipv4/inet_connection_sock.c in the Linux kernel through 4.10.15 allows attackers to cause a denial of service (double free) or possibly have unspecified other impact by leveraging use of the accept system call.
Commit Message: dccp/tcp: do not inherit mc_list from parent
syzkaller found a way to trigger double frees from ip_mc_drop_socket()
It turns out that leave a copy of parent mc_list at accept() time,
which is very bad.
Very similar to commit 8b485ce69876 ("tcp: do not inherit
fastopen_req from parent")
Initial report from Pray3r, completed by Andrey one.
Thanks a lot to them !
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: Pray3r <pray3r.z@gmail.com>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Tested-by: Andrey Konovalov <andreyknvl@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Low
| 168,190
|
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 ChromeOSStopInputMethodProcess(InputMethodStatusConnection* connection) {
g_return_val_if_fail(connection, false);
return connection->StopInputMethodProcess();
}
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,528
|
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 WebviewInfo::IsResourceWebviewAccessible(
const Extension* extension,
const std::string& partition_id,
const std::string& relative_path) {
if (!extension)
return false;
const WebviewInfo* info = GetResourcesInfo(*extension);
if (!info)
return false;
bool partition_is_privileged = false;
for (size_t i = 0;
i < info->webview_privileged_partitions_.size();
++i) {
if (MatchPattern(partition_id, info->webview_privileged_partitions_[i])) {
partition_is_privileged = true;
break;
}
}
return partition_is_privileged && extension->ResourceMatches(
info->webview_accessible_resources_, relative_path);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 28.0.1500.95 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to not properly considering focus during the processing of JavaScript events in the presence of a multiple-fields input type.
Commit Message: <webview>: Update format for local file access in manifest.json
The new format is:
"webview" : {
"partitions" : [
{
"name" : "foo*",
"accessible_resources" : ["a.html", "b.html"]
},
{
"name" : "bar",
"accessible_resources" : ["a.html", "c.html"]
}
]
}
BUG=340291
Review URL: https://codereview.chromium.org/151923005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 171,208
|
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 veth_setup(struct net_device *dev)
{
ether_setup(dev);
dev->netdev_ops = &veth_netdev_ops;
dev->ethtool_ops = &veth_ethtool_ops;
dev->features |= NETIF_F_LLTX;
dev->destructor = veth_dev_free;
dev->hw_features = NETIF_F_NO_CSUM | NETIF_F_SG | NETIF_F_RXCSUM;
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: The net subsystem in the Linux kernel before 3.1 does not properly restrict use of the IFF_TX_SKB_SHARING flag, which allows local users to cause a denial of service (panic) by leveraging the CAP_NET_ADMIN capability to access /proc/net/pktgen/pgctrl, and then using the pktgen package in conjunction with a bridge device for a VLAN interface.
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <nhorman@tuxdriver.com>
CC: Karsten Keil <isdn@linux-pingi.de>
CC: "David S. Miller" <davem@davemloft.net>
CC: Jay Vosburgh <fubar@us.ibm.com>
CC: Andy Gospodarek <andy@greyhouse.net>
CC: Patrick McHardy <kaber@trash.net>
CC: Krzysztof Halasa <khc@pm.waw.pl>
CC: "John W. Linville" <linville@tuxdriver.com>
CC: Greg Kroah-Hartman <gregkh@suse.de>
CC: Marcel Holtmann <marcel@holtmann.org>
CC: Johannes Berg <johannes@sipsolutions.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Low
| 165,731
|
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 simulate_llsc(struct pt_regs *regs, unsigned int opcode)
{
if ((opcode & OPCODE) == LL) {
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
1, 0, regs, 0);
return simulate_ll(regs, opcode);
}
if ((opcode & OPCODE) == SC) {
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
1, 0, regs, 0);
return simulate_sc(regs, opcode);
}
return -1; /* Must be something else ... */
}
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,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: void FrameSelection::MoveRangeSelection(const VisiblePosition& base_position,
const VisiblePosition& extent_position,
TextGranularity granularity) {
SelectionInDOMTree new_selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtentDeprecated(base_position.DeepEquivalent(),
extent_position.DeepEquivalent())
.SetAffinity(base_position.Affinity())
.SetIsHandleVisible(IsHandleVisible())
.Build();
if (new_selection.IsNone())
return;
const VisibleSelection& visible_selection =
CreateVisibleSelectionWithGranularity(new_selection, granularity);
if (visible_selection.IsNone())
return;
SelectionInDOMTree::Builder builder;
if (visible_selection.IsBaseFirst()) {
builder.SetBaseAndExtent(visible_selection.Start(),
visible_selection.End());
} else {
builder.SetBaseAndExtent(visible_selection.End(),
visible_selection.Start());
}
builder.SetAffinity(visible_selection.Affinity());
builder.SetIsHandleVisible(IsHandleVisible());
SetSelection(builder.Build(), SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetGranularity(granularity)
.Build());
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The convolution implementation in Skia, as used in Google Chrome before 47.0.2526.73, does not properly constrain row lengths, which allows remote attackers to cause a denial of service (out-of-bounds memory access) or possibly have unspecified other impact via crafted graphics data.
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <yosin@chromium.org>
Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org>
Reviewed-by: Kent Tamura <tkent@chromium.org>
Cr-Commit-Position: refs/heads/master@{#491660}
|
Low
| 171,757
|
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: Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize,
size_t gcInfoIndex) {
size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize;
#if defined(ADDRESS_SANITIZER)
largeObjectSize += allocationGranularity;
#endif
getThreadState()->shouldFlushHeapDoesNotContainCache();
PageMemory* pageMemory = PageMemory::allocate(
largeObjectSize, getThreadState()->heap().getRegionTree());
Address largeObjectAddress = pageMemory->writableStart();
Address headerAddress =
largeObjectAddress + LargeObjectPage::pageHeaderSize();
#if DCHECK_IS_ON()
for (size_t i = 0; i < largeObjectSize; ++i)
ASSERT(!largeObjectAddress[i]);
#endif
ASSERT(gcInfoIndex > 0);
HeapObjectHeader* header = new (NotNull, headerAddress)
HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex);
Address result = headerAddress + sizeof(*header);
ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask));
LargeObjectPage* largeObject = new (largeObjectAddress)
LargeObjectPage(pageMemory, this, allocationSize);
ASSERT(header->checkHeader());
ASAN_POISON_MEMORY_REGION(header, sizeof(*header));
ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(),
allocationGranularity);
largeObject->link(&m_firstPage);
getThreadState()->heap().heapStats().increaseAllocatedSpace(
largeObject->size());
getThreadState()->increaseAllocatedObjectSize(largeObject->size());
return result;
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: Inline metadata in GarbageCollection in Google Chrome prior to 66.0.3359.117 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
|
Medium
| 172,709
|
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: xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) {
int ret = 0;
int avail, tlen;
xmlChar cur, next;
const xmlChar *lastlt, *lastgt;
if (ctxt->input == NULL)
return(0);
#ifdef DEBUG_PUSH
switch (ctxt->instate) {
case XML_PARSER_EOF:
xmlGenericError(xmlGenericErrorContext,
"PP: try EOF\n"); break;
case XML_PARSER_START:
xmlGenericError(xmlGenericErrorContext,
"PP: try START\n"); break;
case XML_PARSER_MISC:
xmlGenericError(xmlGenericErrorContext,
"PP: try MISC\n");break;
case XML_PARSER_COMMENT:
xmlGenericError(xmlGenericErrorContext,
"PP: try COMMENT\n");break;
case XML_PARSER_PROLOG:
xmlGenericError(xmlGenericErrorContext,
"PP: try PROLOG\n");break;
case XML_PARSER_START_TAG:
xmlGenericError(xmlGenericErrorContext,
"PP: try START_TAG\n");break;
case XML_PARSER_CONTENT:
xmlGenericError(xmlGenericErrorContext,
"PP: try CONTENT\n");break;
case XML_PARSER_CDATA_SECTION:
xmlGenericError(xmlGenericErrorContext,
"PP: try CDATA_SECTION\n");break;
case XML_PARSER_END_TAG:
xmlGenericError(xmlGenericErrorContext,
"PP: try END_TAG\n");break;
case XML_PARSER_ENTITY_DECL:
xmlGenericError(xmlGenericErrorContext,
"PP: try ENTITY_DECL\n");break;
case XML_PARSER_ENTITY_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: try ENTITY_VALUE\n");break;
case XML_PARSER_ATTRIBUTE_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: try ATTRIBUTE_VALUE\n");break;
case XML_PARSER_DTD:
xmlGenericError(xmlGenericErrorContext,
"PP: try DTD\n");break;
case XML_PARSER_EPILOG:
xmlGenericError(xmlGenericErrorContext,
"PP: try EPILOG\n");break;
case XML_PARSER_PI:
xmlGenericError(xmlGenericErrorContext,
"PP: try PI\n");break;
case XML_PARSER_IGNORE:
xmlGenericError(xmlGenericErrorContext,
"PP: try IGNORE\n");break;
}
#endif
if ((ctxt->input != NULL) &&
(ctxt->input->cur - ctxt->input->base > 4096)) {
xmlSHRINK(ctxt);
ctxt->checkIndex = 0;
}
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
while (1) {
if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))
return(0);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if (ctxt->input == NULL) break;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else {
/*
* If we are operating on converted input, try to flush
* remainng chars to avoid them stalling in the non-converted
* buffer.
*/
if ((ctxt->input->buf->raw != NULL) &&
(ctxt->input->buf->raw->use > 0)) {
int base = ctxt->input->base -
ctxt->input->buf->buffer->content;
int current = ctxt->input->cur - ctxt->input->base;
xmlParserInputBufferPush(ctxt->input->buf, 0, "");
ctxt->input->base = ctxt->input->buf->buffer->content + base;
ctxt->input->cur = ctxt->input->base + current;
ctxt->input->end =
&ctxt->input->buf->buffer->content[
ctxt->input->buf->buffer->use];
}
avail = ctxt->input->buf->buffer->use -
(ctxt->input->cur - ctxt->input->base);
}
if (avail < 1)
goto done;
switch (ctxt->instate) {
case XML_PARSER_EOF:
/*
* Document parsing is done !
*/
goto done;
case XML_PARSER_START:
if (ctxt->charset == XML_CHAR_ENCODING_NONE) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* Very first chars read from the document flow.
*/
if (avail < 4)
goto done;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines,
* else xmlSwitchEncoding will set to (default)
* UTF8.
*/
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
xmlSwitchEncoding(ctxt, enc);
break;
}
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if (cur == 0) {
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
ctxt->instate = XML_PARSER_EOF;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering EOF\n");
#endif
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
if ((cur == '<') && (next == '?')) {
/* PI or XML decl */
if (avail < 5) return(ret);
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
return(ret);
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
if ((ctxt->input->cur[2] == 'x') &&
(ctxt->input->cur[3] == 'm') &&
(ctxt->input->cur[4] == 'l') &&
(IS_BLANK_CH(ctxt->input->cur[5]))) {
ret += 5;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing XML Decl\n");
#endif
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right
* here
*/
ctxt->instate = XML_PARSER_EOF;
return(0);
}
ctxt->standalone = ctxt->input->standalone;
if ((ctxt->encoding == NULL) &&
(ctxt->input->encoding != NULL))
ctxt->encoding = xmlStrdup(ctxt->input->encoding);
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
}
} else {
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
if (ctxt->version == NULL) {
xmlErrMemory(ctxt, NULL);
break;
}
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
}
break;
case XML_PARSER_START_TAG: {
const xmlChar *name;
const xmlChar *prefix = NULL;
const xmlChar *URI = NULL;
int nsNr = ctxt->nsNr;
if ((avail < 2) && (ctxt->inputNr == 1))
goto done;
cur = ctxt->input->cur[0];
if (cur != '<') {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
ctxt->instate = XML_PARSER_EOF;
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
if (!terminate) {
if (ctxt->progressive) {
/* > can be found unescaped in attribute values */
if ((lastgt == NULL) || (ctxt->input->cur >= lastgt))
goto done;
} else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) {
goto done;
}
}
if (ctxt->spaceNr == 0)
spacePush(ctxt, -1);
else if (*ctxt->space == -2)
spacePush(ctxt, -1);
else
spacePush(ctxt, *ctxt->space);
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax2)
#endif /* LIBXML_SAX1_ENABLED */
name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen);
#ifdef LIBXML_SAX1_ENABLED
else
name = xmlParseStartTag(ctxt);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF)
goto done;
if (name == NULL) {
spacePop(ctxt);
ctxt->instate = XML_PARSER_EOF;
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
#ifdef LIBXML_VALID_ENABLED
/*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match
* the element type of the root element.
*/
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
ctxt->node && (ctxt->node == ctxt->myDoc->children))
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
#endif /* LIBXML_VALID_ENABLED */
/*
* Check for an Empty Element.
*/
if ((RAW == '/') && (NXT(1) == '>')) {
SKIP(2);
if (ctxt->sax2) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, name,
prefix, URI);
if (ctxt->nsNr - nsNr > 0)
nsPop(ctxt, ctxt->nsNr - nsNr);
#ifdef LIBXML_SAX1_ENABLED
} else {
if ((ctxt->sax != NULL) &&
(ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, name);
#endif /* LIBXML_SAX1_ENABLED */
}
spacePop(ctxt);
if (ctxt->nameNr == 0) {
ctxt->instate = XML_PARSER_EPILOG;
} else {
ctxt->instate = XML_PARSER_CONTENT;
}
break;
}
if (RAW == '>') {
NEXT;
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s\n",
name);
nodePop(ctxt);
spacePop(ctxt);
}
if (ctxt->sax2)
nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr);
#ifdef LIBXML_SAX1_ENABLED
else
namePush(ctxt, name);
#endif /* LIBXML_SAX1_ENABLED */
ctxt->instate = XML_PARSER_CONTENT;
break;
}
case XML_PARSER_CONTENT: {
const xmlChar *test;
unsigned int cons;
if ((avail < 2) && (ctxt->inputNr == 1))
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
test = CUR_PTR;
cons = ctxt->input->consumed;
if ((cur == '<') && (next == '/')) {
ctxt->instate = XML_PARSER_END_TAG;
break;
} else if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
xmlParsePI(ctxt);
} else if ((cur == '<') && (next != '!')) {
ctxt->instate = XML_PARSER_START_TAG;
break;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') &&
(ctxt->input->cur[3] == '-')) {
int term;
if (avail < 4)
goto done;
ctxt->input->cur += 4;
term = xmlParseLookupSequence(ctxt, '-', '-', '>');
ctxt->input->cur -= 4;
if ((!terminate) && (term < 0))
goto done;
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_CONTENT;
} else if ((cur == '<') && (ctxt->input->cur[1] == '!') &&
(ctxt->input->cur[2] == '[') &&
(ctxt->input->cur[3] == 'C') &&
(ctxt->input->cur[4] == 'D') &&
(ctxt->input->cur[5] == 'A') &&
(ctxt->input->cur[6] == 'T') &&
(ctxt->input->cur[7] == 'A') &&
(ctxt->input->cur[8] == '[')) {
SKIP(9);
ctxt->instate = XML_PARSER_CDATA_SECTION;
break;
} else if ((cur == '<') && (next == '!') &&
(avail < 9)) {
goto done;
} else if (cur == '&') {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, ';', 0, 0) < 0))
goto done;
xmlParseReference(ctxt);
} else {
/* TODO Avoid the extra copy, handle directly !!! */
/*
* Goal of the following test is:
* - minimize calls to the SAX 'character' callback
* when they are mergeable
* - handle an problem for isBlank when we only parse
* a sequence of blank chars and the next one is
* not available to check against '<' presence.
* - tries to homogenize the differences in SAX
* callbacks between the push and pull versions
* of the parser.
*/
if ((ctxt->inputNr == 1) &&
(avail < XML_PARSER_BIG_BUFFER_SIZE)) {
if (!terminate) {
if (ctxt->progressive) {
if ((lastlt == NULL) ||
(ctxt->input->cur > lastlt))
goto done;
} else if (xmlParseLookupSequence(ctxt,
'<', 0, 0) < 0) {
goto done;
}
}
}
ctxt->checkIndex = 0;
xmlParseCharData(ctxt, 0);
}
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"detected an error in element content\n");
ctxt->instate = XML_PARSER_EOF;
break;
}
break;
}
case XML_PARSER_END_TAG:
if (avail < 2)
goto done;
if (!terminate) {
if (ctxt->progressive) {
/* > can be found unescaped in attribute values */
if ((lastgt == NULL) || (ctxt->input->cur >= lastgt))
goto done;
} else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) {
goto done;
}
}
if (ctxt->sax2) {
xmlParseEndTag2(ctxt,
(void *) ctxt->pushTab[ctxt->nameNr * 3 - 3],
(void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0,
(int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0);
nameNsPop(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
else
xmlParseEndTag1(ctxt, 0);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF) {
/* Nothing */
} else if (ctxt->nameNr == 0) {
ctxt->instate = XML_PARSER_EPILOG;
} else {
ctxt->instate = XML_PARSER_CONTENT;
}
break;
case XML_PARSER_CDATA_SECTION: {
/*
* The Push mode need to have the SAX callback for
* cdataBlock merge back contiguous callbacks.
*/
int base;
base = xmlParseLookupSequence(ctxt, ']', ']', '>');
if (base < 0) {
if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) {
int tmp;
tmp = xmlCheckCdataPush(ctxt->input->cur,
XML_PARSER_BIG_BUFFER_SIZE);
if (tmp < 0) {
tmp = -tmp;
ctxt->input->cur += tmp;
goto encoding_error;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData,
ctxt->input->cur, tmp);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, tmp);
}
SKIPL(tmp);
ctxt->checkIndex = 0;
}
goto done;
} else {
int tmp;
tmp = xmlCheckCdataPush(ctxt->input->cur, base);
if ((tmp < 0) || (tmp != base)) {
tmp = -tmp;
ctxt->input->cur += tmp;
goto encoding_error;
}
if ((ctxt->sax != NULL) && (base == 0) &&
(ctxt->sax->cdataBlock != NULL) &&
(!ctxt->disableSAX)) {
/*
* Special case to provide identical behaviour
* between pull and push parsers on enpty CDATA
* sections
*/
if ((ctxt->input->cur - ctxt->input->base >= 9) &&
(!strncmp((const char *)&ctxt->input->cur[-9],
"<![CDATA[", 9)))
ctxt->sax->cdataBlock(ctxt->userData,
BAD_CAST "", 0);
} else if ((ctxt->sax != NULL) && (base > 0) &&
(!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData,
ctxt->input->cur, base);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, base);
}
SKIPL(base + 3);
ctxt->checkIndex = 0;
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
}
break;
}
case XML_PARSER_MISC:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else
avail = ctxt->input->buf->buffer->use -
(ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
ctxt->checkIndex = 0;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') &&
(ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_MISC;
ctxt->checkIndex = 0;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == 'D') &&
(ctxt->input->cur[3] == 'O') &&
(ctxt->input->cur[4] == 'C') &&
(ctxt->input->cur[5] == 'T') &&
(ctxt->input->cur[6] == 'Y') &&
(ctxt->input->cur[7] == 'P') &&
(ctxt->input->cur[8] == 'E')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '>', 0, 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing internal subset\n");
#endif
ctxt->inSubset = 1;
xmlParseDocTypeDecl(ctxt);
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
} else {
/*
* Create and update the external subset.
*/
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->externalSubset != NULL))
ctxt->sax->externalSubset(ctxt->userData,
ctxt->intSubName, ctxt->extSubSystem,
ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering PROLOG\n");
#endif
}
} else if ((cur == '<') && (next == '!') &&
(avail < 9)) {
goto done;
} else {
ctxt->instate = XML_PARSER_START_TAG;
ctxt->progressive = 1;
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
}
break;
case XML_PARSER_PROLOG:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base);
else
avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
} else if ((cur == '<') && (next == '!') &&
(avail < 4)) {
goto done;
} else {
ctxt->instate = XML_PARSER_START_TAG;
if (ctxt->progressive == 0)
ctxt->progressive = 1;
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
}
break;
case XML_PARSER_EPILOG:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base);
else
avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
ctxt->instate = XML_PARSER_EPILOG;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0))
goto done;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_EPILOG;
} else if ((cur == '<') && (next == '!') &&
(avail < 4)) {
goto done;
} else {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
ctxt->instate = XML_PARSER_EOF;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering EOF\n");
#endif
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
break;
case XML_PARSER_DTD: {
/*
* Sorry but progressive parsing of the internal subset
* is not expected to be supported. We first check that
* the full content of the internal subset is available and
* the parsing is launched only at that point.
* Internal subset ends up with "']' S? '>'" in an unescaped
* section and not in a ']]>' sequence which are conditional
* sections (whoever argued to keep that crap in XML deserve
* a place in hell !).
*/
int base, i;
xmlChar *buf;
xmlChar quote = 0;
base = ctxt->input->cur - ctxt->input->base;
if (base < 0) return(0);
if (ctxt->checkIndex > base)
base = ctxt->checkIndex;
buf = ctxt->input->buf->buffer->content;
for (;(unsigned int) base < ctxt->input->buf->buffer->use;
base++) {
if (quote != 0) {
if (buf[base] == quote)
quote = 0;
continue;
}
if ((quote == 0) && (buf[base] == '<')) {
int found = 0;
/* special handling of comments */
if (((unsigned int) base + 4 <
ctxt->input->buf->buffer->use) &&
(buf[base + 1] == '!') &&
(buf[base + 2] == '-') &&
(buf[base + 3] == '-')) {
for (;(unsigned int) base + 3 <
ctxt->input->buf->buffer->use; base++) {
if ((buf[base] == '-') &&
(buf[base + 1] == '-') &&
(buf[base + 2] == '>')) {
found = 1;
base += 2;
break;
}
}
if (!found) {
#if 0
fprintf(stderr, "unfinished comment\n");
#endif
break; /* for */
}
continue;
}
}
if (buf[base] == '"') {
quote = '"';
continue;
}
if (buf[base] == '\'') {
quote = '\'';
continue;
}
if (buf[base] == ']') {
#if 0
fprintf(stderr, "%c%c%c%c: ", buf[base],
buf[base + 1], buf[base + 2], buf[base + 3]);
#endif
if ((unsigned int) base +1 >=
ctxt->input->buf->buffer->use)
break;
if (buf[base + 1] == ']') {
/* conditional crap, skip both ']' ! */
base++;
continue;
}
for (i = 1;
(unsigned int) base + i < ctxt->input->buf->buffer->use;
i++) {
if (buf[base + i] == '>') {
#if 0
fprintf(stderr, "found\n");
#endif
goto found_end_int_subset;
}
if (!IS_BLANK_CH(buf[base + i])) {
#if 0
fprintf(stderr, "not found\n");
#endif
goto not_end_of_int_subset;
}
}
#if 0
fprintf(stderr, "end of stream\n");
#endif
break;
}
not_end_of_int_subset:
continue; /* for */
}
/*
* We didn't found the end of the Internal subset
*/
#ifdef DEBUG_PUSH
if (next == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup of int subset end filed\n");
#endif
goto done;
found_end_int_subset:
xmlParseInternalSubset(ctxt);
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->externalSubset != NULL))
ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
ctxt->extSubSystem, ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
ctxt->checkIndex = 0;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering PROLOG\n");
#endif
break;
}
case XML_PARSER_COMMENT:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == COMMENT\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
break;
case XML_PARSER_IGNORE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == IGNORE");
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_PI:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == PI\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
break;
case XML_PARSER_ENTITY_DECL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ENTITY_DECL\n");
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_ENTITY_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ENTITY_VALUE\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_ATTRIBUTE_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ATTRIBUTE_VALUE\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
case XML_PARSER_SYSTEM_LITERAL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == SYSTEM_LITERAL\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
case XML_PARSER_PUBLIC_LITERAL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == PUBLIC_LITERAL\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
}
}
done:
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret);
#endif
return(ret);
encoding_error:
{
char buffer[150];
snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
ctxt->input->cur[0], ctxt->input->cur[1],
ctxt->input->cur[2], ctxt->input->cur[3]);
__xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
"Input is not proper UTF-8, indicate encoding !\n%s",
BAD_CAST buffer, NULL);
}
return(0);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: parser.c in libxml2 before 2.9.0, as used in Google Chrome before 28.0.1500.71 and other products, allows remote attackers to cause a denial of service (out-of-bounds read) via a document that ends abruptly, related to the lack of certain checks for the XML_PARSER_EOF state.
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 171,307
|
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 btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
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,439
|
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 SimpleBlock::GetKind() const
{
return kBlockSimple;
}
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,332
|
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::UpdateFragmentClip() {
DCHECK(properties_);
if (NeedsPaintPropertyUpdate()) {
if (context_.fragment_clip) {
OnUpdateClip(properties_->UpdateFragmentClip(
context_.current.clip,
ClipPaintPropertyNode::State{context_.current.transform,
ToClipRect(*context_.fragment_clip)}));
} else {
OnClearClip(properties_->ClearFragmentClip());
}
}
if (properties_->FragmentClip())
context_.current.clip = properties_->FragmentClip();
}
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,797
|
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: SYSCALL_DEFINE1(inotify_init1, int, flags)
{
struct fsnotify_group *group;
struct user_struct *user;
int ret;
/* Check the IN_* constants for consistency. */
BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);
if (flags & ~(IN_CLOEXEC | IN_NONBLOCK))
return -EINVAL;
user = get_current_user();
if (unlikely(atomic_read(&user->inotify_devs) >=
inotify_max_user_instances)) {
ret = -EMFILE;
goto out_free_uid;
}
/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */
group = inotify_new_group(user, inotify_max_queued_events);
if (IS_ERR(group)) {
ret = PTR_ERR(group);
goto out_free_uid;
}
atomic_inc(&user->inotify_devs);
ret = anon_inode_getfd("inotify", &inotify_fops, group,
O_RDONLY | flags);
if (ret >= 0)
return ret;
atomic_dec(&user->inotify_devs);
out_free_uid:
free_uid(user);
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Memory leak in the inotify_init1 function in fs/notify/inotify/inotify_user.c in the Linux kernel before 2.6.37 allows local users to cause a denial of service (memory consumption) via vectors involving failed attempts to create files.
Commit Message: inotify: stop kernel memory leak on file creation failure
If inotify_init is unable to allocate a new file for the new inotify
group we leak the new group. This patch drops the reference on the
group on file allocation failure.
Reported-by: Vegard Nossum <vegard.nossum@gmail.com>
cc: stable@kernel.org
Signed-off-by: Eric Paris <eparis@redhat.com>
|
Low
| 165,908
|
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: virtual void TearDown() {
content::GetContentClient()->set_browser(old_browser_client_);
RenderViewHostTestHarness::TearDown();
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: Google Chrome before 19.0.1084.46 does not use a dedicated process for the loading of links found on an internal page, which might allow attackers to bypass intended sandbox restrictions via a crafted page.
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
|
Low
| 171,016
|
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: pkinit_server_verify_padata(krb5_context context,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_enc_tkt_part * enc_tkt_reply,
krb5_pa_data * data,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
krb5_auth_pack *auth_pack = NULL;
krb5_auth_pack_draft9 *auth_pack9 = NULL;
pkinit_kdc_context plgctx = NULL;
pkinit_kdc_req_context reqctx = NULL;
krb5_checksum cksum = {0, 0, 0, NULL};
krb5_data *der_req = NULL;
int valid_eku = 0, valid_san = 0;
krb5_data k5data;
int is_signed = 1;
krb5_pa_data **e_data = NULL;
krb5_kdcpreauth_modreq modreq = NULL;
pkiDebug("pkinit_verify_padata: entered!\n");
if (data == NULL || data->length <= 0 || data->contents == NULL) {
(*respond)(arg, 0, NULL, NULL, NULL);
return;
}
if (moddata == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
(*respond)(arg, 0, NULL, NULL, NULL);
return;
}
#ifdef DEBUG_ASN1
print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req");
#endif
/* create a per-request context */
retval = pkinit_init_kdc_req_context(context, &reqctx);
if (retval)
goto cleanup;
reqctx->pa_type = data->pa_type;
PADATA_TO_KRB5DATA(data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n");
retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp->signedAuthPack.data,
reqp->signedAuthPack.length,
"/tmp/kdc_signed_data");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp->signedAuthPack.data, reqp->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, &is_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n");
retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp9->signedAuthPack.data,
reqp9->signedAuthPack.length,
"/tmp/kdc_signed_data_draft9");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp9->signedAuthPack.data, reqp9->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, NULL);
break;
default:
pkiDebug("unrecognized pa_type = %d\n", data->pa_type);
retval = EINVAL;
goto cleanup;
}
if (retval) {
pkiDebug("pkcs7_signeddata_verify failed\n");
goto cleanup;
}
if (is_signed) {
retval = verify_client_san(context, plgctx, reqctx, request->client,
&valid_san);
if (retval)
goto cleanup;
if (!valid_san) {
pkiDebug("%s: did not find an acceptable SAN in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto cleanup;
}
retval = verify_client_eku(context, plgctx, reqctx, &valid_eku);
if (retval)
goto cleanup;
if (!valid_eku) {
pkiDebug("%s: did not find an acceptable EKU in user "
"certificate\n", __FUNCTION__);
retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
goto cleanup;
}
} else { /* !is_signed */
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal())) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Pkinit request not signed, but client "
"not anonymous."));
goto cleanup;
}
}
#ifdef DEBUG_ASN1
print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack");
#endif
OCTETDATA_TO_KRB5DATA(&authp_data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack\n");
goto cleanup;
}
retval = krb5_check_clockskew(context,
auth_pack->pkAuthenticator.ctime);
if (retval)
goto cleanup;
/* check dh parameters */
if (auth_pack->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
} else if (!is_signed) {
/*Anonymous pkinit requires DH*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Anonymous pkinit without DH public "
"value not supported."));
goto cleanup;
}
der_req = cb->request_body(context, rock);
retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL,
0, der_req, &cksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length ||
k5_bcmp(cksum.contents,
auth_pack->pkAuthenticator.paChecksum.contents,
cksum.length) != 0) {
pkiDebug("failed to match the checksum\n");
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size (%d)\n",
req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("received checksum type=%d size=%d ",
auth_pack->pkAuthenticator.paChecksum.checksum_type,
auth_pack->pkAuthenticator.paChecksum.length);
print_buffer(auth_pack->pkAuthenticator.paChecksum.contents,
auth_pack->pkAuthenticator.paChecksum.length);
pkiDebug("expected checksum type=%d size=%d ",
cksum.checksum_type, cksum.length);
print_buffer(cksum.contents, cksum.length);
#endif
retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
goto cleanup;
}
/* check if kdcPkId present and match KDC's subjectIdentifier */
if (reqp->kdcPkId.data != NULL) {
int valid_kdcPkId = 0;
retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
(unsigned char *)reqp->kdcPkId.data,
reqp->kdcPkId.length, &valid_kdcPkId);
if (retval)
goto cleanup;
if (!valid_kdcPkId)
pkiDebug("kdcPkId in AS_REQ does not match KDC's cert"
"RFC says to ignore and proceed\n");
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack = auth_pack;
auth_pack = NULL;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack_draft9\n");
goto cleanup;
}
if (auth_pack9->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack9->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack9 = auth_pack9;
auth_pack9 = NULL;
break;
}
/* remember to set the PREAUTH flag in the reply */
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
modreq = (krb5_kdcpreauth_modreq)reqctx;
reqctx = NULL;
cleanup:
if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) {
pkiDebug("pkinit_verify_padata failed: creating e-data\n");
if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx,
plgctx->idctx, plgctx->opts, retval, &e_data))
pkiDebug("pkinit_create_edata failed\n");
}
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free(cksum.contents);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
}
free(authp_data.data);
free(krb5_authz.data);
if (reqctx != NULL)
pkinit_fini_kdc_req_context(context, reqctx);
free_krb5_auth_pack(&auth_pack);
free_krb5_auth_pack_draft9(context, &auth_pack9);
(*respond)(arg, retval, modreq, e_data, NULL);
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The kdcpreauth modules in MIT Kerberos 5 (aka krb5) 1.12.x and 1.13.x before 1.13.2 do not properly track whether a client's request has been validated, which allows remote attackers to bypass an intended preauthentication requirement by providing (1) zero bytes of data or (2) an arbitrary realm name, related to plugins/preauth/otp/main.c and plugins/preauth/pkinit/pkinit_srv.c.
Commit Message: Prevent requires_preauth bypass [CVE-2015-2694]
In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until
the request is successfully verified. In the PKINIT kdcpreauth
module, don't respond with code 0 on empty input or an unconfigured
realm. Together these bugs could cause the KDC preauth framework to
erroneously treat a request as pre-authenticated.
CVE-2015-2694:
In MIT krb5 1.12 and later, when the KDC is configured with PKINIT
support, an unauthenticated remote attacker can bypass the
requires_preauth flag on a client principal and obtain a ciphertext
encrypted in the principal's long-term key. This ciphertext could be
used to conduct an off-line dictionary attack against the user's
password.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C
ticket: 8160 (new)
target_version: 1.13.2
tags: pullup
subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694]
|
Medium
| 166,678
|
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 usb_parse_configuration(struct usb_device *dev, int cfgidx,
struct usb_host_config *config, unsigned char *buffer, int size)
{
struct device *ddev = &dev->dev;
unsigned char *buffer0 = buffer;
int cfgno;
int nintf, nintf_orig;
int i, j, n;
struct usb_interface_cache *intfc;
unsigned char *buffer2;
int size2;
struct usb_descriptor_header *header;
int len, retval;
u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
unsigned iad_num = 0;
memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
if (config->desc.bDescriptorType != USB_DT_CONFIG ||
config->desc.bLength < USB_DT_CONFIG_SIZE ||
config->desc.bLength > size) {
dev_err(ddev, "invalid descriptor for config index %d: "
"type = 0x%X, length = %d\n", cfgidx,
config->desc.bDescriptorType, config->desc.bLength);
return -EINVAL;
}
cfgno = config->desc.bConfigurationValue;
buffer += config->desc.bLength;
size -= config->desc.bLength;
nintf = nintf_orig = config->desc.bNumInterfaces;
if (nintf > USB_MAXINTERFACES) {
dev_warn(ddev, "config %d has too many interfaces: %d, "
"using maximum allowed: %d\n",
cfgno, nintf, USB_MAXINTERFACES);
nintf = USB_MAXINTERFACES;
}
/* Go through the descriptors, checking their length and counting the
* number of altsettings for each interface */
n = 0;
for ((buffer2 = buffer, size2 = size);
size2 > 0;
(buffer2 += header->bLength, size2 -= header->bLength)) {
if (size2 < sizeof(struct usb_descriptor_header)) {
dev_warn(ddev, "config %d descriptor has %d excess "
"byte%s, ignoring\n",
cfgno, size2, plural(size2));
break;
}
header = (struct usb_descriptor_header *) buffer2;
if ((header->bLength > size2) || (header->bLength < 2)) {
dev_warn(ddev, "config %d has an invalid descriptor "
"of length %d, skipping remainder of the config\n",
cfgno, header->bLength);
break;
}
if (header->bDescriptorType == USB_DT_INTERFACE) {
struct usb_interface_descriptor *d;
int inum;
d = (struct usb_interface_descriptor *) header;
if (d->bLength < USB_DT_INTERFACE_SIZE) {
dev_warn(ddev, "config %d has an invalid "
"interface descriptor of length %d, "
"skipping\n", cfgno, d->bLength);
continue;
}
inum = d->bInterfaceNumber;
if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&
n >= nintf_orig) {
dev_warn(ddev, "config %d has more interface "
"descriptors, than it declares in "
"bNumInterfaces, ignoring interface "
"number: %d\n", cfgno, inum);
continue;
}
if (inum >= nintf_orig)
dev_warn(ddev, "config %d has an invalid "
"interface number: %d but max is %d\n",
cfgno, inum, nintf_orig - 1);
/* Have we already encountered this interface?
* Count its altsettings */
for (i = 0; i < n; ++i) {
if (inums[i] == inum)
break;
}
if (i < n) {
if (nalts[i] < 255)
++nalts[i];
} else if (n < USB_MAXINTERFACES) {
inums[n] = inum;
nalts[n] = 1;
++n;
}
} else if (header->bDescriptorType ==
USB_DT_INTERFACE_ASSOCIATION) {
if (iad_num == USB_MAXIADS) {
dev_warn(ddev, "found more Interface "
"Association Descriptors "
"than allocated for in "
"configuration %d\n", cfgno);
} else {
config->intf_assoc[iad_num] =
(struct usb_interface_assoc_descriptor
*)header;
iad_num++;
}
} else if (header->bDescriptorType == USB_DT_DEVICE ||
header->bDescriptorType == USB_DT_CONFIG)
dev_warn(ddev, "config %d contains an unexpected "
"descriptor of type 0x%X, skipping\n",
cfgno, header->bDescriptorType);
} /* for ((buffer2 = buffer, size2 = size); ...) */
size = buffer2 - buffer;
config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
if (n != nintf)
dev_warn(ddev, "config %d has %d interface%s, different from "
"the descriptor's value: %d\n",
cfgno, n, plural(n), nintf_orig);
else if (n == 0)
dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
config->desc.bNumInterfaces = nintf = n;
/* Check for missing interface numbers */
for (i = 0; i < nintf; ++i) {
for (j = 0; j < nintf; ++j) {
if (inums[j] == i)
break;
}
if (j >= nintf)
dev_warn(ddev, "config %d has no interface number "
"%d\n", cfgno, i);
}
/* Allocate the usb_interface_caches and altsetting arrays */
for (i = 0; i < nintf; ++i) {
j = nalts[i];
if (j > USB_MAXALTSETTING) {
dev_warn(ddev, "too many alternate settings for "
"config %d interface %d: %d, "
"using maximum allowed: %d\n",
cfgno, inums[i], j, USB_MAXALTSETTING);
nalts[i] = j = USB_MAXALTSETTING;
}
len = sizeof(*intfc) + sizeof(struct usb_host_interface) * j;
config->intf_cache[i] = intfc = kzalloc(len, GFP_KERNEL);
if (!intfc)
return -ENOMEM;
kref_init(&intfc->ref);
}
/* FIXME: parse the BOS descriptor */
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first interface descriptor */
config->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, &n);
config->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "configuration");
buffer += i;
size -= i;
/* Parse all the interface/altsetting descriptors */
while (size > 0) {
retval = usb_parse_interface(ddev, cfgno, config,
buffer, size, inums, nalts);
if (retval < 0)
return retval;
buffer += retval;
size -= retval;
}
/* Check for missing altsettings */
for (i = 0; i < nintf; ++i) {
intfc = config->intf_cache[i];
for (j = 0; j < intfc->num_altsetting; ++j) {
for (n = 0; n < intfc->num_altsetting; ++n) {
if (intfc->altsetting[n].desc.
bAlternateSetting == j)
break;
}
if (n >= intfc->num_altsetting)
dev_warn(ddev, "config %d interface %d has no "
"altsetting %d\n", cfgno, inums[i], j);
}
}
return 0;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: drivers/usb/core/config.c in the Linux kernel before 4.13.6 allows local users to cause a denial of service (out-of-bounds read and system crash) or possibly have unspecified other impact via a crafted USB device, related to the USB_DT_INTERFACE_ASSOCIATION descriptor.
Commit Message: USB: fix out-of-bounds in usb_set_configuration
Andrey Konovalov reported a possible out-of-bounds problem for a USB interface
association descriptor. He writes:
It seems there's no proper size check of a USB_DT_INTERFACE_ASSOCIATION
descriptor. It's only checked that the size is >= 2 in
usb_parse_configuration(), so find_iad() might do out-of-bounds access
to intf_assoc->bInterfaceCount.
And he's right, we don't check for crazy descriptors of this type very well, so
resolve this problem. Yet another issue found by syzkaller...
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Tested-by: Andrey Konovalov <andreyknvl@google.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
|
Low
| 167,679
|
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: NodeIterator::NodeIterator(PassRefPtrWillBeRawPtr<Node> rootNode, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter)
: NodeIteratorBase(rootNode, whatToShow, filter)
, m_referenceNode(root(), true)
{
root()->document().attachNodeIterator(this);
}
Vulnerability Type: DoS
CWE ID:
Summary: Use-after-free vulnerability in Blink, as used in Google Chrome before 49.0.2623.75, allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
Commit Message: Fix detached Attr nodes interaction with NodeIterator
- Don't register NodeIterator to document when attaching to Attr node.
-- NodeIterator is registered to its document to receive updateForNodeRemoval notifications.
-- However it wouldn't make sense on Attr nodes, as they never have children.
BUG=572537
Review URL: https://codereview.chromium.org/1577213003
Cr-Commit-Position: refs/heads/master@{#369687}
|
Low
| 172,142
|
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: x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid = ARR_SIZE(insn_regs_intel) / 2;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
while (first <= last) {
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
mid = (first + last) / 2;
}
return 0;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: Capstone 3.0.4 has an out-of-bounds vulnerability (SEGV caused by a read memory access) in X86_insn_reg_intel in arch/X86/X86Mapping.c.
Commit Message: x86: fast path checking for X86_insn_reg_intel()
|
Medium
| 169,866
|
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 perf_syscall_exit(void *ignore, struct pt_regs *regs, long ret)
{
struct syscall_metadata *sys_data;
struct syscall_trace_exit *rec;
struct hlist_head *head;
int syscall_nr;
int rctx;
int size;
syscall_nr = trace_get_syscall_nr(current, regs);
if (syscall_nr < 0)
return;
if (!test_bit(syscall_nr, enabled_perf_exit_syscalls))
return;
sys_data = syscall_nr_to_meta(syscall_nr);
if (!sys_data)
return;
head = this_cpu_ptr(sys_data->exit_event->perf_events);
if (hlist_empty(head))
return;
/* We can probably do that at build time */
size = ALIGN(sizeof(*rec) + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
rec = (struct syscall_trace_exit *)perf_trace_buf_prepare(size,
sys_data->exit_event->event.type, regs, &rctx);
if (!rec)
return;
rec->nr = syscall_nr;
rec->ret = syscall_get_return_value(current, regs);
perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL);
}
Vulnerability Type: DoS +Priv
CWE ID: CWE-264
Summary: kernel/trace/trace_syscalls.c in the Linux kernel through 3.17.2 does not properly handle private syscall numbers during use of the ftrace subsystem, which allows local users to gain privileges or cause a denial of service (invalid pointer dereference) via a crafted application.
Commit Message: tracing/syscalls: Ignore numbers outside NR_syscalls' range
ARM has some private syscalls (for example, set_tls(2)) which lie
outside the range of NR_syscalls. If any of these are called while
syscall tracing is being performed, out-of-bounds array access will
occur in the ftrace and perf sys_{enter,exit} handlers.
# trace-cmd record -e raw_syscalls:* true && trace-cmd report
...
true-653 [000] 384.675777: sys_enter: NR 192 (0, 1000, 3, 4000022, ffffffff, 0)
true-653 [000] 384.675812: sys_exit: NR 192 = 1995915264
true-653 [000] 384.675971: sys_enter: NR 983045 (76f74480, 76f74000, 76f74b28, 76f74480, 76f76f74, 1)
true-653 [000] 384.675988: sys_exit: NR 983045 = 0
...
# trace-cmd record -e syscalls:* true
[ 17.289329] Unable to handle kernel paging request at virtual address aaaaaace
[ 17.289590] pgd = 9e71c000
[ 17.289696] [aaaaaace] *pgd=00000000
[ 17.289985] Internal error: Oops: 5 [#1] PREEMPT SMP ARM
[ 17.290169] Modules linked in:
[ 17.290391] CPU: 0 PID: 704 Comm: true Not tainted 3.18.0-rc2+ #21
[ 17.290585] task: 9f4dab00 ti: 9e710000 task.ti: 9e710000
[ 17.290747] PC is at ftrace_syscall_enter+0x48/0x1f8
[ 17.290866] LR is at syscall_trace_enter+0x124/0x184
Fix this by ignoring out-of-NR_syscalls-bounds syscall numbers.
Commit cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls"
added the check for less than zero, but it should have also checked
for greater than NR_syscalls.
Link: http://lkml.kernel.org/p/1414620418-29472-1-git-send-email-rabin@rab.in
Fixes: cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls"
Cc: stable@vger.kernel.org # 2.6.33+
Signed-off-by: Rabin Vincent <rabin@rab.in>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
|
Low
| 166,257
|
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 sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!asoc->temp) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk->sk_ack_backlog--;
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = true;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free ssnmap storage. */
sctp_ssnmap_free(asoc->ssnmap);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
if (asoc->asconf_addr_del_pending != NULL)
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The sctp_association_free function in net/sctp/associola.c in the Linux kernel before 3.15.2 does not properly manage a certain backlog value, which allows remote attackers to cause a denial of service (socket outage) via a crafted SCTP packet.
Commit Message: sctp: Fix sk_ack_backlog wrap-around problem
Consider the scenario:
For a TCP-style socket, while processing the COOKIE_ECHO chunk in
sctp_sf_do_5_1D_ce(), after it has passed a series of sanity check,
a new association would be created in sctp_unpack_cookie(), but afterwards,
some processing maybe failed, and sctp_association_free() will be called to
free the previously allocated association, in sctp_association_free(),
sk_ack_backlog value is decremented for this socket, since the initial
value for sk_ack_backlog is 0, after the decrement, it will be 65535,
a wrap-around problem happens, and if we want to establish new associations
afterward in the same socket, ABORT would be triggered since sctp deem the
accept queue as full.
Fix this issue by only decrementing sk_ack_backlog for associations in
the endpoint's list.
Fix-suggested-by: Neil Horman <nhorman@tuxdriver.com>
Signed-off-by: Xufeng Zhang <xufeng.zhang@windriver.com>
Acked-by: Daniel Borkmann <dborkman@redhat.com>
Acked-by: Vlad Yasevich <vyasevich@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Low
| 166,289
|
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 *ReadJPEGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
value[MaxTextExtent];
const char
*option;
ErrorManager
error_manager;
Image
*image;
IndexPacket
index;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
debug,
status;
MagickSizeType
number_pixels;
MemoryInfo
*memory_info;
register ssize_t
i;
struct jpeg_decompress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
register JSAMPLE
*p;
size_t
units;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
debug=IsEventLogging();
(void) debug;
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Verify that file size large enough to contain a JPEG datastream.
*/
if (GetBlobSize(image) < 107)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Initialize JPEG parameters.
*/
(void) ResetMagickMemory(&error_manager,0,sizeof(error_manager));
(void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info));
(void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error));
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
memory_info=(MemoryInfo *) NULL;
error_manager.image=image;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_decompress(&jpeg_info);
if (error_manager.profile != (StringInfo *) NULL)
error_manager.profile=DestroyStringInfo(error_manager.profile);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
InheritException(exception,&image->exception);
return(DestroyImage(image));
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_decompress(&jpeg_info);
JPEGSourceManager(&jpeg_info,image);
jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment);
option=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile);
if (IsOptionMember("IPTC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile);
for (i=1; i < 16; i++)
if ((i != 2) && (i != 13) && (i != 14))
if (IsOptionMember("APP",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile);
i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE);
if ((image_info->colorspace == YCbCrColorspace) ||
(image_info->colorspace == Rec601YCbCrColorspace) ||
(image_info->colorspace == Rec709YCbCrColorspace))
jpeg_info.out_color_space=JCS_YCbCr;
/*
Set image resolution.
*/
units=0;
if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) &&
(jpeg_info.Y_density != 1))
{
image->x_resolution=(double) jpeg_info.X_density;
image->y_resolution=(double) jpeg_info.Y_density;
units=(size_t) jpeg_info.density_unit;
}
if (units == 1)
image->units=PixelsPerInchResolution;
if (units == 2)
image->units=PixelsPerCentimeterResolution;
number_pixels=(MagickSizeType) image->columns*image->rows;
option=GetImageOption(image_info,"jpeg:size");
if ((option != (const char *) NULL) &&
(jpeg_info.out_color_space != JCS_YCbCr))
{
double
scale_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Scale the image.
*/
flags=ParseGeometry(option,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_calc_output_dimensions(&jpeg_info);
image->magick_columns=jpeg_info.output_width;
image->magick_rows=jpeg_info.output_height;
scale_factor=1.0;
if (geometry_info.rho != 0.0)
scale_factor=jpeg_info.output_width/geometry_info.rho;
if ((geometry_info.sigma != 0.0) &&
(scale_factor > (jpeg_info.output_height/geometry_info.sigma)))
scale_factor=jpeg_info.output_height/geometry_info.sigma;
jpeg_info.scale_num=1U;
jpeg_info.scale_denom=(unsigned int) scale_factor;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Scale factor: %.20g",(double) scale_factor);
}
#if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED)
#if defined(D_LOSSLESS_SUPPORTED)
image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ?
JPEGInterlace : NoInterlace;
image->compression=jpeg_info.process == JPROC_LOSSLESS ?
LosslessJPEGCompression : JPEGCompression;
if (jpeg_info.data_precision > 8)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'",
image->filename);
if (jpeg_info.data_precision == 16)
jpeg_info.data_precision=12;
#else
image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace :
NoInterlace;
image->compression=JPEGCompression;
#endif
#else
image->compression=JPEGCompression;
image->interlace=JPEGInterlace;
#endif
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
{
/*
Let the JPEG library quantize for us.
*/
jpeg_info.quantize_colors=TRUE;
jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option);
}
option=GetImageOption(image_info,"jpeg:block-smoothing");
if (option != (const char *) NULL)
jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
jpeg_info.dct_method=JDCT_FLOAT;
option=GetImageOption(image_info,"jpeg:dct-method");
if (option != (const char *) NULL)
switch (*option)
{
case 'D':
case 'd':
{
if (LocaleCompare(option,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(option,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(option,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(option,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(option,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:fancy-upsampling");
if (option != (const char *) NULL)
jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
(void) jpeg_start_decompress(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
image->depth=(size_t) jpeg_info.data_precision;
switch (jpeg_info.out_color_space)
{
case JCS_RGB:
default:
{
(void) SetImageColorspace(image,sRGBColorspace);
break;
}
case JCS_GRAYSCALE:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
case JCS_YCbCr:
{
(void) SetImageColorspace(image,YCbCrColorspace);
break;
}
case JCS_CMYK:
{
(void) SetImageColorspace(image,CMYKColorspace);
break;
}
}
if (IsITUFaxImage(image) != MagickFalse)
{
(void) SetImageColorspace(image,LabColorspace);
jpeg_info.out_color_space=JCS_YCbCr;
}
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0))
{
size_t
colors;
colors=(size_t) GetQuantumRange(image->depth)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
}
if (image->debug != MagickFalse)
{
if (image->interlace != NoInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d",
(int) jpeg_info.data_precision);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d",
(int) jpeg_info.output_width,(int) jpeg_info.output_height);
}
JPEGSetImageQuality(&jpeg_info,image);
JPEGSetImageSamplingFactor(&jpeg_info,image);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
jpeg_info.out_color_space);
(void) SetImageProperty(image,"jpeg:colorspace",value);
if (image_info->ping != MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components != 1) &&
(jpeg_info.output_components != 3) && (jpeg_info.output_components != 4))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.output_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
/*
Convert JPEG pixels to pixel packets.
*/
if (setjmp(error_manager.error_recovery) != 0)
{
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
return(DestroyImage(image));
}
if (jpeg_info.quantize_colors != 0)
{
image->colors=(size_t) jpeg_info.actual_number_of_colors;
if (jpeg_info.out_color_space == JCS_GRAYSCALE)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=image->colormap[i].red;
image->colormap[i].blue=image->colormap[i].red;
image->colormap[i].opacity=OpaqueOpacity;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]);
image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]);
image->colormap[i].opacity=OpaqueOpacity;
}
}
scanline[0]=(JSAMPROW) jpeg_pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
continue;
}
p=jpeg_pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (jpeg_info.data_precision > 8)
{
unsigned short
scale;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
size_t
pixel;
pixel=(size_t) (scale*GETJSAMPLE(*p));
index=ConstrainColormapIndex(image,pixel);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelYellow(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum(
(unsigned char) GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
{
jpeg_abort_decompress(&jpeg_info);
break;
}
}
if (status != MagickFalse)
{
error_manager.finished=MagickTrue;
if (setjmp(error_manager.error_recovery) == 0)
(void) jpeg_finish_decompress(&jpeg_info);
}
/*
Free jpeg resources.
*/
jpeg_destroy_decompress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The ReadJPEGImage function in coders/jpeg.c in ImageMagick before 7.0.6-1 allows remote attackers to obtain sensitive information from uninitialized memory locations via a crafted file.
Commit Message: Zero pixel buffer
|
Medium
| 168,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: void RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
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: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
|
Low
| 174,522
|
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: tight_detect_smooth_image24(VncState *vs, int w, int h)
{
int off;
int x, y, d, dx;
unsigned int c;
unsigned int stats[256];
int pixels = 0;
int pix, left[3];
unsigned int errors;
unsigned char *buf = vs->tight.tight.buffer;
/*
* If client is big-endian, color samples begin from the second
* byte (offset 1) of a 32-bit pixel value.
*/
off = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
memset(stats, 0, sizeof (stats));
for (y = 0, x = 0; y < h && x < w;) {
for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;
d++) {
for (c = 0; c < 3; c++) {
left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;
}
for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {
for (c = 0; c < 3; c++) {
pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;
stats[abs(pix - left[c])]++;
left[c] = pix;
}
pixels++;
}
}
if (w > h) {
x += h;
y = 0;
} else {
x = 0;
y += w;
}
}
/* 95% smooth or more ... */
if (stats[0] * 33 / pixels >= 95) {
return 0;
}
errors = 0;
for (c = 1; c < 8; c++) {
errors += stats[c] * (c * c);
if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {
return 0;
}
}
for (; c < 256; c++) {
errors += stats[c] * (c * c);
}
errors /= (pixels * 3 - stats[0]);
return errors;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: An out-of-bounds memory access issue was found in Quick Emulator (QEMU) before 1.7.2 in the VNC display driver. This flaw could occur while refreshing the VNC display surface area in the 'vnc_refresh_server_surface'. A user inside a guest could use this flaw to crash the QEMU process.
Commit Message:
|
Low
| 165,465
|
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 hugetlb_vm_op_close(struct vm_area_struct *vma)
{
struct hstate *h = hstate_vma(vma);
struct resv_map *reservations = vma_resv_map(vma);
struct hugepage_subpool *spool = subpool_vma(vma);
unsigned long reserve;
unsigned long start;
unsigned long end;
if (reservations) {
start = vma_hugecache_offset(h, vma, vma->vm_start);
end = vma_hugecache_offset(h, vma, vma->vm_end);
reserve = (end - start) -
region_count(&reservations->regions, start, end);
kref_put(&reservations->refs, resv_map_release);
if (reserve) {
hugetlb_acct_memory(h, -reserve);
hugepage_subpool_put_pages(spool, reserve);
}
}
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Memory leak in mm/hugetlb.c in the Linux kernel before 3.4.2 allows local users to cause a denial of service (memory consumption or system crash) via invalid MAP_HUGETLB mmap operations.
Commit Message: hugetlb: fix resv_map leak in error path
When called for anonymous (non-shared) mappings, hugetlb_reserve_pages()
does a resv_map_alloc(). It depends on code in hugetlbfs's
vm_ops->close() to release that allocation.
However, in the mmap() failure path, we do a plain unmap_region() without
the remove_vma() which actually calls vm_ops->close().
This is a decent fix. This leak could get reintroduced if new code (say,
after hugetlb_reserve_pages() in hugetlbfs_file_mmap()) decides to return
an error. But, I think it would have to unroll the reservation anyway.
Christoph's test case:
http://marc.info/?l=linux-mm&m=133728900729735
This patch applies to 3.4 and later. A version for earlier kernels is at
https://lkml.org/lkml/2012/5/22/418.
Signed-off-by: Dave Hansen <dave@linux.vnet.ibm.com>
Acked-by: Mel Gorman <mel@csn.ul.ie>
Acked-by: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com>
Reported-by: Christoph Lameter <cl@linux.com>
Tested-by: Christoph Lameter <cl@linux.com>
Cc: Andrea Arcangeli <aarcange@redhat.com>
Cc: <stable@vger.kernel.org> [2.6.32+]
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
|
Low
| 165,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 Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
if (tile_image != (Image *) NULL) \
tile_image=DestroyImage(tile_image); \
if (read_info != (ImageInfo *) NULL) \
read_info=DestroyImageInfo(read_info); \
ThrowReaderException((exception),(message)); \
}
char
geometry[MagickPathExtent],
header_ole[4];
Image
*image,
*tile_image;
ImageInfo
*read_info;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PICT header.
*/
read_info=(ImageInfo *) NULL;
tile_image=(Image *) NULL;
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2.
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
version=(ssize_t) ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
image->resolution.x=DefaultResolution;
image->resolution.y=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code == 0)
continue;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowPICTException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
image->depth=(size_t) pixmap.component_size;
image->resolution.x=1.0*pixmap.horizontal_resolution;
image->resolution.y=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=(size_t) (frame.bottom-frame.top);
height=(size_t) (frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (i=0; i < (ssize_t) height; i++)
{
if (EOFBlob(image) != MagickFalse)
break;
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
ssize_t
bytes_per_line;
unsigned char
*pixels;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
(size_t) (frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
tile_image->depth=(size_t) pixmap.component_size;
tile_image->alpha_trait=pixmap.component_count == 4 ?
BlendPixelTrait : UndefinedPixelTrait;
tile_image->resolution.x=(double) pixmap.horizontal_resolution;
tile_image->resolution.y=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->alpha_trait != UndefinedPixelTrait)
(void) SetImageAlpha(tile_image,OpaqueAlpha,exception);
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors,
exception);
if (status == MagickFalse)
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (EOFBlob(image) != MagickFalse)
ThrowPICTException(CorruptImageError,
"InsufficientImageDataInFile");
if (ReadRectangle(image,&source) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadRectangle(image,&destination) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
&extent);
else
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,
(unsigned int) pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t)
*p,exception);
SetPixelIndex(tile_image,index,q);
SetPixelRed(tile_image,
tile_image->colormap[(ssize_t) index].red,q);
SetPixelGreen(tile_image,
tile_image->colormap[(ssize_t) index].green,q);
SetPixelBlue(tile_image,
tile_image->colormap[(ssize_t) index].blue,q);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(ssize_t) (*p++);
j=(size_t) (*p);
SetPixelRed(tile_image,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)),q);
}
else
if (tile_image->alpha_trait == UndefinedPixelTrait)
{
if (p > (pixels+extent+2*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
}
else
{
if (p > (pixels+extent+3*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);
SetPixelRed(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+3*tile_image->columns)),q);
}
}
p++;
q+=GetPixelChannels(tile_image);
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,tile_image,CopyCompositeOp,
MagickTrue,(ssize_t) destination.left,(ssize_t)
destination.top,exception);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=MagickMin(length,4);
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
}
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile,exception);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
char
filename[MaxTextExtent];
FILE
*file;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
(void) fputc(c,file);
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows),exception);
(void) TransformImageColorspace(image,tile_image->colorspace,exception);
(void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,
(ssize_t) frame.left,(ssize_t) frame.right,exception);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The functions ReadDCMImage in coders/dcm.c, ReadPWPImage in coders/pwp.c, ReadCALSImage in coders/cals.c, and ReadPICTImage in coders/pict.c in ImageMagick 7.0.8-4 do not check the return value of the fputc function, which allows remote attackers to cause a denial of service via a crafted image file.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199
|
Medium
| 169,040
|
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 SSL_METHOD *ssl23_get_client_method(int ver)
{
#ifndef OPENSSL_NO_SSL2
if (ver == SSL2_VERSION)
return(SSLv2_client_method());
#endif
if (ver == SSL3_VERSION)
return(SSLv3_client_method());
else if (ver == TLS1_VERSION)
return(TLSv1_client_method());
else if (ver == TLS1_1_VERSION)
return(TLSv1_1_client_method());
else
return(NULL);
}
Vulnerability Type: Bypass
CWE ID: CWE-310
Summary: OpenSSL before 0.9.8zc, 1.0.0 before 1.0.0o, and 1.0.1 before 1.0.1j does not properly enforce the no-ssl3 build option, which allows remote attackers to bypass intended access restrictions via an SSL 3.0 handshake, related to s23_clnt.c and s23_srvr.c.
Commit Message:
|
Medium
| 165,156
|
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 phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
phar_zip_dir_end locator;
char buf[sizeof(locator) + 65536];
long size;
php_uint16 i;
phar_archive_data *mydata = NULL;
phar_entry_info entry = {0};
char *p = buf, *ext, *actual_alias = NULL;
char *metadata = NULL;
size = php_stream_tell(fp);
if (size > sizeof(locator) + 65536) {
/* seek to max comment length + end of central directory record */
size = sizeof(locator) + 65536;
if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
} else {
php_stream_seek(fp, 0, SEEK_SET);
}
if (!php_stream_read(fp, buf, size)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) {
if (!memcmp(p + 1, "K\5\6", 3)) {
memcpy((void *)&locator, (void *) p, sizeof(locator));
if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) {
/* split archives not handled */
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
return FAILURE;
}
mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
mydata->is_persistent = PHAR_G(persist);
/* read in archive comment, if any */
if (PHAR_GET_16(locator.comment_len)) {
metadata = p + sizeof(locator);
if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
pefree(mydata, mydata->is_persistent);
return FAILURE;
}
mydata->metadata_len = PHAR_GET_16(locator.comment_len);
if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len) TSRMLS_CC) == FAILURE) {
mydata->metadata_len = 0;
/* if not valid serialized data, it is a regular string */
if (entry.is_persistent) {
ALLOC_PERMANENT_ZVAL(mydata->metadata);
} else {
ALLOC_ZVAL(mydata->metadata);
}
INIT_ZVAL(*mydata->metadata);
metadata = pestrndup(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent);
ZVAL_STRINGL(mydata->metadata, metadata, PHAR_GET_16(locator.comment_len), 0);
}
} else {
mydata->metadata = NULL;
}
goto foundit;
}
}
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname);
}
return FAILURE;
foundit:
mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
mydata->is_zip = 1;
mydata->fname_len = fname_len;
ext = strrchr(mydata->fname, '/');
if (ext) {
mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext);
if (mydata->ext == ext) {
mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + fname_len) - mydata->ext;
}
}
/* clean up on big-endian systems */
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* read in central directory */
zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
entry.phar = mydata;
entry.is_zip = 1;
entry.fp_type = PHAR_FP;
entry.is_persistent = mydata->is_persistent;
#define PHAR_ZIP_FAIL_FREE(errmsg, save) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.arBuckets = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.arBuckets = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.arBuckets = 0; \
php_stream_close(fp); \
if (mydata->metadata) { \
zval_dtor(mydata->metadata); \
} \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
efree(save); \
return FAILURE;
#define PHAR_ZIP_FAIL(errmsg) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.arBuckets = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.arBuckets = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.arBuckets = 0; \
php_stream_close(fp); \
if (mydata->metadata) { \
zval_dtor(mydata->metadata); \
} \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
return FAILURE;
/* add each central directory item to the manifest */
for (i = 0; i < PHAR_GET_16(locator.count); ++i) {
phar_zip_central_dir_file zipentry;
off_t beforeus = php_stream_tell(fp);
if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) {
PHAR_ZIP_FAIL("unable to read central directory entry, truncated");
}
/* clean up for bigendian systems */
if (memcmp("PK\1\2", zipentry.signature, 4)) {
/* corrupted entry */
PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature");
}
if (entry.is_persistent) {
entry.manifest_pos = i;
}
entry.compressed_filesize = PHAR_GET_32(zipentry.compsize);
entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize);
entry.crc32 = PHAR_GET_32(zipentry.crc32);
/* do not PHAR_GET_16 either on the next line */
entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp);
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.header_offset = PHAR_GET_32(zipentry.offset);
entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) +
PHAR_GET_16(zipentry.extra_len);
if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) {
PHAR_ZIP_FAIL("Cannot process encrypted zip files");
}
if (!PHAR_GET_16(zipentry.filename_len)) {
PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)");
}
entry.filename_len = PHAR_GET_16(zipentry.filename_len);
entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent);
if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated");
}
entry.filename[entry.filename_len] = '\0';
if (entry.filename[entry.filename_len - 1] == '/') {
entry.is_dir = 1;
if(entry.filename_len > 1) {
entry.filename_len--;
}
entry.flags |= PHAR_ENT_PERM_DEF_DIR;
} else {
entry.is_dir = 0;
}
if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
size_t read;
php_stream *sigfile;
off_t now;
char *sig;
now = php_stream_tell(fp);
pefree(entry.filename, entry.is_persistent);
sigfile = php_stream_fopen_tmpfile();
if (!sigfile) {
PHAR_ZIP_FAIL("couldn't open temporary file");
}
php_stream_seek(fp, 0, SEEK_SET);
/* copy file contents + local headers and zip comment, if any, to be hashed for signature */
phar_stream_copy_to_stream(fp, sigfile, entry.header_offset, NULL);
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* copy central directory header */
phar_stream_copy_to_stream(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL);
if (metadata) {
php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len));
}
php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
sig = (char *) emalloc(entry.uncompressed_filesize);
read = php_stream_read(fp, sig, entry.uncompressed_filesize);
if (read != entry.uncompressed_filesize) {
php_stream_close(sigfile);
efree(sig);
PHAR_ZIP_FAIL("signature cannot be read");
}
mydata->sig_flags = PHAR_GET_32(sig);
if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error TSRMLS_CC)) {
efree(sig);
if (error) {
char *save;
php_stream_close(sigfile);
spprintf(&save, 4096, "signature cannot be verified: %s", *error);
efree(*error);
PHAR_ZIP_FAIL_FREE(save, save);
} else {
php_stream_close(sigfile);
PHAR_ZIP_FAIL("signature cannot be verified");
}
}
php_stream_close(sigfile);
efree(sig);
/* signature checked out, let's ensure this is the last file in the phar */
if (i != PHAR_GET_16(locator.count) - 1) {
PHAR_ZIP_FAIL("entries exist after signature, invalid phar");
}
continue;
}
phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len TSRMLS_CC);
if (PHAR_GET_16(zipentry.extra_len)) {
off_t loc = php_stream_tell(fp);
if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len) TSRMLS_CC)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory");
}
php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
}
switch (PHAR_GET_16(zipentry.compressed)) {
case PHAR_ZIP_COMP_NONE :
/* compression flag already set */
break;
case PHAR_ZIP_COMP_DEFLATE :
entry.flags |= PHAR_ENT_COMPRESSED_GZ;
if (!PHAR_G(has_zlib)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("zlib extension is required");
}
break;
case PHAR_ZIP_COMP_BZIP2 :
entry.flags |= PHAR_ENT_COMPRESSED_BZ2;
if (!PHAR_G(has_bz2)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("bzip2 extension is required");
}
break;
case 1 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip");
case 2 :
case 3 :
case 4 :
case 5 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip");
case 6 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip");
case 7 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip");
case 9 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip");
case 10 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip");
case 14 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip");
case 18 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip");
case 19 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip");
case 97 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip");
case 98 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip");
default :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip");
}
/* get file metadata */
if (PHAR_GET_16(zipentry.comment_len)) {
if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in file comment, truncated");
}
p = buf;
entry.metadata_len = PHAR_GET_16(zipentry.comment_len);
if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len) TSRMLS_CC) == FAILURE) {
entry.metadata_len = 0;
/* if not valid serialized data, it is a regular string */
if (entry.is_persistent) {
ALLOC_PERMANENT_ZVAL(entry.metadata);
} else {
ALLOC_ZVAL(entry.metadata);
}
INIT_ZVAL(*entry.metadata);
ZVAL_STRINGL(entry.metadata, pestrndup(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent), PHAR_GET_16(zipentry.comment_len), 0);
}
} else {
entry.metadata = NULL;
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
php_stream_filter *filter;
off_t saveloc;
/* verify local file header */
phar_zip_file_header local;
/* archive alias found */
saveloc = php_stream_tell(fp);
php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET);
if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)");
}
/* verify local header */
if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)");
}
/* construct actual offset to file start - local extra_len can be different from central extra_len */
entry.offset = entry.offset_abs =
sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len);
php_stream_seek(fp, entry.offset, SEEK_SET);
/* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */
fp->writepos = 0;
fp->readpos = 0;
php_stream_seek(fp, entry.offset, SEEK_SET);
fp->writepos = 0;
fp->readpos = 0;
/* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */
mydata->alias_len = entry.uncompressed_filesize;
if (entry.flags & PHAR_ENT_COMPRESSED_GZ) {
filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp) TSRMLS_CC);
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC);
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
} else {
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
}
/* return to central directory parsing */
php_stream_seek(fp, saveloc, SEEK_SET);
}
phar_set_inode(&entry TSRMLS_CC);
zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry,sizeof(phar_entry_info), NULL);
}
mydata->fp = fp;
if (zend_hash_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
mydata->is_data = 0;
} else {
mydata->is_data = 1;
}
zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
if (actual_alias) {
phar_archive_data **fd_ptr;
if (!phar_validate_alias(actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname);
}
efree(actual_alias);
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
mydata->is_temporary_alias = 0;
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, mydata->alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname);
}
efree(actual_alias);
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
}
mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias;
if (entry.is_persistent) {
efree(actual_alias);
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
} else {
phar_archive_data **fd_ptr;
if (alias_len) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent);
mydata->alias_len = alias_len;
} else {
mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent);
mydata->alias_len = fname_len;
}
mydata->is_temporary_alias = 1;
}
if (pphar) {
*pphar = mydata;
}
return SUCCESS;
}
/* }}} */
Vulnerability Type: DoS Overflow +Info
CWE ID: CWE-119
Summary: The phar_parse_zipfile function in zip.c in the PHAR extension in PHP before 5.5.33 and 5.6.x before 5.6.19 allows remote attackers to obtain sensitive information from process memory or cause a denial of service (out-of-bounds read and application crash) by placing a PK\x05\x06 signature at an invalid location.
Commit Message:
|
Low
| 165,163
|
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: UINT CSoundFile::ReadSample(MODINSTRUMENT *pIns, UINT nFlags, LPCSTR lpMemFile, DWORD dwMemLength)
{
UINT len = 0, mem = pIns->nLength+6;
if ((!pIns) || (pIns->nLength < 4) || (!lpMemFile)) return 0;
if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH;
pIns->uFlags &= ~(CHN_16BIT|CHN_STEREO);
if (nFlags & RSF_16BIT)
{
mem *= 2;
pIns->uFlags |= CHN_16BIT;
}
if (nFlags & RSF_STEREO)
{
mem *= 2;
pIns->uFlags |= CHN_STEREO;
}
if ((pIns->pSample = AllocateSample(mem)) == NULL)
{
pIns->nLength = 0;
return 0;
}
switch(nFlags)
{
case RS_PCM8U:
{
len = pIns->nLength;
if (len > dwMemLength) len = pIns->nLength = dwMemLength;
signed char *pSample = pIns->pSample;
for (UINT j=0; j<len; j++) pSample[j] = (signed char)(lpMemFile[j] - 0x80);
}
break;
case RS_PCM8D:
{
len = pIns->nLength;
if (len > dwMemLength) break;
signed char *pSample = pIns->pSample;
const signed char *p = (const signed char *)lpMemFile;
int delta = 0;
for (UINT j=0; j<len; j++)
{
delta += p[j];
*pSample++ = (signed char)delta;
}
}
break;
case RS_ADPCM4:
{
len = (pIns->nLength + 1) / 2;
if (len > dwMemLength - 16) break;
memcpy(CompressionTable, lpMemFile, 16);
lpMemFile += 16;
signed char *pSample = pIns->pSample;
signed char delta = 0;
for (UINT j=0; j<len; j++)
{
BYTE b0 = (BYTE)lpMemFile[j];
BYTE b1 = (BYTE)(lpMemFile[j] >> 4);
delta = (signed char)GetDeltaValue((int)delta, b0);
pSample[0] = delta;
delta = (signed char)GetDeltaValue((int)delta, b1);
pSample[1] = delta;
pSample += 2;
}
len += 16;
}
break;
case RS_PCM16D:
{
len = pIns->nLength * 2;
if (len > dwMemLength) break;
short int *pSample = (short int *)pIns->pSample;
short int *p = (short int *)lpMemFile;
int delta16 = 0;
for (UINT j=0; j<len; j+=2)
{
delta16 += bswapLE16(*p++);
*pSample++ = (short int)delta16;
}
}
break;
case RS_PCM16S:
{
len = pIns->nLength * 2;
if (len <= dwMemLength) memcpy(pIns->pSample, lpMemFile, len);
short int *pSample = (short int *)pIns->pSample;
for (UINT j=0; j<len; j+=2)
{
short int s = bswapLE16(*pSample);
*pSample++ = s;
}
}
break;
case RS_PCM16M:
len = pIns->nLength * 2;
if (len > dwMemLength) len = dwMemLength & ~1;
if (len > 1)
{
signed char *pSample = (signed char *)pIns->pSample;
signed char *pSrc = (signed char *)lpMemFile;
for (UINT j=0; j<len; j+=2)
{
*((unsigned short *)(pSample+j)) = bswapBE16(*((unsigned short *)(pSrc+j)));
}
}
break;
case RS_PCM16U:
{
len = pIns->nLength * 2;
if (len > dwMemLength) break;
short int *pSample = (short int *)pIns->pSample;
short int *pSrc = (short int *)lpMemFile;
for (UINT j=0; j<len; j+=2) *pSample++ = bswapLE16(*(pSrc++)) - 0x8000;
}
break;
case RS_STPCM16M:
len = pIns->nLength * 2;
if (len*2 <= dwMemLength)
{
signed char *pSample = (signed char *)pIns->pSample;
signed char *pSrc = (signed char *)lpMemFile;
for (UINT j=0; j<len; j+=2)
{
*((unsigned short *)(pSample+j*2)) = bswapBE16(*((unsigned short *)(pSrc+j)));
*((unsigned short *)(pSample+j*2+2)) = bswapBE16(*((unsigned short *)(pSrc+j+len)));
}
len *= 2;
}
break;
case RS_STPCM8S:
case RS_STPCM8U:
case RS_STPCM8D:
{
int iadd_l = 0, iadd_r = 0;
if (nFlags == RS_STPCM8U) { iadd_l = iadd_r = -128; }
len = pIns->nLength;
signed char *psrc = (signed char *)lpMemFile;
signed char *pSample = (signed char *)pIns->pSample;
if (len*2 > dwMemLength) break;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (signed char)(psrc[0] + iadd_l);
pSample[j*2+1] = (signed char)(psrc[len] + iadd_r);
psrc++;
if (nFlags == RS_STPCM8D)
{
iadd_l = pSample[j*2];
iadd_r = pSample[j*2+1];
}
}
len *= 2;
}
break;
case RS_STPCM16S:
case RS_STPCM16U:
case RS_STPCM16D:
{
int iadd_l = 0, iadd_r = 0;
if (nFlags == RS_STPCM16U) { iadd_l = iadd_r = -0x8000; }
len = pIns->nLength;
short int *psrc = (short int *)lpMemFile;
short int *pSample = (short int *)pIns->pSample;
if (len*4 > dwMemLength) break;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (short int) (bswapLE16(psrc[0]) + iadd_l);
pSample[j*2+1] = (short int) (bswapLE16(psrc[len]) + iadd_r);
psrc++;
if (nFlags == RS_STPCM16D)
{
iadd_l = pSample[j*2];
iadd_r = pSample[j*2+1];
}
}
len *= 4;
}
break;
case RS_IT2148:
case RS_IT21416:
case RS_IT2158:
case RS_IT21516:
len = dwMemLength;
if (len < 4) break;
if ((nFlags == RS_IT2148) || (nFlags == RS_IT2158))
ITUnpack8Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT2158));
else
ITUnpack16Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT21516));
break;
#ifndef MODPLUG_BASIC_SUPPORT
#ifndef FASTSOUNDLIB
case RS_STIPCM8S:
case RS_STIPCM8U:
{
int iadd = 0;
if (nFlags == RS_STIPCM8U) { iadd = -0x80; }
len = pIns->nLength;
if (len*2 > dwMemLength) len = dwMemLength >> 1;
LPBYTE psrc = (LPBYTE)lpMemFile;
LPBYTE pSample = (LPBYTE)pIns->pSample;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (signed char)(psrc[0] + iadd);
pSample[j*2+1] = (signed char)(psrc[1] + iadd);
psrc+=2;
}
len *= 2;
}
break;
case RS_STIPCM16S:
case RS_STIPCM16U:
{
int iadd = 0;
if (nFlags == RS_STIPCM16U) iadd = -32768;
len = pIns->nLength;
if (len*4 > dwMemLength) len = dwMemLength >> 2;
short int *psrc = (short int *)lpMemFile;
short int *pSample = (short int *)pIns->pSample;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (short int)(bswapLE16(psrc[0]) + iadd);
pSample[j*2+1] = (short int)(bswapLE16(psrc[1]) + iadd);
psrc += 2;
}
len *= 4;
}
break;
case RS_AMS8:
case RS_AMS16:
len = 9;
if (dwMemLength > 9)
{
const char *psrc = lpMemFile;
char packcharacter = lpMemFile[8], *pdest = (char *)pIns->pSample;
len += bswapLE32(*((LPDWORD)(lpMemFile+4)));
if (len > dwMemLength) len = dwMemLength;
UINT dmax = pIns->nLength;
if (pIns->uFlags & CHN_16BIT) dmax <<= 1;
AMSUnpack(psrc+9, len-9, pdest, dmax, packcharacter);
}
break;
case RS_PTM8DTO16:
{
len = pIns->nLength * 2;
if (len > dwMemLength) break;
signed char *pSample = (signed char *)pIns->pSample;
signed char delta8 = 0;
for (UINT j=0; j<len; j++)
{
delta8 += lpMemFile[j];
*pSample++ = delta8;
}
WORD *pSampleW = (WORD *)pIns->pSample;
for (UINT j=0; j<len; j+=2) // swaparoni!
{
WORD s = bswapLE16(*pSampleW);
*pSampleW++ = s;
}
}
break;
case RS_MDL8:
case RS_MDL16:
len = dwMemLength;
if (len >= 4)
{
LPBYTE pSample = (LPBYTE)pIns->pSample;
LPBYTE ibuf = (LPBYTE)lpMemFile;
DWORD bitbuf = bswapLE32(*((DWORD *)ibuf));
UINT bitnum = 32;
BYTE dlt = 0, lowbyte = 0;
ibuf += 4;
for (UINT j=0; j<pIns->nLength; j++)
{
BYTE hibyte;
BYTE sign;
if (nFlags == RS_MDL16) lowbyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 8);
sign = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 1);
if (MDLReadBits(bitbuf, bitnum, ibuf, 1))
{
hibyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 3);
} else
{
hibyte = 8;
while (!MDLReadBits(bitbuf, bitnum, ibuf, 1)) hibyte += 0x10;
hibyte += MDLReadBits(bitbuf, bitnum, ibuf, 4);
}
if (sign) hibyte = ~hibyte;
dlt += hibyte;
if (nFlags != RS_MDL16)
pSample[j] = dlt;
else
{
pSample[j<<1] = lowbyte;
pSample[(j<<1)+1] = dlt;
}
}
}
break;
case RS_DMF8:
case RS_DMF16:
len = dwMemLength;
if (len >= 4)
{
UINT maxlen = pIns->nLength;
if (pIns->uFlags & CHN_16BIT) maxlen <<= 1;
LPBYTE ibuf = (LPBYTE)lpMemFile, ibufmax = (LPBYTE)(lpMemFile+dwMemLength);
len = DMFUnpack((LPBYTE)pIns->pSample, ibuf, ibufmax, maxlen);
}
break;
#ifdef MODPLUG_TRACKER
case RS_PCM24S:
case RS_PCM32S:
len = pIns->nLength * 3;
if (nFlags == RS_PCM32S) len += pIns->nLength;
if (len > dwMemLength) break;
if (len > 4*8)
{
UINT slsize = (nFlags == RS_PCM32S) ? 4 : 3;
LPBYTE pSrc = (LPBYTE)lpMemFile;
LONG max = 255;
if (nFlags == RS_PCM32S) pSrc++;
for (UINT j=0; j<len; j+=slsize)
{
LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8;
l /= 256;
if (l > max) max = l;
if (-l > max) max = -l;
}
max = (max / 128) + 1;
signed short *pDest = (signed short *)pIns->pSample;
for (UINT k=0; k<len; k+=slsize)
{
LONG l = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
*pDest++ = (signed short)(l / max);
}
}
break;
case RS_STIPCM24S:
case RS_STIPCM32S:
len = pIns->nLength * 6;
if (nFlags == RS_STIPCM32S) len += pIns->nLength * 2;
if (len > dwMemLength) break;
if (len > 8*8)
{
UINT slsize = (nFlags == RS_STIPCM32S) ? 4 : 3;
LPBYTE pSrc = (LPBYTE)lpMemFile;
LONG max = 255;
if (nFlags == RS_STIPCM32S) pSrc++;
for (UINT j=0; j<len; j+=slsize)
{
LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8;
l /= 256;
if (l > max) max = l;
if (-l > max) max = -l;
}
max = (max / 128) + 1;
signed short *pDest = (signed short *)pIns->pSample;
for (UINT k=0; k<len; k+=slsize)
{
LONG lr = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
k += slsize;
LONG ll = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
pDest[0] = (signed short)ll;
pDest[1] = (signed short)lr;
pDest += 2;
}
}
break;
case RS_STIPCM16M:
{
len = pIns->nLength;
if (len*4 > dwMemLength) len = dwMemLength >> 2;
LPCBYTE psrc = (LPCBYTE)lpMemFile;
short int *pSample = (short int *)pIns->pSample;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (signed short)(((UINT)psrc[0] << 8) | (psrc[1]));
pSample[j*2+1] = (signed short)(((UINT)psrc[2] << 8) | (psrc[3]));
psrc += 4;
}
len *= 4;
}
break;
#endif // MODPLUG_TRACKER
#endif // !FASTSOUNDLIB
#endif // !MODPLUG_BASIC_SUPPORT
default:
len = pIns->nLength;
if (len > dwMemLength) len = pIns->nLength = dwMemLength;
memcpy(pIns->pSample, lpMemFile, len);
}
if (len > dwMemLength)
{
if (pIns->pSample)
{
pIns->nLength = 0;
FreeSample(pIns->pSample);
pIns->pSample = NULL;
}
return 0;
}
AdjustSampleLoop(pIns);
return len;
}
Vulnerability Type: Exec Code Overflow
CWE ID:
Summary: Multiple buffer overflows in MODPlug Tracker (OpenMPT) 1.17.02.43 and earlier and libmodplug 0.8 and earlier, as used in GStreamer and possibly other products, allow user-assisted remote attackers to execute arbitrary code via (1) long strings in ITP files used by the CSoundFile::ReadITProject function in soundlib/Load_it.cpp and (2) crafted modules used by the CSoundFile::ReadSample function in soundlib/Sndfile.cpp, as demonstrated by crafted AMF files.
Commit Message:
|
High
| 164,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: int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error) /* {{{ */
{
int read_size, len;
zend_off_t read_len;
unsigned char buf[1024];
php_stream_rewind(fp);
switch (sig_type) {
case PHAR_SIG_OPENSSL: {
#ifdef PHAR_HAVE_OPENSSL
BIO *in;
EVP_PKEY *key;
EVP_MD *mdtype = (EVP_MD *) EVP_sha1();
EVP_MD_CTX md_ctx;
#else
int tempsig;
#endif
zend_string *pubkey = NULL;
char *pfile;
php_stream *pfp;
#ifndef PHAR_HAVE_OPENSSL
if (!zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) {
if (error) {
spprintf(error, 0, "openssl not loaded");
}
return FAILURE;
}
#endif
/* use __FILE__ . '.pubkey' for public key file */
spprintf(&pfile, 0, "%s.pubkey", fname);
pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL);
efree(pfile);
if (!pfp || !(pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0)) || !ZSTR_LEN(pubkey)) {
if (pfp) {
php_stream_close(pfp);
}
if (error) {
spprintf(error, 0, "openssl public key could not be read");
}
return FAILURE;
}
php_stream_close(pfp);
#ifndef PHAR_HAVE_OPENSSL
tempsig = sig_len;
if (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0, &sig, &tempsig)) {
if (pubkey) {
zend_string_release(pubkey);
}
if (error) {
spprintf(error, 0, "openssl signature could not be verified");
}
return FAILURE;
}
if (pubkey) {
zend_string_release(pubkey);
}
sig_len = tempsig;
#else
in = BIO_new_mem_buf(pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0);
if (NULL == in) {
zend_string_release(pubkey);
if (error) {
spprintf(error, 0, "openssl signature could not be processed");
}
return FAILURE;
}
key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL);
BIO_free(in);
zend_string_release(pubkey);
if (NULL == key) {
if (error) {
spprintf(error, 0, "openssl signature could not be processed");
}
return FAILURE;
}
EVP_VerifyInit(&md_ctx, mdtype);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
php_stream_seek(fp, 0, SEEK_SET);
while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
EVP_VerifyUpdate (&md_ctx, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
if (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) {
/* 1: signature verified, 0: signature does not match, -1: failed signature operation */
EVP_MD_CTX_cleanup(&md_ctx);
if (error) {
spprintf(error, 0, "broken openssl signature");
}
return FAILURE;
}
EVP_MD_CTX_cleanup(&md_ctx);
#endif
*signature_len = phar_hex_str((const char*)sig, sig_len, signature);
}
break;
#ifdef PHAR_HASH_OK
case PHAR_SIG_SHA512: {
unsigned char digest[64];
PHP_SHA512_CTX context;
PHP_SHA512Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_SHA512Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_SHA512Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
case PHAR_SIG_SHA256: {
unsigned char digest[32];
PHP_SHA256_CTX context;
PHP_SHA256Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_SHA256Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_SHA256Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
#else
case PHAR_SIG_SHA512:
case PHAR_SIG_SHA256:
if (error) {
spprintf(error, 0, "unsupported signature");
}
return FAILURE;
#endif
case PHAR_SIG_SHA1: {
unsigned char digest[20];
PHP_SHA1_CTX context;
PHP_SHA1Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_SHA1Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_SHA1Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
case PHAR_SIG_MD5: {
unsigned char digest[16];
PHP_MD5_CTX context;
PHP_MD5Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_MD5Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_MD5Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
default:
if (error) {
spprintf(error, 0, "broken or unsupported signature");
}
return FAILURE;
}
return SUCCESS;
}
/* }}} */
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The ZIP signature-verification feature in PHP before 5.6.26 and 7.x before 7.0.11 does not ensure that the uncompressed_filesize field is large enough, which allows remote attackers to cause a denial of service (out-of-bounds memory access) or possibly have unspecified other impact via a crafted PHAR archive, related to ext/phar/util.c and ext/phar/zip.c.
Commit Message: Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile
(cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2)
|
Low
| 166,934
|
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: rdpsnddbg_process(STREAM s)
{
unsigned int pkglen;
static char *rest = NULL;
char *buf;
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = (char *) xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &rest, rdpsnddbg_line_handler, NULL);
xfree(buf);
}
Vulnerability Type: Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: rdesktop versions up to and including v1.8.3 contain a Buffer Overflow over the global variables in the function seamless_process_line() that results in memory corruption and probably even a remote code execution.
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
|
Low
| 169,807
|
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: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
q = (const uint8_t *)(const void *)
((const char *)(const void *)p +
CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t);
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i,
inp[i].pi_id, inp[i].pi_type, q - p,
CDF_GETUINT32(p, (i << 1) + 1)));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements; j++, i++) {
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: file before 5.11 and libmagic allow remote attackers to cause a denial of service (crash) via a crafted Composite Document File (CDF) file that triggers (1) an out-of-bounds read or (2) an invalid pointer dereference.
Commit Message: Fix bounds checks again.
|
Medium
| 165,623
|
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 * calloc(size_t n, size_t lb)
{
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
Vulnerability Type: Overflow
CWE ID: CWE-189
Summary: Multiple integer overflows in the (1) GC_generic_malloc and (2) calloc functions in malloc.c, and the (3) GC_generic_malloc_ignore_off_page function in mallocx.c in Boehm-Demers-Weiser GC (libgc) before 7.2 make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
Commit Message: Fix calloc() overflow
* malloc.c (calloc): Check multiplication overflow in calloc(),
assuming REDIRECT_MALLOC.
|
Low
| 165,592
|
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 ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
int (*output)(struct net *, struct sock *, struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ?
inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id;
int ptr, offset = 0, err = 0;
u8 *prevhdr, nexthdr = 0;
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->ignore_df && skb->len > mtu))
goto fail_toobig;
if (IP6CB(skb)->frag_max_size) {
if (IP6CB(skb)->frag_max_size > mtu)
goto fail_toobig;
/* don't send fragments larger than what we received */
mtu = IP6CB(skb)->frag_max_size;
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
if (mtu < hlen + sizeof(struct frag_hdr) + 8)
goto fail_toobig;
mtu -= hlen + sizeof(struct frag_hdr);
frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr);
if (skb->ip_summed == CHECKSUM_PARTIAL &&
(err = skb_checksum_help(skb)))
goto fail;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
if (skb_has_frag_list(skb)) {
unsigned int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb) ||
skb_headroom(skb) < (hroom + sizeof(struct frag_hdr)))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr)))
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
__skb_pull(skb, hlen);
fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
fh->identification = frag_id;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(net, sk, skb);
if (!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
kfree_skb_list(frag);
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while (left > 0) {
u8 *fragnexthdr_offset;
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/* Allocate buffer */
frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC);
if (!frag) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
fragnexthdr_offset = skb_network_header(frag);
fragnexthdr_offset += prevhdr - skb_network_header(skb);
*fragnexthdr_offset = NEXTHDR_FRAGMENT;
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag),
len));
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(net, sk, frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail_toobig:
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
err = -EMSGSIZE;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
Vulnerability Type: DoS
CWE ID: CWE-125
Summary: The IPv6 fragmentation implementation in the Linux kernel through 4.11.1 does not consider that the nexthdr field may be associated with an invalid option, which allows local users to cause a denial of service (out-of-bounds read and BUG) or possibly have unspecified other impact via crafted socket and send system calls.
Commit Message: ipv6: Prevent overrun when parsing v6 header options
The KASAN warning repoted below was discovered with a syzkaller
program. The reproducer is basically:
int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP);
send(s, &one_byte_of_data, 1, MSG_MORE);
send(s, &more_than_mtu_bytes_data, 2000, 0);
The socket() call sets the nexthdr field of the v6 header to
NEXTHDR_HOP, the first send call primes the payload with a non zero
byte of data, and the second send call triggers the fragmentation path.
The fragmentation code tries to parse the header options in order
to figure out where to insert the fragment option. Since nexthdr points
to an invalid option, the calculation of the size of the network header
can made to be much larger than the linear section of the skb and data
is read outside of it.
This fix makes ip6_find_1stfrag return an error if it detects
running out-of-bounds.
[ 42.361487] ==================================================================
[ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730
[ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789
[ 42.366469]
[ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41
[ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014
[ 42.368824] Call Trace:
[ 42.369183] dump_stack+0xb3/0x10b
[ 42.369664] print_address_description+0x73/0x290
[ 42.370325] kasan_report+0x252/0x370
[ 42.370839] ? ip6_fragment+0x11c8/0x3730
[ 42.371396] check_memory_region+0x13c/0x1a0
[ 42.371978] memcpy+0x23/0x50
[ 42.372395] ip6_fragment+0x11c8/0x3730
[ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110
[ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0
[ 42.374263] ? ip6_forward+0x2e30/0x2e30
[ 42.374803] ip6_finish_output+0x584/0x990
[ 42.375350] ip6_output+0x1b7/0x690
[ 42.375836] ? ip6_finish_output+0x990/0x990
[ 42.376411] ? ip6_fragment+0x3730/0x3730
[ 42.376968] ip6_local_out+0x95/0x160
[ 42.377471] ip6_send_skb+0xa1/0x330
[ 42.377969] ip6_push_pending_frames+0xb3/0xe0
[ 42.378589] rawv6_sendmsg+0x2051/0x2db0
[ 42.379129] ? rawv6_bind+0x8b0/0x8b0
[ 42.379633] ? _copy_from_user+0x84/0xe0
[ 42.380193] ? debug_check_no_locks_freed+0x290/0x290
[ 42.380878] ? ___sys_sendmsg+0x162/0x930
[ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120
[ 42.382074] ? sock_has_perm+0x1f6/0x290
[ 42.382614] ? ___sys_sendmsg+0x167/0x930
[ 42.383173] ? lock_downgrade+0x660/0x660
[ 42.383727] inet_sendmsg+0x123/0x500
[ 42.384226] ? inet_sendmsg+0x123/0x500
[ 42.384748] ? inet_recvmsg+0x540/0x540
[ 42.385263] sock_sendmsg+0xca/0x110
[ 42.385758] SYSC_sendto+0x217/0x380
[ 42.386249] ? SYSC_connect+0x310/0x310
[ 42.386783] ? __might_fault+0x110/0x1d0
[ 42.387324] ? lock_downgrade+0x660/0x660
[ 42.387880] ? __fget_light+0xa1/0x1f0
[ 42.388403] ? __fdget+0x18/0x20
[ 42.388851] ? sock_common_setsockopt+0x95/0xd0
[ 42.389472] ? SyS_setsockopt+0x17f/0x260
[ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe
[ 42.390650] SyS_sendto+0x40/0x50
[ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.391731] RIP: 0033:0x7fbbb711e383
[ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c
[ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383
[ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003
[ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018
[ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad
[ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00
[ 42.397257]
[ 42.397411] Allocated by task 3789:
[ 42.397702] save_stack_trace+0x16/0x20
[ 42.398005] save_stack+0x46/0xd0
[ 42.398267] kasan_kmalloc+0xad/0xe0
[ 42.398548] kasan_slab_alloc+0x12/0x20
[ 42.398848] __kmalloc_node_track_caller+0xcb/0x380
[ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0
[ 42.399654] __alloc_skb+0xf8/0x580
[ 42.400003] sock_wmalloc+0xab/0xf0
[ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0
[ 42.400813] ip6_append_data+0x1a8/0x2f0
[ 42.401122] rawv6_sendmsg+0x11ee/0x2db0
[ 42.401505] inet_sendmsg+0x123/0x500
[ 42.401860] sock_sendmsg+0xca/0x110
[ 42.402209] ___sys_sendmsg+0x7cb/0x930
[ 42.402582] __sys_sendmsg+0xd9/0x190
[ 42.402941] SyS_sendmsg+0x2d/0x50
[ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.403718]
[ 42.403871] Freed by task 1794:
[ 42.404146] save_stack_trace+0x16/0x20
[ 42.404515] save_stack+0x46/0xd0
[ 42.404827] kasan_slab_free+0x72/0xc0
[ 42.405167] kfree+0xe8/0x2b0
[ 42.405462] skb_free_head+0x74/0xb0
[ 42.405806] skb_release_data+0x30e/0x3a0
[ 42.406198] skb_release_all+0x4a/0x60
[ 42.406563] consume_skb+0x113/0x2e0
[ 42.406910] skb_free_datagram+0x1a/0xe0
[ 42.407288] netlink_recvmsg+0x60d/0xe40
[ 42.407667] sock_recvmsg+0xd7/0x110
[ 42.408022] ___sys_recvmsg+0x25c/0x580
[ 42.408395] __sys_recvmsg+0xd6/0x190
[ 42.408753] SyS_recvmsg+0x2d/0x50
[ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.409513]
[ 42.409665] The buggy address belongs to the object at ffff88000969e780
[ 42.409665] which belongs to the cache kmalloc-512 of size 512
[ 42.410846] The buggy address is located 24 bytes inside of
[ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980)
[ 42.411941] The buggy address belongs to the page:
[ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0
[ 42.413298] flags: 0x100000000008100(slab|head)
[ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c
[ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000
[ 42.415074] page dumped because: kasan: bad access detected
[ 42.415604]
[ 42.415757] Memory state around the buggy address:
[ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 42.418273] ^
[ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419882] ==================================================================
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Signed-off-by: Craig Gallek <kraig@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Low
| 168,131
|
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: dissect_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL;
proto_tree *agg_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint version, flags;
gint tot_len, data_len;
guint data_type;
guint32 dlt;
guint32 n_ext_flags = 0;
guint32 ampdu_id = 0;
fragment_head *fd_head = NULL;
fragment_item *ft_fdh = NULL;
gint mpdu_count = 0;
gchar *mpdu_str;
gboolean first_mpdu = TRUE;
guint last_frame = 0;
gint len_remain, /*pad_len = 0,*/ ampdu_len = 0;
struct ieee_802_11_phdr phdr;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPI");
col_clear(pinfo->cinfo, COL_INFO);
version = tvb_get_guint8(tvb, offset);
flags = tvb_get_guint8(tvb, offset + 1);
tot_len = tvb_get_letohs(tvb, offset+2);
dlt = tvb_get_letohl(tvb, offset+4);
col_add_fstr(pinfo->cinfo, COL_INFO, "PPI version %u, %u bytes",
version, tot_len);
/* Dissect the packet */
if (tree) {
ti = proto_tree_add_protocol_format(tree, proto_ppi,
tvb, 0, tot_len, "PPI version %u, %u bytes", version, tot_len);
ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph);
proto_tree_add_item(ppi_tree, hf_ppi_head_version,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags);
proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_tree, hf_ppi_head_len,
tvb, offset + 2, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_tree, hf_ppi_head_dlt,
tvb, offset + 4, 4, ENC_LITTLE_ENDIAN);
}
tot_len -= PPI_V0_HEADER_LEN;
offset += 8;
/* We don't have any 802.11 metadata yet. */
memset(&phdr, 0, sizeof(phdr));
phdr.fcs_len = -1;
phdr.decrypted = FALSE;
phdr.datapad = FALSE;
phdr.phy = PHDR_802_11_PHY_UNKNOWN;
phdr.presence_flags = 0;
while (tot_len > 0) {
data_type = tvb_get_letohs(tvb, offset);
data_len = tvb_get_letohs(tvb, offset + 2) + 4;
tot_len -= data_len;
switch (data_type) {
case PPI_80211_COMMON:
dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr);
break;
case PPI_80211N_MAC:
dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len,
TRUE, &n_ext_flags, &du_id, &phdr);
break;
case PPI_80211N_MAC_PHY:
dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset,
data_len, &n_ext_flags, &du_id, &phdr);
break;
case PPI_SPECTRUM_MAP:
ADD_BASIC_TAG(hf_spectrum_map);
break;
case PPI_PROCESS_INFO:
ADD_BASIC_TAG(hf_process_info);
break;
case PPI_CAPTURE_INFO:
ADD_BASIC_TAG(hf_capture_info);
break;
case PPI_AGGREGATION_EXTENSION:
dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len);
break;
case PPI_8023_EXTENSION:
dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len);
break;
case PPI_GPS_INFO:
if (ppi_gps_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_VECTOR_INFO:
if (ppi_vector_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_SENSOR_INFO:
if (ppi_sensor_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_ANTENNA_INFO:
if (ppi_antenna_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree);
}
break;
case FNET_PRIVATE:
if (ppi_fnet_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree);
}
break;
default:
proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA);
}
offset += data_len;
if (IS_PPI_FLAG_ALIGN(flags)){
offset += PADDING4(offset);
}
}
if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) {
len_remain = tvb_captured_length_remaining(tvb, offset);
#if 0 /* XXX: pad_len never actually used ?? */
if (DOT11N_MORE_AGGREGATES(n_ext_flags)) {
pad_len = PADDING4(len_remain);
}
#endif
pinfo->fragmented = TRUE;
/* Make sure we aren't going to go past AGGREGATE_MAX
* and caclulate our full A-MPDU length */
fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);
while (fd_head) {
ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4;
fd_head = fd_head->next;
}
if (ampdu_len > AGGREGATE_MAX) {
if (tree) {
proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, "Aggregate length greater than maximum (%u)", AGGREGATE_MAX);
THROW(ReportedBoundsError);
} else {
return;
}
}
/*
* Note that we never actually reassemble our A-MPDUs. Doing
* so would require prepending each MPDU with an A-MPDU delimiter
* and appending it with padding, only to hand it off to some
* routine which would un-do the work we just did. We're using
* the reassembly code to track MPDU sizes and frame numbers.
*/
/*??fd_head = */fragment_add_seq_next(&du_reassembly_table,
tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE);
pinfo->fragmented = TRUE;
/* Do reassembly? */
fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);
/* Show our fragments */
if (fd_head && tree) {
ft_fdh = fd_head;
/* List our fragments */
seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1,
ett_ampdu_segments, &ti, "A-MPDU (%u bytes w/hdrs):", ampdu_len);
PROTO_ITEM_SET_GENERATED(ti);
while (ft_fdh) {
if (ft_fdh->tvb_data && ft_fdh->len) {
last_frame = ft_fdh->frame;
if (!first_mpdu)
proto_item_append_text(ti, ",");
first_mpdu = FALSE;
proto_item_append_text(ti, " #%u(%u)",
ft_fdh->frame, ft_fdh->len);
proto_tree_add_uint_format(seg_tree, hf_ampdu_segment,
tvb, 0, 0, last_frame,
"Frame: %u (%u byte%s)",
last_frame,
ft_fdh->len,
plurality(ft_fdh->len, "", "s"));
}
ft_fdh = ft_fdh->next;
}
if (last_frame && last_frame != pinfo->fd->num)
proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in,
tvb, 0, 0, last_frame);
}
if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) {
if (tree) {
ti = proto_tree_add_protocol_format(tree,
proto_get_id_by_filter_name("wlan_aggregate"),
tvb, 0, tot_len, "IEEE 802.11 Aggregate MPDU");
agg_tree = proto_item_add_subtree(ti, ett_ampdu);
}
while (fd_head) {
if (fd_head->tvb_data && fd_head->len) {
mpdu_count++;
mpdu_str = wmem_strdup_printf(wmem_packet_scope(), "MPDU #%d", mpdu_count);
next_tvb = tvb_new_chain(tvb, fd_head->tvb_data);
add_new_data_source(pinfo, next_tvb, mpdu_str);
ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str);
call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr);
}
fd_head = fd_head->next;
}
proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count);
pinfo->fragmented=FALSE;
} else {
next_tvb = tvb_new_subset_remaining(tvb, offset);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE 802.11n");
col_set_str(pinfo->cinfo, COL_INFO, "Unreassembled A-MPDU data");
call_dissector(data_handle, next_tvb, pinfo, tree);
}
return;
}
next_tvb = tvb_new_subset_remaining(tvb, offset);
/*
* You can't just call an arbitrary subdissector based on a
* LINKTYPE_ value, because they may expect a particular
* pseudo-header to be passed to them.
*
* So we look for LINKTYPE_IEEE802_11, which is 105, and, if
* that's what the LINKTYPE_ value is, pass it a pointer
* to a struct ieee_802_11_phdr; otherwise, we pass it
* a null pointer - if it actually matters, we need to
* construct the appropriate pseudo-header and pass that.
*/
if (dlt == 105) {
/* LINKTYPE_IEEE802_11 */
call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr);
} else {
/* Everything else. This will pass a NULL data argument. */
dissector_try_uint(wtap_encap_dissector_table,
wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree);
}
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: epan/dissectors/packet-pktap.c in the Ethernet dissector in Wireshark 2.x before 2.0.4 mishandles the packet-header data type, which allows remote attackers to cause a denial of service (application crash) via a crafted packet.
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <guy@alum.mit.edu>
|
Medium
| 167,144
|
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 ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *isk = inet_sk(sk);
int family = sk->sk_family;
struct sk_buff *skb;
int copied, err;
pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
if (flags & MSG_ERRQUEUE) {
if (family == AF_INET) {
return ip_recv_error(sk, msg, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
return pingv6_ops.ipv6_recv_error(sk, msg, len);
#endif
}
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* Don't bother checking the checksum */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address and add cmsg data. */
if (family == AF_INET) {
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
sin->sin_family = AF_INET;
sin->sin_port = 0 /* skb->h.uh->source */;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
if (isk->cmsg_flags)
ip_cmsg_recv(msg, skb);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *ip6 = ipv6_hdr(skb);
struct sockaddr_in6 *sin6 =
(struct sockaddr_in6 *)msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ip6->saddr;
sin6->sin6_flowinfo = 0;
if (np->sndflow)
sin6->sin6_flowinfo = ip6_flowinfo(ip6);
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
*addr_len = sizeof(*sin6);
if (inet6_sk(sk)->rxopt.all)
pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);
#endif
} else {
BUG();
}
err = copied;
done:
skb_free_datagram(sk, skb);
out:
pr_debug("ping_recvmsg -> %d\n", err);
return err;
}
Vulnerability Type: DoS
CWE ID:
Summary: The ping_recvmsg function in net/ipv4/ping.c in the Linux kernel before 3.12.4 does not properly interact with read system calls on ping sockets, which allows local users to cause a denial of service (NULL pointer dereference and system crash) by leveraging unspecified privileges to execute a crafted application.
Commit Message: ping: prevent NULL pointer dereference on write to msg_name
A plain read() on a socket does set msg->msg_name to NULL. So check for
NULL pointer first.
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
|
Low
| 165,937
|
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 pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
{
int i, id, dummy;
char *buf, *c;
long start, sz;
start = ftell(fp);
/* Load all kids for all xref tables (versions) */
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))
{
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to trailer */
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
buf = malloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
{
free(buf);
continue;
}
/* Jump to catalog (root) */
id = atoi(c + strlen("/Root") + 1);
free(buf);
buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);
if (!buf || !(c = strstr(buf, "/Pages")))
{
free(buf);
continue;
}
/* Start at the first Pages obj and get kids */
id = atoi(c + strlen("/Pages") + 1);
load_kids(fp, id, &pdf->xrefs[i]);
free(buf);
}
}
fseek(fp, start, SEEK_SET);
}
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,571
|
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: mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ip6t_entry *e = (struct ip6t_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ip6t_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct ip6t_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 &&
unconditional(&e->ipv6)) || visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ip6t_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ip6t_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ip6t_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ip6t_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
Vulnerability Type: DoS Overflow +Priv Mem. Corr.
CWE ID: CWE-119
Summary: The netfilter subsystem in the Linux kernel through 4.5.2 does not validate certain offset fields, which allows local users to gain privileges or cause a denial of service (heap memory corruption) via an IPT_SO_SET_REPLACE setsockopt call.
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <hawkes@google.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
|
Low
| 167,375
|
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: QuicErrorCode QuicStreamSequencerBuffer::OnStreamData(
QuicStreamOffset starting_offset,
QuicStringPiece data,
QuicTime timestamp,
size_t* const bytes_buffered,
std::string* error_details) {
CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed";
*bytes_buffered = 0;
QuicStreamOffset offset = starting_offset;
size_t size = data.size();
if (size == 0) {
*error_details = "Received empty stream frame without FIN.";
return QUIC_EMPTY_STREAM_FRAME_NO_FIN;
}
std::list<Gap>::iterator current_gap = gaps_.begin();
while (current_gap != gaps_.end() && current_gap->end_offset <= offset) {
++current_gap;
}
DCHECK(current_gap != gaps_.end());
if (offset < current_gap->begin_offset &&
offset + size <= current_gap->begin_offset) {
QUIC_DVLOG(1) << "Duplicated data at offset: " << offset
<< " length: " << size;
return QUIC_NO_ERROR;
}
if (offset < current_gap->begin_offset &&
offset + size > current_gap->begin_offset) {
string prefix(data.data(), data.length() < 128 ? data.length() : 128);
*error_details =
QuicStrCat("Beginning of received data overlaps with buffered data.\n",
"New frame range [", offset, ", ", offset + size,
") with first 128 bytes: ", prefix, "\n",
"Currently received frames: ", GapsDebugString(), "\n",
"Current gaps: ", ReceivedFramesDebugString());
return QUIC_OVERLAPPING_STREAM_DATA;
}
if (offset + size > current_gap->end_offset) {
string prefix(data.data(), data.length() < 128 ? data.length() : 128);
*error_details = QuicStrCat(
"End of received data overlaps with buffered data.\nNew frame range [",
offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n",
"Currently received frames: ", ReceivedFramesDebugString(), "\n",
"Current gaps: ", GapsDebugString());
return QUIC_OVERLAPPING_STREAM_DATA;
}
if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_) {
*error_details = "Received data beyond available range.";
return QUIC_INTERNAL_ERROR;
}
if (current_gap->begin_offset != starting_offset &&
current_gap->end_offset != starting_offset + data.length() &&
gaps_.size() >= kMaxNumGapsAllowed) {
*error_details = "Too many gaps created for this stream.";
return QUIC_TOO_MANY_FRAME_GAPS;
}
size_t total_written = 0;
size_t source_remaining = size;
const char* source = data.data();
while (source_remaining > 0) {
const size_t write_block_num = GetBlockIndex(offset);
const size_t write_block_offset = GetInBlockOffset(offset);
DCHECK_GT(blocks_count_, write_block_num);
size_t block_capacity = GetBlockCapacity(write_block_num);
size_t bytes_avail = block_capacity - write_block_offset;
if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) {
bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset;
}
if (blocks_ == nullptr) {
blocks_.reset(new BufferBlock*[blocks_count_]());
for (size_t i = 0; i < blocks_count_; ++i) {
blocks_[i] = nullptr;
}
}
if (write_block_num >= blocks_count_) {
*error_details = QuicStrCat(
"QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds."
"write offset = ",
offset, " write_block_num = ", write_block_num,
" blocks_count_ = ", blocks_count_);
return QUIC_STREAM_SEQUENCER_INVALID_STATE;
}
if (blocks_ == nullptr) {
*error_details =
"QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null";
return QUIC_STREAM_SEQUENCER_INVALID_STATE;
}
if (blocks_[write_block_num] == nullptr) {
blocks_[write_block_num] = new BufferBlock();
}
const size_t bytes_to_copy =
std::min<size_t>(bytes_avail, source_remaining);
char* dest = blocks_[write_block_num]->buffer + write_block_offset;
QUIC_DVLOG(1) << "Write at offset: " << offset
<< " length: " << bytes_to_copy;
if (dest == nullptr || source == nullptr) {
*error_details = QuicStrCat(
"QuicStreamSequencerBuffer error: OnStreamData()"
" dest == nullptr: ",
(dest == nullptr), " source == nullptr: ", (source == nullptr),
" Writing at offset ", offset, " Gaps: ", GapsDebugString(),
" Remaining frames: ", ReceivedFramesDebugString(),
" total_bytes_read_ = ", total_bytes_read_);
return QUIC_STREAM_SEQUENCER_INVALID_STATE;
}
memcpy(dest, source, bytes_to_copy);
source += bytes_to_copy;
source_remaining -= bytes_to_copy;
offset += bytes_to_copy;
total_written += bytes_to_copy;
}
DCHECK_GT(total_written, 0u);
*bytes_buffered = total_written;
UpdateGapList(current_gap, starting_offset, total_written);
frame_arrival_time_map_.insert(
std::make_pair(starting_offset, FrameInfo(size, timestamp)));
num_bytes_buffered_ += total_written;
return QUIC_NO_ERROR;
}
Vulnerability Type: Exec Code
CWE ID: CWE-787
Summary: Out-of-bounds Write in the QUIC networking stack in Google Chrome prior to 63.0.3239.84 allowed a remote attacker to gain code execution via a malicious server.
Commit Message: Fix OOB Write in QuicStreamSequencerBuffer::OnStreamData
BUG=778505
Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I1dfd1d26a2c7ee8fe047f7fe6e4ac2e9b97efa52
Reviewed-on: https://chromium-review.googlesource.com/748282
Commit-Queue: Ryan Hamilton <rch@chromium.org>
Reviewed-by: Zhongyi Shi <zhongyi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#513144}
|
Medium
| 172,923
|
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 HTML_put_string(HTStructured * me, const char *s)
{
#ifdef USE_PRETTYSRC
char *translated_string = NULL;
#endif
if (s == NULL || (LYMapsOnly && me->sp[0].tag_number != HTML_OBJECT))
return;
#ifdef USE_PRETTYSRC
if (psrc_convert_string) {
StrAllocCopy(translated_string, s);
TRANSLATE_AND_UNESCAPE_ENTITIES(&translated_string, TRUE, FALSE);
s = (const char *) translated_string;
}
#endif
switch (me->sp[0].tag_number) {
case HTML_COMMENT:
break; /* Do Nothing */
case HTML_TITLE:
HTChunkPuts(&me->title, s);
break;
case HTML_STYLE:
HTChunkPuts(&me->style_block, s);
break;
case HTML_SCRIPT:
HTChunkPuts(&me->script, s);
break;
case HTML_PRE: /* Formatted text */
case HTML_LISTING: /* Literal text */
case HTML_XMP:
case HTML_PLAINTEXT:
/*
* We guarantee that the style is up-to-date in begin_litteral
*/
HText_appendText(me->text, s);
break;
case HTML_OBJECT:
HTChunkPuts(&me->object, s);
break;
case HTML_TEXTAREA:
HTChunkPuts(&me->textarea, s);
break;
case HTML_SELECT:
case HTML_OPTION:
HTChunkPuts(&me->option, s);
break;
case HTML_MATH:
HTChunkPuts(&me->math, s);
break;
default: /* Free format text? */
if (!me->sp->style->freeFormat) {
/*
* If we are within a preformatted text style not caught by the
* cases above (HTML_PRE or similar may not be the last element
* pushed on the style stack). - kw
*/
#ifdef USE_PRETTYSRC
if (psrc_view) {
/*
* We do this so that a raw '\r' in the string will not be
* interpreted as an internal request to break a line - passing
* '\r' to HText_appendText is treated by it as a request to
* insert a blank line - VH
*/
for (; *s; ++s)
HTML_put_character(me, *s);
} else
#endif
HText_appendText(me->text, s);
break;
} else {
const char *p = s;
char c;
if (me->style_change) {
for (; *p && ((*p == '\n') || (*p == '\r') ||
(*p == ' ') || (*p == '\t')); p++) ; /* Ignore leaders */
if (!*p)
break;
UPDATE_STYLE;
}
for (; *p; p++) {
if (*p == 13 && p[1] != 10) {
/*
* Treat any '\r' which is not followed by '\n' as '\n', to
* account for macintosh lineend in ALT attributes etc. -
* kw
*/
c = '\n';
} else {
c = *p;
}
if (me->style_change) {
if ((c == '\n') || (c == ' ') || (c == '\t'))
continue; /* Ignore it */
UPDATE_STYLE;
}
if (c == '\n') {
if (!FIX_JAPANESE_SPACES) {
if (me->in_word) {
if (HText_getLastChar(me->text) != ' ')
HText_appendCharacter(me->text, ' ');
me->in_word = NO;
}
}
} else if (c == ' ' || c == '\t') {
if (HText_getLastChar(me->text) != ' ')
HText_appendCharacter(me->text, ' ');
} else if (c == '\r') {
/* ignore */
} else {
HText_appendCharacter(me->text, c);
me->in_word = YES;
}
/* set the Last Character */
if (c == '\n' || c == '\t') {
/* set it to a generic separator */
HText_setLastChar(me->text, ' ');
} else if (c == '\r' &&
HText_getLastChar(me->text) == ' ') {
/*
* \r's are ignored. In order to keep collapsing spaces
* correctly, we must default back to the previous
* separator, if there was one. So we set LastChar to a
* generic separator.
*/
HText_setLastChar(me->text, ' ');
} else {
HText_setLastChar(me->text, c);
}
} /* for */
}
} /* end switch */
#ifdef USE_PRETTYSRC
if (psrc_convert_string) {
psrc_convert_string = FALSE;
FREE(translated_string);
}
#endif
}
Vulnerability Type:
CWE ID: CWE-416
Summary: Lynx before 2.8.9dev.16 is vulnerable to a use after free in the HTML parser resulting in memory disclosure, because HTML_put_string() can append a chunk onto itself.
Commit Message: snapshot of project "lynx", label v2-8-9dev_15b
|
Low
| 167,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: void InProcessBrowserTest::PrepareTestCommandLine(CommandLine* command_line) {
test_launcher_utils::PrepareBrowserCommandLineForTests(command_line);
command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType);
#if defined(OS_WIN)
if (command_line->HasSwitch(switches::kAshBrowserTests)) {
command_line->AppendSwitchNative(switches::kViewerLaunchViaAppId,
win8::test::kDefaultTestAppUserModelId);
command_line->AppendSwitch(switches::kSilentLaunch);
}
#endif
#if defined(OS_MACOSX)
base::FilePath subprocess_path;
PathService::Get(base::FILE_EXE, &subprocess_path);
subprocess_path = subprocess_path.DirName().DirName();
DCHECK_EQ(subprocess_path.BaseName().value(), "Contents");
subprocess_path =
subprocess_path.Append("Versions").Append(chrome::kChromeVersion);
subprocess_path =
subprocess_path.Append(chrome::kHelperProcessExecutablePath);
command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,
subprocess_path);
#endif
if (exit_when_last_browser_closes_)
command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests);
if (command_line->GetArgs().empty())
command_line->AppendArg(url::kAboutBlankURL);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The SVG implementation in Blink, as used in Google Chrome before 31.0.1650.48, allows remote attackers to cause a denial of service (out-of-bounds read) by leveraging the use of tree order, rather than transitive dependency order, for layout.
Commit Message: Make the policy fetch for first time login blocking
The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users.
BUG=334584
Review URL: https://codereview.chromium.org/330843002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98
|
Medium
| 171,152
|
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: XGetFeedbackControl(
register Display *dpy,
XDevice *dev,
int *num_feedbacks)
{
XFeedbackState *Feedback = NULL;
XFeedbackState *Sav = NULL;
xFeedbackState *f = NULL;
xFeedbackState *sav = NULL;
xGetFeedbackControlReq *req;
xGetFeedbackControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1)
return NULL;
GetReq(GetFeedbackControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetFeedbackControl;
req->deviceid = dev->device_id;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
int i;
*num_feedbacks = rep.num_feedbacks;
if (rep.length < (INT_MAX >> 2)) {
nbytes = rep.length << 2;
f = Xmalloc(nbytes);
}
if (!f) {
_XEatDataWords(dpy, rep.length);
goto out;
goto out;
}
sav = f;
_XRead(dpy, (char *)f, nbytes);
for (i = 0; i < *num_feedbacks; i++) {
if (f->length > nbytes)
goto out;
nbytes -= f->length;
break;
case PtrFeedbackClass:
size += sizeof(XPtrFeedbackState);
break;
case IntegerFeedbackClass:
size += sizeof(XIntegerFeedbackState);
break;
case StringFeedbackClass:
{
xStringFeedbackState *strf = (xStringFeedbackState *) f;
case StringFeedbackClass:
{
xStringFeedbackState *strf = (xStringFeedbackState *) f;
size += sizeof(XStringFeedbackState) +
(strf->num_syms_supported * sizeof(KeySym));
}
size += sizeof(XBellFeedbackState);
break;
default:
size += f->length;
break;
}
if (size > INT_MAX)
goto out;
f = (xFeedbackState *) ((char *)f + f->length);
}
Feedback = Xmalloc(size);
if (!Feedback)
goto out;
Sav = Feedback;
f = sav;
for (i = 0; i < *num_feedbacks; i++) {
switch (f->class) {
case KbdFeedbackClass:
{
xKbdFeedbackState *k;
XKbdFeedbackState *K;
k = (xKbdFeedbackState *) f;
K = (XKbdFeedbackState *) Feedback;
K->class = k->class;
K->length = sizeof(XKbdFeedbackState);
K->id = k->id;
K->click = k->click;
K->percent = k->percent;
K->pitch = k->pitch;
K->duration = k->duration;
K->led_mask = k->led_mask;
K->global_auto_repeat = k->global_auto_repeat;
memcpy((char *)&K->auto_repeats[0],
(char *)&k->auto_repeats[0], 32);
break;
}
case PtrFeedbackClass:
{
xPtrFeedbackState *p;
XPtrFeedbackState *P;
p = (xPtrFeedbackState *) f;
P = (XPtrFeedbackState *) Feedback;
P->class = p->class;
P->length = sizeof(XPtrFeedbackState);
P->id = p->id;
P->accelNum = p->accelNum;
P->accelDenom = p->accelDenom;
P->threshold = p->threshold;
break;
}
case IntegerFeedbackClass:
{
xIntegerFeedbackState *ifs;
XIntegerFeedbackState *I;
ifs = (xIntegerFeedbackState *) f;
I = (XIntegerFeedbackState *) Feedback;
I->class = ifs->class;
I->length = sizeof(XIntegerFeedbackState);
I->id = ifs->id;
I->resolution = ifs->resolution;
I->minVal = ifs->min_value;
I->maxVal = ifs->max_value;
break;
}
case StringFeedbackClass:
{
xStringFeedbackState *s;
XStringFeedbackState *S;
s = (xStringFeedbackState *) f;
S = (XStringFeedbackState *) Feedback;
S->class = s->class;
S->length = sizeof(XStringFeedbackState) +
(s->num_syms_supported * sizeof(KeySym));
S->id = s->id;
S->max_symbols = s->max_symbols;
S->num_syms_supported = s->num_syms_supported;
S->syms_supported = (KeySym *) (S + 1);
memcpy((char *)S->syms_supported, (char *)(s + 1),
(S->num_syms_supported * sizeof(KeySym)));
break;
}
case LedFeedbackClass:
{
xLedFeedbackState *l;
XLedFeedbackState *L;
l = (xLedFeedbackState *) f;
L = (XLedFeedbackState *) Feedback;
L->class = l->class;
L->length = sizeof(XLedFeedbackState);
L->id = l->id;
L->led_values = l->led_values;
L->led_mask = l->led_mask;
break;
}
case BellFeedbackClass:
{
xBellFeedbackState *b;
XBellFeedbackState *B;
b = (xBellFeedbackState *) f;
B = (XBellFeedbackState *) Feedback;
B->class = b->class;
B->length = sizeof(XBellFeedbackState);
B->id = b->id;
B->percent = b->percent;
B->pitch = b->pitch;
B->duration = b->duration;
break;
}
default:
break;
}
f = (xFeedbackState *) ((char *)f + f->length);
Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length);
}
}
out:
XFree((char *)sav);
UnlockDisplay(dpy);
SyncHandle();
return (Sav);
}
Vulnerability Type: DoS
CWE ID: CWE-284
Summary: X.org libXi before 1.7.7 allows remote X servers to cause a denial of service (infinite loop) via vectors involving length fields.
Commit Message:
|
Low
| 164,919
|
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: xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) {
int i = 0;
int j = comp->nbStep - 1;
while (j > i) {
register xmlChar *tmp;
register xsltOp op;
register xmlXPathCompExprPtr expr;
register int t;
tmp = comp->steps[i].value;
comp->steps[i].value = comp->steps[j].value;
comp->steps[j].value = tmp;
tmp = comp->steps[i].value2;
comp->steps[i].value2 = comp->steps[j].value2;
comp->steps[j].value2 = tmp;
tmp = comp->steps[i].value3;
comp->steps[i].value3 = comp->steps[j].value3;
comp->steps[j].value3 = tmp;
op = comp->steps[i].op;
comp->steps[i].op = comp->steps[j].op;
comp->steps[j].op = op;
expr = comp->steps[i].comp;
comp->steps[i].comp = comp->steps[j].comp;
comp->steps[j].comp = expr;
t = comp->steps[i].previousExtra;
comp->steps[i].previousExtra = comp->steps[j].previousExtra;
comp->steps[j].previousExtra = t;
t = comp->steps[i].indexExtra;
comp->steps[i].indexExtra = comp->steps[j].indexExtra;
comp->steps[j].indexExtra = t;
t = comp->steps[i].lenExtra;
comp->steps[i].lenExtra = comp->steps[j].lenExtra;
comp->steps[j].lenExtra = t;
j--;
i++;
}
xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0);
/*
* detect consecutive XSLT_OP_PREDICATE indicating a direct
* matching should be done.
*/
for (i = 0;i < comp->nbStep - 1;i++) {
if ((comp->steps[i].op == XSLT_OP_PREDICATE) &&
(comp->steps[i + 1].op == XSLT_OP_PREDICATE)) {
comp->direct = 1;
if (comp->pattern[0] != '/') {
xmlChar *query;
query = xmlStrdup((const xmlChar *)"//");
query = xmlStrcat(query, comp->pattern);
xmlFree((xmlChar *) comp->pattern);
comp->pattern = query;
}
break;
}
}
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: numbers.c in libxslt before 1.1.29, as used in Google Chrome before 51.0.2704.63, mishandles namespace nodes, which allows remote attackers to cause a denial of service (out-of-bounds heap memory access) or possibly have unspecified other impact via a crafted document.
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
|
High
| 173,313
|
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 bool IsManualFallbackForFillingEnabled() {
return base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksFilling) &&
!IsPreLollipopAndroid();
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The provisional-load commit implementation in WebKit/Source/bindings/core/v8/WindowProxy.cpp in Google Chrome before 47.0.2526.73 allows remote attackers to bypass the Same Origin Policy by leveraging a delay in window proxy clearing.
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <vabr@chromium.org>
Commit-Queue: NIKHIL SAHNI <nikhil.sahni@samsung.com>
Cr-Commit-Position: refs/heads/master@{#534923}
|
Low
| 171,748
|
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: LayerTreeHost::LayerTreeHost(InitParams* params, CompositorMode mode)
: micro_benchmark_controller_(this),
image_worker_task_runner_(params->image_worker_task_runner),
compositor_mode_(mode),
ui_resource_manager_(base::MakeUnique<UIResourceManager>()),
client_(params->client),
rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()),
settings_(*params->settings),
debug_state_(settings_.initial_debug_state),
id_(s_layer_tree_host_sequence_number.GetNext() + 1),
task_graph_runner_(params->task_graph_runner),
event_listener_properties_(),
mutator_host_(params->mutator_host) {
DCHECK(task_graph_runner_);
DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_);
DCHECK(!settings_.enable_checker_imaging ||
settings_.image_decode_tasks_enabled);
mutator_host_->SetMutatorHostClient(this);
rendering_stats_instrumentation_->set_record_rendering_stats(
debug_state_.RecordRenderingStats());
}
Vulnerability Type:
CWE ID: CWE-362
Summary: A race condition in navigation in Google Chrome prior to 58.0.3029.81 for Linux, Windows, and Mac allowed a remote attacker to spoof the contents of the Omnibox (URL bar) via a crafted HTML page.
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
TBR=danakj@chromium.org, creis@chromium.org
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
|
High
| 172,394
|
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: RenderFrameHostManager::DetermineSiteInstanceForURL(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* current_instance,
SiteInstance* dest_instance,
ui::PageTransition transition,
bool dest_is_restore,
bool dest_is_view_source_mode,
bool force_browsing_instance_swap,
bool was_server_redirect) {
SiteInstanceImpl* current_instance_impl =
static_cast<SiteInstanceImpl*>(current_instance);
NavigationControllerImpl& controller =
delegate_->GetControllerForRenderManager();
BrowserContext* browser_context = controller.GetBrowserContext();
if (dest_instance) {
if (force_browsing_instance_swap) {
CHECK(!dest_instance->IsRelatedSiteInstance(
render_frame_host_->GetSiteInstance()));
}
return SiteInstanceDescriptor(dest_instance);
}
if (force_browsing_instance_swap)
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kProcessPerSite) &&
ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
return SiteInstanceDescriptor(current_instance_impl);
}
if (SiteIsolationPolicy::AreCrossProcessFramesPossible() &&
!frame_tree_node_->IsMainFrame()) {
SiteInstance* parent_site_instance =
frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) &&
dest_url.SchemeIs(kChromeUIScheme)) {
return SiteInstanceDescriptor(parent_site_instance);
}
}
if (!current_instance_impl->HasSite()) {
bool use_process_per_site =
RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
use_process_per_site) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
}
if (current_instance_impl->HasWrongProcessForURL(dest_url))
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
if (dest_is_view_source_mode)
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, dest_url)) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
}
if (dest_is_restore &&
GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
current_instance_impl->SetSite(dest_url);
}
return SiteInstanceDescriptor(current_instance_impl);
}
NavigationEntry* current_entry = controller.GetLastCommittedEntry();
if (interstitial_page_) {
current_entry = controller.GetEntryAtOffset(-1);
}
if (current_entry &&
current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
!IsRendererDebugURL(dest_url)) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
}
GURL about_blank(url::kAboutBlankURL);
GURL about_srcdoc(content::kAboutSrcDocURL);
bool dest_is_data_or_about = dest_url == about_srcdoc ||
dest_url == about_blank ||
dest_url.scheme() == url::kDataScheme;
if (source_instance && dest_is_data_or_about && !was_server_redirect)
return SiteInstanceDescriptor(source_instance);
if (IsCurrentlySameSite(render_frame_host_.get(), dest_url))
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) {
if (!frame_tree_node_->IsMainFrame()) {
RenderFrameHostImpl* main_frame =
frame_tree_node_->frame_tree()->root()->current_frame_host();
if (IsCurrentlySameSite(main_frame, dest_url))
return SiteInstanceDescriptor(main_frame->GetSiteInstance());
}
if (frame_tree_node_->opener()) {
RenderFrameHostImpl* opener_frame =
frame_tree_node_->opener()->current_frame_host();
if (IsCurrentlySameSite(opener_frame, dest_url))
return SiteInstanceDescriptor(opener_frame->GetSiteInstance());
}
}
if (!frame_tree_node_->IsMainFrame() &&
SiteIsolationPolicy::IsTopDocumentIsolationEnabled() &&
!SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context,
dest_url)) {
if (GetContentClient()
->browser()
->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation(
dest_url, current_instance)) {
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
}
return SiteInstanceDescriptor(
browser_context, dest_url,
SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME);
}
if (!frame_tree_node_->IsMainFrame()) {
RenderFrameHostImpl* parent =
frame_tree_node_->parent()->current_frame_host();
bool dest_url_requires_dedicated_process =
SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context,
dest_url);
if (!parent->GetSiteInstance()->RequiresDedicatedProcess() &&
!dest_url_requires_dedicated_process) {
return SiteInstanceDescriptor(parent->GetSiteInstance());
}
}
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Inappropriate implementation in interstitials in Google Chrome prior to 60.0.3112.78 for Mac allowed a remote attacker to spoof the contents of the omnibox via a crafted HTML page.
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
|
Medium
| 172,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: static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version)
{
zval **oid, **value, **type;
char *a1, *a2, *a3, *a4, *a5, *a6, *a7;
int a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len;
zend_bool use_orignames = 0, suffix_keys = 0;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
int argc = ZEND_NUM_ARGS();
struct objid_query objid_query;
php_snmp_session *session;
int session_less_mode = (getThis() == NULL);
php_snmp_object *snmp_object;
php_snmp_object glob_snmp_object;
objid_query.max_repetitions = -1;
objid_query.non_repeaters = 0;
objid_query.valueretrieval = SNMP_G(valueretrieval);
objid_query.oid_increasing_check = TRUE;
if (session_less_mode) {
if (version == SNMP_VERSION_3) {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "ssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc TSRMLS_CC, "ssZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc TSRMLS_CC, "ZZZ", &oid, &type, &value) == FAILURE) {
RETURN_FALSE;
}
} else if (st & SNMP_CMD_WALK) {
if (zend_parse_parameters(argc TSRMLS_CC, "Z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) {
RETURN_FALSE;
}
if (suffix_keys) {
st |= SNMP_USE_SUFFIX_AS_KEYS;
}
} else if (st & SNMP_CMD_GET) {
if (zend_parse_parameters(argc TSRMLS_CC, "Z|b", &oid, &use_orignames) == FAILURE) {
RETURN_FALSE;
}
if (use_orignames) {
st |= SNMP_ORIGINAL_NAMES_AS_KEYS;
}
} else {
/* SNMP_CMD_GETNEXT
*/
if (zend_parse_parameters(argc TSRMLS_CC, "Z", &oid) == FAILURE) {
RETURN_FALSE;
}
}
}
if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value TSRMLS_CC)) {
RETURN_FALSE;
}
if (session_less_mode) {
if (netsnmp_session_init(&session, version, a1, a2, timeout, retries TSRMLS_CC)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
RETURN_FALSE;
}
if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL TSRMLS_CC)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
} else {
zval *object = getThis();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
session = snmp_object->session;
if (!session) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid or uninitialized SNMP object");
efree(objid_query.vars);
RETURN_FALSE;
}
if (snmp_object->max_oids > 0) {
objid_query.step = snmp_object->max_oids;
if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */
objid_query.max_repetitions = snmp_object->max_oids;
}
}
objid_query.oid_increasing_check = snmp_object->oid_increasing_check;
objid_query.valueretrieval = snmp_object->valueretrieval;
glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print);
glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print);
glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format);
}
if (objid_query.max_repetitions < 0) {
objid_query.max_repetitions = 20; /* provide correct default value */
}
php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query);
efree(objid_query.vars);
if (session_less_mode) {
netsnmp_session_free(&session);
} else {
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format);
}
}
Vulnerability Type: DoS
CWE ID: CWE-416
Summary: ext/snmp/snmp.c in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to cause a denial of service (use-after-free and application crash) or possibly have unspecified other impact via crafted serialized data, a related issue to CVE-2016-5773.
Commit Message:
|
Low
| 164,974
|
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: vrrp_tfile_end_handler(void)
{
vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files);
struct stat statb;
FILE *tf;
int ret;
if (!tfile->file_path) {
report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname);
free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail);
return;
}
if (track_file_init == TRACK_FILE_NO_INIT)
return;
ret = stat(tfile->file_path, &statb);
if (!ret) {
if (track_file_init == TRACK_FILE_CREATE) {
/* The file exists */
return;
}
if ((statb.st_mode & S_IFMT) != S_IFREG) {
/* It is not a regular file */
report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname);
return;
}
/* Don't overwrite a file on reload */
if (reload)
return;
}
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
/* Write the value to the file */
if ((tf = fopen(tfile->file_path, "w"))) {
fprintf(tf, "%d\n", track_file_init_value);
fclose(tf);
}
else
report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname);
}
}
Vulnerability Type:
CWE ID: CWE-59
Summary: keepalived 2.0.8 didn't check for pathnames with symlinks when writing data to a temporary file upon a call to PrintData or PrintStats. This allowed local users to overwrite arbitrary files if fs.protected_symlinks is set to 0, as demonstrated by a symlink from /tmp/keepalived.data or /tmp/keepalived.stats to /etc/passwd.
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>
|
Medium
| 168,990
|
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: vips_malloc( VipsObject *object, size_t size )
{
void *buf;
buf = g_malloc( size );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), buf );
object->local_memory += size;
}
return( buf );
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: libvips before 8.7.4 generates output images from uninitialized memory locations when processing corrupted input image data because iofuncs/memory.c does not zero out allocated memory. This can result in leaking raw process memory contents through the output image.
Commit Message: zero memory on malloc
to prevent write of uninit memory under some error conditions
thanks Balint
|
Low
| 169,739
|
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 CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const
{
ParaNdis_CheckSumVerifyFlat(IpHeader,
EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum,
__FUNCTION__);
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The NetKVM Windows Virtio driver allows remote attackers to cause a denial of service (guest crash) via a crafted length value in an IP packet, as demonstrated by a value that does not account for the size of the IP options.
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
|
Low
| 170,140
|
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: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out == NULL) {
return;
}
gdImageWebpCtx(im, out, -1);
out->gd_free(out);
}
Vulnerability Type:
CWE ID: CWE-415
Summary: Double free vulnerability in the gdImageWebPtr function in the GD Graphics Library (aka libgd) before 2.2.4 allows remote attackers to have unspecified impact via large width and height values.
Commit Message: Fix double-free in gdImageWebPtr()
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org.
CVE-2016-6912
|
Low
| 168,816
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.