instruction
stringclasses 1
value | input
stringlengths 306
235k
| output
stringclasses 3
values | __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: LONG ValidateSignature(HWND hDlg, const char* path)
{
LONG r;
WINTRUST_DATA trust_data = { 0 };
WINTRUST_FILE_INFO trust_file = { 0 };
GUID guid_generic_verify = // WINTRUST_ACTION_GENERIC_VERIFY_V2
{ 0xaac56b, 0xcd44, 0x11d0,{ 0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee } };
char *signature_name;
size_t i, len;
signature_name = GetSignatureName(path);
if (signature_name == NULL) {
uprintf("PKI: Could not get signature name");
MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
return TRUST_E_NOSIGNATURE;
}
for (i = 0; i < ARRAYSIZE(cert_name); i++) {
len = strlen(cert_name[i]);
if (strncmp(signature_name, cert_name[i], len) == 0) {
if ((len >= strlen(signature_name)) || isspace(signature_name[len]))
break;
}
}
if (i >= ARRAYSIZE(cert_name)) {
uprintf("PKI: Signature '%s' is unexpected...", signature_name);
if (MessageBoxExU(hDlg, lmprintf(MSG_285, signature_name), lmprintf(MSG_283),
MB_YESNO | MB_ICONWARNING | MB_IS_RTL, selected_langid) != IDYES)
return TRUST_E_EXPLICIT_DISTRUST;
}
trust_file.cbStruct = sizeof(trust_file);
trust_file.pcwszFilePath = utf8_to_wchar(path);
if (trust_file.pcwszFilePath == NULL) {
uprintf("PKI: Unable to convert '%s' to UTF16", path);
return ERROR_SEVERITY_ERROR | FAC(FACILITY_CERT) | ERROR_NOT_ENOUGH_MEMORY;
}
trust_data.cbStruct = sizeof(trust_data);
trust_data.dwUIChoice = WTD_UI_ALL;
trust_data.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
trust_data.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN | 0x400;
trust_data.dwUnionChoice = WTD_CHOICE_FILE;
trust_data.pFile = &trust_file;
r = WinVerifyTrust(NULL, &guid_generic_verify, &trust_data);
safe_free(trust_file.pcwszFilePath);
return r;
}
Vulnerability Type: Exec Code
CWE ID: CWE-494
Summary: Akeo Consulting Rufus prior to version 2.17.1187 does not adequately validate the integrity of updates downloaded over HTTP, allowing an attacker to easily convince a user to execute arbitrary code
Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768
* This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as
it is described per its revision 11, which is the latest revision at the time of this commit,
by disabling Windows prompts, enacted during signature validation, that allow the user to
bypass the intended signature verification checks.
* It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed
certificate"), which relies on the end-user actively ignoring a Windows prompt that tells
them that the update failed the signature validation whilst also advising against running it,
is being fully addressed, even as the update protocol remains HTTP.
* It also need to be pointed out that the extended delay (48 hours) between the time the
vulnerability was reported and the moment it is fixed in our codebase has to do with
the fact that the reporter chose to deviate from standard security practices by not
disclosing the details of the vulnerability with us, be it publicly or privately,
before creating the cert.org report. The only advance notification we received was a
generic note about the use of HTTP vs HTTPS, which, as have established, is not
immediately relevant to addressing the reported vulnerability.
* Closes #1009
* Note: The other vulnerability scenario described towards the end of #1009, which
doesn't have to do with the "lack of CA checking", will be addressed separately. | Medium | 167,815 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: cib_remote_listen(gpointer data)
{
int lpc = 0;
int csock = 0;
unsigned laddr;
time_t now = 0;
time_t start = time(NULL);
struct sockaddr_in addr;
int ssock = *(int *)data;
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_session *session = NULL;
#endif
cib_client_t *new_client = NULL;
xmlNode *login = NULL;
const char *user = NULL;
const char *pass = NULL;
const char *tmp = NULL;
#ifdef HAVE_DECL_NANOSLEEP
const struct timespec sleepfast = { 0, 10000000 }; /* 10 millisec */
#endif
static struct mainloop_fd_callbacks remote_client_fd_callbacks =
{
.dispatch = cib_remote_msg,
.destroy = cib_remote_connection_destroy,
};
/* accept the connection */
laddr = sizeof(addr);
csock = accept(ssock, (struct sockaddr *)&addr, &laddr);
crm_debug("New %s connection from %s",
ssock == remote_tls_fd ? "secure" : "clear-text", inet_ntoa(addr.sin_addr));
if (csock == -1) {
crm_err("accept socket failed");
return TRUE;
}
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
/* create gnutls session for the server socket */
session = create_tls_session(csock, GNUTLS_SERVER);
if (session == NULL) {
crm_err("TLS session creation failed");
close(csock);
return TRUE;
}
#endif
}
do {
crm_trace("Iter: %d", lpc++);
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
login = crm_recv_remote_msg(session, TRUE);
#endif
} else {
login = crm_recv_remote_msg(GINT_TO_POINTER(csock), FALSE);
}
if (login != NULL) {
break;
}
#ifdef HAVE_DECL_NANOSLEEP
nanosleep(&sleepfast, NULL);
#else
sleep(1);
#endif
now = time(NULL);
/* Peers have 3s to connect */
} while (login == NULL && (start - now) < 4);
crm_log_xml_info(login, "Login: ");
if (login == NULL) {
goto bail;
}
tmp = crm_element_name(login);
if (safe_str_neq(tmp, "cib_command")) {
crm_err("Wrong tag: %s", tmp);
goto bail;
}
tmp = crm_element_value(login, "op");
if (safe_str_neq(tmp, "authenticate")) {
crm_err("Wrong operation: %s", tmp);
goto bail;
}
user = crm_element_value(login, "user");
pass = crm_element_value(login, "password");
/* Non-root daemons can only validate the password of the
* user they're running as
*/
if (check_group_membership(user, CRM_DAEMON_GROUP) == FALSE) {
crm_err("User is not a member of the required group");
goto bail;
} else if (authenticate_user(user, pass) == FALSE) {
crm_err("PAM auth failed");
goto bail;
}
/* send ACK */
num_clients++;
new_client = calloc(1, sizeof(cib_client_t));
new_client->name = crm_element_value_copy(login, "name");
CRM_CHECK(new_client->id == NULL, free(new_client->id));
new_client->id = crm_generate_uuid();
#if ENABLE_ACL
new_client->user = strdup(user);
#endif
new_client->callback_id = NULL;
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
new_client->encrypted = TRUE;
new_client->session = session;
#endif
} else {
new_client->session = GINT_TO_POINTER(csock);
}
free_xml(login);
login = create_xml_node(NULL, "cib_result");
crm_xml_add(login, F_CIB_OPERATION, CRM_OP_REGISTER);
crm_xml_add(login, F_CIB_CLIENTID, new_client->id);
crm_send_remote_msg(new_client->session, login, new_client->encrypted);
free_xml(login);
new_client->remote = mainloop_add_fd(
"cib-remote-client", G_PRIORITY_DEFAULT, csock, new_client, &remote_client_fd_callbacks);
g_hash_table_insert(client_list, new_client->id, new_client);
return TRUE;
bail:
if (ssock == remote_tls_fd) {
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_bye(*session, GNUTLS_SHUT_RDWR);
gnutls_deinit(*session);
gnutls_free(session);
#endif
}
close(csock);
free_xml(login);
return TRUE;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Pacemaker 1.1.10, when remote Cluster Information Base (CIB) configuration or resource management is enabled, does not limit the duration of connections to the blocking sockets, which allows remote attackers to cause a denial of service (connection blocking).
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. | Medium | 166,148 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata(
const H264SPS* sps,
const H264PPS* pps,
const H264DPB& dpb,
const H264Picture::Vector& ref_pic_listp0,
const H264Picture::Vector& ref_pic_listb0,
const H264Picture::Vector& ref_pic_listb1,
const scoped_refptr<H264Picture>& pic) {
VAPictureParameterBufferH264 pic_param;
memset(&pic_param, 0, sizeof(pic_param));
#define FROM_SPS_TO_PP(a) pic_param.a = sps->a
#define FROM_SPS_TO_PP2(a, b) pic_param.b = sps->a
FROM_SPS_TO_PP2(pic_width_in_mbs_minus1, picture_width_in_mbs_minus1);
FROM_SPS_TO_PP2(pic_height_in_map_units_minus1, picture_height_in_mbs_minus1);
FROM_SPS_TO_PP(bit_depth_luma_minus8);
FROM_SPS_TO_PP(bit_depth_chroma_minus8);
#undef FROM_SPS_TO_PP
#undef FROM_SPS_TO_PP2
#define FROM_SPS_TO_PP_SF(a) pic_param.seq_fields.bits.a = sps->a
#define FROM_SPS_TO_PP_SF2(a, b) pic_param.seq_fields.bits.b = sps->a
FROM_SPS_TO_PP_SF(chroma_format_idc);
FROM_SPS_TO_PP_SF2(separate_colour_plane_flag,
residual_colour_transform_flag);
FROM_SPS_TO_PP_SF(gaps_in_frame_num_value_allowed_flag);
FROM_SPS_TO_PP_SF(frame_mbs_only_flag);
FROM_SPS_TO_PP_SF(mb_adaptive_frame_field_flag);
FROM_SPS_TO_PP_SF(direct_8x8_inference_flag);
pic_param.seq_fields.bits.MinLumaBiPredSize8x8 = (sps->level_idc >= 31);
FROM_SPS_TO_PP_SF(log2_max_frame_num_minus4);
FROM_SPS_TO_PP_SF(pic_order_cnt_type);
FROM_SPS_TO_PP_SF(log2_max_pic_order_cnt_lsb_minus4);
FROM_SPS_TO_PP_SF(delta_pic_order_always_zero_flag);
#undef FROM_SPS_TO_PP_SF
#undef FROM_SPS_TO_PP_SF2
#define FROM_PPS_TO_PP(a) pic_param.a = pps->a
FROM_PPS_TO_PP(pic_init_qp_minus26);
FROM_PPS_TO_PP(pic_init_qs_minus26);
FROM_PPS_TO_PP(chroma_qp_index_offset);
FROM_PPS_TO_PP(second_chroma_qp_index_offset);
#undef FROM_PPS_TO_PP
#define FROM_PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps->a
#define FROM_PPS_TO_PP_PF2(a, b) pic_param.pic_fields.bits.b = pps->a
FROM_PPS_TO_PP_PF(entropy_coding_mode_flag);
FROM_PPS_TO_PP_PF(weighted_pred_flag);
FROM_PPS_TO_PP_PF(weighted_bipred_idc);
FROM_PPS_TO_PP_PF(transform_8x8_mode_flag);
pic_param.pic_fields.bits.field_pic_flag = 0;
FROM_PPS_TO_PP_PF(constrained_intra_pred_flag);
FROM_PPS_TO_PP_PF2(bottom_field_pic_order_in_frame_present_flag,
pic_order_present_flag);
FROM_PPS_TO_PP_PF(deblocking_filter_control_present_flag);
FROM_PPS_TO_PP_PF(redundant_pic_cnt_present_flag);
pic_param.pic_fields.bits.reference_pic_flag = pic->ref;
#undef FROM_PPS_TO_PP_PF
#undef FROM_PPS_TO_PP_PF2
pic_param.frame_num = pic->frame_num;
InitVAPicture(&pic_param.CurrPic);
FillVAPicture(&pic_param.CurrPic, pic);
for (int i = 0; i < 16; ++i)
InitVAPicture(&pic_param.ReferenceFrames[i]);
FillVARefFramesFromDPB(dpb, pic_param.ReferenceFrames,
arraysize(pic_param.ReferenceFrames));
pic_param.num_ref_frames = sps->max_num_ref_frames;
if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType,
sizeof(pic_param), &pic_param))
return false;
VAIQMatrixBufferH264 iq_matrix_buf;
memset(&iq_matrix_buf, 0, sizeof(iq_matrix_buf));
if (pps->pic_scaling_matrix_present_flag) {
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 16; ++j)
iq_matrix_buf.ScalingList4x4[i][kZigzagScan4x4[j]] =
pps->scaling_list4x4[i][j];
}
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 64; ++j)
iq_matrix_buf.ScalingList8x8[i][kZigzagScan8x8[j]] =
pps->scaling_list8x8[i][j];
}
} else {
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 16; ++j)
iq_matrix_buf.ScalingList4x4[i][kZigzagScan4x4[j]] =
sps->scaling_list4x4[i][j];
}
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 64; ++j)
iq_matrix_buf.ScalingList8x8[i][kZigzagScan8x8[j]] =
sps->scaling_list8x8[i][j];
}
}
return vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType,
sizeof(iq_matrix_buf), &iq_matrix_buf);
}
Vulnerability Type:
CWE ID: CWE-362
Summary: A race in the handling of SharedArrayBuffers in WebAssembly in Google Chrome prior to 65.0.3325.146 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup()
This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and
posts the destruction of those objects to the appropriate thread on
Cleanup().
Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@
comment in
https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f
TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build
unstripped, let video play for a few seconds then navigate back; no
crashes. Unittests as before:
video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12
video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11
video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1
Bug: 789160
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2
Reviewed-on: https://chromium-review.googlesource.com/794091
Reviewed-by: Pawel Osciak <[email protected]>
Commit-Queue: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523372} | Medium | 172,811 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void AddServiceRequestHandlerOnIoThread(
const std::string& name,
const ServiceRequestHandler& handler) {
DCHECK(io_thread_checker_.CalledOnValidThread());
auto result = request_handlers_.insert(std::make_pair(name, handler));
DCHECK(result.second);
}
Vulnerability Type: DoS Overflow Mem. Corr.
CWE ID: CWE-119
Summary: SkPictureShader.cpp in Skia, as used in Google Chrome before 44.0.2403.89, allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact by leveraging access to a renderer process and providing crafted serialized data.
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947} | High | 171,940 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void unix_notinflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
spin_lock(&unix_gc_lock);
if (s) {
struct unix_sock *u = unix_sk(s);
BUG_ON(list_empty(&u->link));
if (atomic_long_dec_and_test(&u->inflight))
list_del_init(&u->link);
unix_tot_inflight--;
}
fp->f_cred->user->unix_inflight--;
spin_unlock(&unix_gc_lock);
}
Vulnerability Type: DoS Bypass
CWE ID: CWE-399
Summary: The Linux kernel before 4.5 allows local users to bypass file-descriptor limits and cause a denial of service (memory consumption) by leveraging incorrect tracking of descriptor ownership and sending each descriptor over a UNIX socket before closing it. NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-4312.
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Medium | 167,397 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: _prolog_error(batch_job_launch_msg_t *req, int rc)
{
char *err_name_ptr, err_name[256], path_name[MAXPATHLEN];
char *fmt_char;
int fd;
if (req->std_err || req->std_out) {
if (req->std_err)
strncpy(err_name, req->std_err, sizeof(err_name));
else
strncpy(err_name, req->std_out, sizeof(err_name));
if ((fmt_char = strchr(err_name, (int) '%')) &&
(fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) {
char tmp_name[256];
fmt_char[1] = 'u';
snprintf(tmp_name, sizeof(tmp_name), err_name,
req->job_id);
strncpy(err_name, tmp_name, sizeof(err_name));
}
} else {
snprintf(err_name, sizeof(err_name), "slurm-%u.out",
req->job_id);
}
err_name_ptr = err_name;
if (err_name_ptr[0] == '/')
snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr);
else if (req->work_dir)
snprintf(path_name, MAXPATHLEN, "%s/%s",
req->work_dir, err_name_ptr);
else
snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr);
if ((fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644)) == -1) {
error("Unable to open %s: %s", path_name,
slurm_strerror(errno));
return;
}
snprintf(err_name, sizeof(err_name),
"Error running slurm prolog: %d\n", WEXITSTATUS(rc));
safe_write(fd, err_name, strlen(err_name));
if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) {
snprintf(err_name, sizeof(err_name),
"Couldn't change fd owner to %u:%u: %m\n",
req->uid, req->gid);
}
rwfail:
close(fd);
}
Vulnerability Type:
CWE ID: CWE-284
Summary: The _prolog_error function in slurmd/req.c in Slurm before 15.08.13, 16.x before 16.05.7, and 17.x before 17.02.0-pre4 has a vulnerability in how the slurmd daemon informs users of a Prolog failure on a compute node. That vulnerability could allow a user to assume control of an arbitrary file on the system. Any exploitation of this is dependent on the user being able to cause or anticipate the failure (non-zero return code) of a Prolog script that their job would run on. This issue affects all Slurm versions from 0.6.0 (September 2005) to present. Workarounds to prevent exploitation of this are to either disable your Prolog script, or modify it such that it always returns 0 (*success*) and adjust it to set the node as down using scontrol instead of relying on the slurmd to handle that automatically. If you do not have a Prolog set you are unaffected by this issue.
Commit Message: Fix security issue in _prolog_error().
Fix security issue caused by insecure file path handling triggered by
the failure of a Prolog script. To exploit this a user needs to
anticipate or cause the Prolog to fail for their job.
(This commit is slightly different from the fix to the 15.08 branch.)
CVE-2016-10030. | High | 168,646 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_aead raead;
struct aead_alg *aead = &alg->cra_aead;
snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead");
snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv);
raead.blocksize = alg->cra_blocksize;
raead.maxauthsize = aead->maxauthsize;
raead.ivsize = aead->ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD,
sizeof(struct crypto_report_aead), &raead))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Vulnerability Type: +Info
CWE ID: CWE-310
Summary: The crypto_report_one function in crypto/crypto_user.c in the report API in the crypto user configuration API in the Linux kernel through 3.8.2 uses an incorrect length value during a copy operation, which allows local users to obtain sensitive information from kernel memory by leveraging the CAP_NET_ADMIN capability.
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]> | Low | 166,064 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The secure-session feature in the mm-video-v4l2 venc component in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-08-01 mishandles heap pointers, which allows attackers to obtain sensitive information via a crafted application, aka internal bug 28920116.
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
| Medium | 173,507 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: JSValue JSWebKitMutationObserver::observe(ExecState* exec)
{
if (exec->argumentCount() < 2)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
Node* target = toNode(exec->argument(0));
if (exec->hadException())
return jsUndefined();
JSObject* optionsObject = exec->argument(1).getObject();
if (!optionsObject) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
JSDictionary dictionary(exec, optionsObject);
MutationObserverOptions options = 0;
for (unsigned i = 0; i < numBooleanOptions; ++i) {
bool option = false;
if (!dictionary.tryGetProperty(booleanOptions[i].name, option))
return jsUndefined();
if (option)
options |= booleanOptions[i].value;
}
HashSet<AtomicString> attributeFilter;
if (!dictionary.tryGetProperty("attributeFilter", attributeFilter))
return jsUndefined();
if (!attributeFilter.isEmpty())
options |= WebKitMutationObserver::AttributeFilter;
ExceptionCode ec = 0;
impl()->observe(target, options, attributeFilter, ec);
if (ec)
setDOMException(exec, ec);
return jsUndefined();
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The HTML parser in Google Chrome before 12.0.742.112 does not properly address *lifetime and re-entrancy issues,* which allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | High | 170,564 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), GetExtension()->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
GetExtension()->id(),
GetExtension()->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The Debugger extension API in browser/extensions/api/debugger/debugger_api.cc in Google Chrome before 37.0.2062.94 does not validate a tab's URL before an attach operation, which allows remote attackers to bypass intended access limitations via an extension that uses a restricted URL, as demonstrated by a chrome:// URL.
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 171,654 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: DrawingBuffer::DrawingBuffer(
std::unique_ptr<WebGraphicsContext3DProvider> context_provider,
std::unique_ptr<Extensions3DUtil> extensions_util,
Client* client,
bool discard_framebuffer_supported,
bool want_alpha_channel,
bool premultiplied_alpha,
PreserveDrawingBuffer preserve,
WebGLVersion web_gl_version,
bool want_depth,
bool want_stencil,
ChromiumImageUsage chromium_image_usage,
const CanvasColorParams& color_params)
: client_(client),
preserve_drawing_buffer_(preserve),
web_gl_version_(web_gl_version),
context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper(
std::move(context_provider)))),
gl_(this->ContextProvider()->ContextGL()),
extensions_util_(std::move(extensions_util)),
discard_framebuffer_supported_(discard_framebuffer_supported),
want_alpha_channel_(want_alpha_channel),
premultiplied_alpha_(premultiplied_alpha),
software_rendering_(this->ContextProvider()->IsSoftwareRendering()),
want_depth_(want_depth),
want_stencil_(want_stencil),
color_space_(color_params.GetGfxColorSpace()),
chromium_image_usage_(chromium_image_usage) {
TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation",
TRACE_EVENT_SCOPE_GLOBAL);
}
Vulnerability Type: Exec Code Overflow
CWE ID: CWE-119
Summary: Heap buffer overflow in WebGL in Google Chrome prior to 61.0.3163.79 for Windows allowed a remote attacker to execute arbitrary code inside a sandbox via a crafted HTML page.
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518} | Medium | 172,291 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
int what, xmlChar end, xmlChar end2, xmlChar end3) {
xmlChar *buffer = NULL;
int buffer_size = 0;
xmlChar *current = NULL;
xmlChar *rep = NULL;
const xmlChar *last;
xmlEntityPtr ent;
int c,l;
int nbchars = 0;
if ((ctxt == NULL) || (str == NULL) || (len < 0))
return(NULL);
last = str + len;
if (((ctxt->depth > 40) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(ctxt->depth > 1024)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return(NULL);
}
/*
* allocate a translation buffer.
*/
buffer_size = XML_PARSER_BIG_BUFFER_SIZE;
buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar));
if (buffer == NULL) goto mem_error;
/*
* OK loop until we reach one of the ending char or a size limit.
* we are operating on already parsed values.
*/
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
while ((c != 0) && (c != end) && /* non input consuming loop */
(c != end2) && (c != end3)) {
if (c == 0) break;
if ((c == '&') && (str[1] == '#')) {
int val = xmlParseStringCharRef(ctxt, &str);
if (val != 0) {
COPY_BUF(0,buffer,nbchars,val);
}
if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding Entity Reference: %.30s\n",
str);
ent = xmlParseStringEntityRef(ctxt, &str);
if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
(ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
goto int_error;
if (ent != NULL)
ctxt->nbentities += ent->checked;
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (ent->content != NULL) {
COPY_BUF(0,buffer,nbchars,ent->content[0]);
if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"predefined entity has no content\n");
}
} else if ((ent != NULL) && (ent->content != NULL)) {
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars >
buffer_size - XML_PARSER_BUFFER_SIZE) {
if (xmlParserEntityCheck(ctxt, nbchars, ent))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
} else if (ent != NULL) {
int i = xmlStrlen(ent->name);
const xmlChar *cur = ent->name;
buffer[nbchars++] = '&';
if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
for (;i > 0;i--)
buffer[nbchars++] = *cur++;
buffer[nbchars++] = ';';
}
} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding PE Reference: %.30s\n", str);
ent = xmlParseStringPEReference(ctxt, &str);
if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
goto int_error;
if (ent != NULL)
ctxt->nbentities += ent->checked;
if (ent != NULL) {
if (ent->content == NULL) {
xmlLoadEntityContent(ctxt, ent);
}
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars >
buffer_size - XML_PARSER_BUFFER_SIZE) {
if (xmlParserEntityCheck(ctxt, nbchars, ent))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
}
} else {
COPY_BUF(l,buffer,nbchars,c);
str += l;
if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
}
buffer[nbchars] = 0;
return(buffer);
mem_error:
xmlErrMemory(ctxt, NULL);
int_error:
if (rep != NULL)
xmlFree(rep);
if (buffer != NULL)
xmlFree(buffer);
return(NULL);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Heap-based buffer overflow in libxml2, as used in Google Chrome before 16.0.912.75, allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
Commit Message: Pull entity fix from upstream.
BUG=107128
Review URL: http://codereview.chromium.org/9072008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116175 0039d316-1c4b-4281-b951-d872f2087c98 | High | 170,977 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line,
const void **parsed_require_line)
{
const char *provider_name;
lua_authz_provider_spec *spec;
apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE,
cmd->temp_pool);
ap_assert(provider_name != NULL);
spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING);
ap_assert(spec != NULL);
if (require_line && *require_line) {
const char *arg;
spec->args = apr_array_make(cmd->pool, 2, sizeof(const char *));
while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) {
APR_ARRAY_PUSH(spec->args, const char *) = arg;
}
}
*parsed_require_line = spec;
return NULL;
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.
Commit Message: Merge r1642499 from trunk:
*) SECURITY: CVE-2014-8109 (cve.mitre.org)
mod_lua: Fix handling of the Require line when a LuaAuthzProvider is
used in multiple Require directives with different arguments.
PR57204 [Edward Lu <Chaosed0 gmail.com>]
Submitted By: Edward Lu
Committed By: covener
Submitted by: covener
Reviewed/backported by: jim
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68 | Medium | 166,251 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
PNG_CONST image_transform *transform_list)
{
memset(dp, 0, sizeof *dp);
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->transform_list = transform_list;
/* Local variable fields */
dp->output_colour_type = 255; /* invalid */
dp->output_bit_depth = 255; /* invalid */
}
Vulnerability Type: +Priv
CWE ID:
Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085.
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
| High | 173,712 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
}
Vulnerability Type: DoS
CWE ID: CWE-476
Summary: The acc_ctx_cont function in the SPNEGO acceptor in lib/gssapi/spnego/spnego_mech.c in MIT Kerberos 5 (aka krb5) 1.5.x through 1.12.x before 1.12.2 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via an empty continuation token at a certain point during a SPNEGO negotiation.
Commit Message: Fix null deref in SPNEGO acceptor [CVE-2014-4344]
When processing a continuation token, acc_ctx_cont was dereferencing
the initial byte of the token without checking the length. This could
result in a null dereference.
CVE-2014-4344:
In MIT krb5 1.5 and newer, an unauthenticated or partially
authenticated remote attacker can cause a NULL dereference and
application crash during a SPNEGO negotiation by sending an empty
token as the second or later context token from initiator to acceptor.
The attacker must provide at least one valid context token in the
security context negotiation before sending the empty token. This can
be done by an unauthenticated attacker by forcing SPNEGO to
renegotiate the underlying mechanism, or by using IAKERB to wrap an
unauthenticated AS-REQ as the first token.
CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: CVE summary, CVSSv2 vector]
(cherry picked from commit 524688ce87a15fc75f87efc8c039ba4c7d5c197b)
ticket: 7970
version_fixed: 1.12.2
status: resolved | High | 166,310 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int GetAvailableDraftPageCount() {
int page_data_map_size = page_data_map_.size();
if (page_data_map_.find(printing::COMPLETE_PREVIEW_DOCUMENT_INDEX) !=
page_data_map_.end()) {
page_data_map_size--;
}
return page_data_map_size;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The IPC implementation in Google Chrome before 22.0.1229.79 allows attackers to obtain potentially sensitive information about memory addresses via unspecified vectors.
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 170,819 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static Image *ReadCALSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
header[MagickPathExtent],
message[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register ssize_t
i;
unsigned long
density,
direction,
height,
orientation,
pel_path,
type,
width;
/*
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 CALS header.
*/
(void) memset(header,0,sizeof(header));
density=0;
direction=0;
orientation=1;
pel_path=0;
type=1;
width=0;
height=0;
for (i=0; i < 16; i++)
{
if (ReadBlob(image,128,(unsigned char *) header) != 128)
break;
switch (*header)
{
case 'R':
case 'r':
{
if (LocaleNCompare(header,"rdensty:",8) == 0)
{
(void) sscanf(header+8,"%lu",&density);
break;
}
if (LocaleNCompare(header,"rpelcnt:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&width,&height);
break;
}
if (LocaleNCompare(header,"rorient:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&pel_path,&direction);
if (pel_path == 90)
orientation=5;
else
if (pel_path == 180)
orientation=3;
else
if (pel_path == 270)
orientation=7;
if (direction == 90)
orientation++;
break;
}
if (LocaleNCompare(header,"rtype:",6) == 0)
{
(void) sscanf(header+6,"%lu",&type);
break;
}
break;
}
}
}
/*
Read CALS pixels.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
while ((c=ReadBlobByte(image)) != EOF)
(void) fputc(c,file);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"group4:%s",
filename);
(void) FormatLocaleString(message,MagickPathExtent,"%lux%lu",width,height);
(void) CloneString(&read_info->size,message);
(void) FormatLocaleString(message,MagickPathExtent,"%lu",density);
(void) CloneString(&read_info->density,message);
read_info->orientation=(OrientationType) orientation;
image=ReadImage(read_info,exception);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"CALS",MagickPathExtent);
}
read_info=DestroyImageInfo(read_info);
(void) RelinquishUniqueFileResource(filename);
return(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,038 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void perform_gamma_scale16_tests(png_modifier *pm)
{
# ifndef PNG_MAX_GAMMA_8
# define PNG_MAX_GAMMA_8 11
# endif
# define SBIT_16_TO_8 PNG_MAX_GAMMA_8
/* Include the alpha cases here. Note that sbit matches the internal value
* used by the library - otherwise we will get spurious errors from the
* internal sbit style approximation.
*
* The threshold test is here because otherwise the 16 to 8 conversion will
* proceed *without* gamma correction, and the tests above will fail (but not
* by much) - this could be fixed, it only appears with the -g option.
*/
unsigned int i, j;
for (i=0; i<pm->ngamma_tests; ++i)
{
for (j=0; j<pm->ngamma_tests; ++j)
{
if (i != j &&
fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
{
gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
pm->use_input_precision_16to8, 1 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
Vulnerability Type: +Priv
CWE ID:
Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085.
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
| High | 173,681 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,
struct iw_exif_state *e, iw_uint32 ifd)
{
unsigned int tag_count;
unsigned int i;
unsigned int tag_pos;
unsigned int tag_id;
unsigned int v;
double v_dbl;
if(ifd<8 || ifd>e->d_len-18) return;
tag_count = iw_get_ui16_e(&e->d[ifd],e->endian);
if(tag_count>1000) return; // Sanity check.
for(i=0;i<tag_count;i++) {
tag_pos = ifd+2+i*12;
if(tag_pos+12 > e->d_len) return; // Avoid overruns.
tag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian);
switch(tag_id) {
case 274: // 274 = Orientation
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_orientation = v;
}
break;
case 296: // 296 = ResolutionUnit
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_density_unit = v;
}
break;
case 282: // 282 = XResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_x = v_dbl;
}
break;
case 283: // 283 = YResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_y = v_dbl;
}
break;
}
}
}
Vulnerability Type: DoS
CWE ID: CWE-125
Summary: The iw_get_ui16be function in imagew-util.c:422:24 in libimageworsener.a in ImageWorsener 1.3.1 allows remote attackers to cause a denial of service (heap-based buffer over-read) via a crafted image, related to imagew-jpeg.c.
Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data
Fixes issues #22, #23, #24, #25 | Medium | 168,116 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: PHP_FUNCTION(mcrypt_module_get_supported_key_sizes)
{
int i, count = 0;
int *key_sizes;
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
array_init(return_value);
key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count);
for (i = 0; i < count; i++) {
add_index_long(return_value, i, key_sizes[i]);
}
mcrypt_free(key_sizes);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Multiple integer overflows in mcrypt.c in the mcrypt extension in PHP before 5.5.37, 5.6.x before 5.6.23, and 7.x before 7.0.8 allow remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted length value, related to the (1) mcrypt_generic and (2) mdecrypt_generic functions.
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows | High | 167,101 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: testing::AssertionResult ScriptAllowedExclusivelyOnTab(
const Extension* extension,
const std::set<GURL>& allowed_urls,
int tab_id) {
std::vector<std::string> errors;
for (const GURL& url : urls_) {
bool allowed = IsAllowedScript(extension, url, tab_id);
if (allowed && !allowed_urls.count(url))
errors.push_back("Script unexpectedly disallowed on " + url.spec());
else if (!allowed && allowed_urls.count(url))
errors.push_back("Script unexpectedly allowed on " + url.spec());
}
if (!errors.empty())
return testing::AssertionFailure() << base::JoinString(errors, "\n");
return testing::AssertionSuccess();
}
Vulnerability Type: Bypass
CWE ID: CWE-20
Summary: Insufficient policy enforcement in Extensions API in Google Chrome prior to 67.0.3396.62 allowed an attacker who convinced a user to install a malicious extension to bypass navigation restrictions via a crafted Chrome Extension.
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891} | Medium | 173,233 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void ThreadHeap::WriteBarrier(void* value) {
DCHECK(thread_state_->IsIncrementalMarking());
DCHECK(value);
DCHECK_NE(value, reinterpret_cast<void*>(-1));
BasePage* const page = PageFromObject(value);
HeapObjectHeader* const header =
page->IsLargeObjectPage()
? static_cast<LargeObjectPage*>(page)->GetHeapObjectHeader()
: static_cast<NormalPage*>(page)->FindHeaderFromAddress(
reinterpret_cast<Address>(const_cast<void*>(value)));
if (header->IsMarked())
return;
header->Mark();
marking_worklist_->Push(
WorklistTaskId::MainThread,
{header->Payload(), ThreadHeap::GcInfo(header->GcInfoIndex())->trace_});
}
Vulnerability Type:
CWE ID: CWE-362
Summary: A race condition in Oilpan 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: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434} | Medium | 173,138 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void impeg2d_peek_next_start_code(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush_to_byte_boundary(ps_stream);
while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX)
&& (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset))
{
impeg2d_bit_stream_get(ps_stream,8);
}
return;
}
Vulnerability Type: Bypass +Info
CWE ID: CWE-254
Summary: libmpeg2 in libstagefright in Android 6.x before 2016-03-01 allows attackers to obtain sensitive information, and consequently bypass an unspecified protection mechanism, via crafted Bitstream data, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 25765591.
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
| Medium | 173,951 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int jas_stream_read(jas_stream_t *stream, void *buf, int cnt)
{
int n;
int c;
char *bufptr;
bufptr = buf;
n = 0;
while (n < cnt) {
if ((c = jas_stream_getc(stream)) == EOF) {
return n;
}
*bufptr++ = c;
++n;
}
return n;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Multiple integer overflows in the (1) jas_realloc function in base/jas_malloc.c and (2) mem_resize function in base/jas_stream.c in JasPer before 1.900.22 allow remote attackers to cause a denial of service via a crafted image, which triggers use after free vulnerabilities.
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior. | Medium | 168,747 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
const ptrdiff_t count = compression_entries_end_ - compression_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return compression_entries_[idx];
}
Vulnerability Type: DoS Exec Code Mem. Corr.
CWE ID: CWE-20
Summary: libvpx in libwebm in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted mkv file, aka internal bug 23167726.
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
| High | 173,815 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: char *auth_server(int f_in, int f_out, int module, const char *host,
const char *addr, const char *leader)
{
char *users = lp_auth_users(module);
char challenge[MAX_DIGEST_LEN*2];
char line[BIGPATHBUFLEN];
char **auth_uid_groups = NULL;
int auth_uid_groups_cnt = -1;
const char *err = NULL;
int group_match = -1;
char *tok, *pass;
char opt_ch = '\0';
/* if no auth list then allow anyone in! */
if (!users || !*users)
if (!users || !*users)
return "";
gen_challenge(addr, challenge);
io_printf(f_out, "%s%s\n", leader, challenge);
return NULL;
}
Vulnerability Type: Bypass
CWE ID: CWE-354
Summary: rsync 3.1.3-development before 2017-10-24 mishandles archaic checksums, which makes it easier for remote attackers to bypass intended access restrictions. NOTE: the rsync development branch has significant use beyond the rsync developers, e.g., the code has been copied for use in various GitHub projects.
Commit Message: | High | 164,641 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool ResourcePrefetchPredictor::GetRedirectEndpointsForPreconnect(
const url::Origin& entry_origin,
const RedirectDataMap& redirect_data,
PreconnectPrediction* prediction) const {
if (!base::FeatureList::IsEnabled(
features::kLoadingPreconnectToRedirectTarget)) {
return false;
}
DCHECK(!prediction || prediction->requests.empty());
RedirectData data;
if (!redirect_data.TryGetData(entry_origin.host(), &data))
return false;
const float kMinRedirectConfidenceToTriggerPrefetch = 0.1f;
bool at_least_one_redirect_endpoint_added = false;
for (const auto& redirect : data.redirect_endpoints()) {
if (ComputeRedirectConfidence(redirect) <
kMinRedirectConfidenceToTriggerPrefetch) {
continue;
}
std::string redirect_scheme =
redirect.url_scheme().empty() ? "https" : redirect.url_scheme();
int redirect_port = redirect.has_url_port() ? redirect.url_port() : 443;
const url::Origin redirect_origin = url::Origin::CreateFromNormalizedTuple(
redirect_scheme, redirect.url(), redirect_port);
if (redirect_origin == entry_origin) {
continue;
}
if (prediction) {
prediction->requests.emplace_back(
redirect_origin.GetURL(), 1 /* num_scokets */,
net::NetworkIsolationKey(redirect_origin, redirect_origin));
}
at_least_one_redirect_endpoint_added = true;
}
if (prediction && prediction->host.empty() &&
at_least_one_redirect_endpoint_added) {
prediction->host = entry_origin.host();
}
return at_least_one_redirect_endpoint_added;
}
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 <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311} | Medium | 172,378 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k)
{
void *result;
size_t lg;
size_t lb_rounded;
word n_blocks;
GC_bool init;
DCL_LOCK_STATE;
if (SMALL_OBJ(lb))
return(GC_generic_malloc((word)lb, k));
lg = ROUNDED_UP_GRANULES(lb);
lb_rounded = GRANULES_TO_BYTES(lg);
n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded);
init = GC_obj_kinds[k].ok_init;
if (EXPECT(GC_have_errors, FALSE))
GC_print_all_errors();
GC_INVOKE_FINALIZERS();
LOCK();
result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE);
if (0 != result) {
if (GC_debugging_started) {
BZERO(result, n_blocks * HBLKSIZE);
} else {
# ifdef THREADS
/* Clear any memory that might be used for GC descriptors */
/* before we release the lock. */
((word *)result)[0] = 0;
((word *)result)[1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0;
# endif
}
}
GC_bytes_allocd += lb_rounded;
if (0 == result) {
GC_oom_func oom_fn = GC_oom_fn;
UNLOCK();
return((*oom_fn)(lb));
} else {
UNLOCK();
if (init && !GC_debugging_started) {
BZERO(result, n_blocks * HBLKSIZE);
}
return(result);
}
}
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 allocation size overflows due to rounding.
* malloc.c (GC_generic_malloc): Check if the allocation size is
rounded to a smaller value.
* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. | Medium | 169,879 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: std::vector<uint8_t> NtlmClient::GenerateAuthenticateMessage(
const base::string16& domain,
const base::string16& username,
const base::string16& password,
const std::string& hostname,
const std::string& channel_bindings,
const std::string& spn,
uint64_t client_time,
base::span<const uint8_t, kChallengeLen> client_challenge,
base::span<const uint8_t> server_challenge_message) const {
if (hostname.length() > kMaxFqdnLen || domain.length() > kMaxFqdnLen ||
username.length() > kMaxUsernameLen ||
password.length() > kMaxPasswordLen) {
return {};
}
NegotiateFlags challenge_flags;
uint8_t server_challenge[kChallengeLen];
uint8_t lm_response[kResponseLenV1];
uint8_t ntlm_response[kResponseLenV1];
std::vector<uint8_t> updated_target_info;
std::vector<uint8_t> v2_proof_input;
uint8_t v2_proof[kNtlmProofLenV2];
uint8_t v2_session_key[kSessionKeyLenV2];
if (IsNtlmV2()) {
std::vector<AvPair> av_pairs;
if (!ParseChallengeMessageV2(server_challenge_message, &challenge_flags,
server_challenge, &av_pairs)) {
return {};
}
uint64_t timestamp;
updated_target_info =
GenerateUpdatedTargetInfo(IsMicEnabled(), IsEpaEnabled(),
channel_bindings, spn, av_pairs, ×tamp);
memset(lm_response, 0, kResponseLenV1);
if (timestamp == UINT64_MAX) {
timestamp = client_time;
}
uint8_t v2_hash[kNtlmHashLen];
GenerateNtlmHashV2(domain, username, password, v2_hash);
v2_proof_input = GenerateProofInputV2(timestamp, client_challenge);
GenerateNtlmProofV2(v2_hash, server_challenge, v2_proof_input,
updated_target_info, v2_proof);
GenerateSessionBaseKeyV2(v2_hash, v2_proof, v2_session_key);
} else {
if (!ParseChallengeMessage(server_challenge_message, &challenge_flags,
server_challenge)) {
return {};
}
GenerateResponsesV1WithSessionSecurity(password, server_challenge,
client_challenge, lm_response,
ntlm_response);
}
NegotiateFlags authenticate_flags = (challenge_flags & negotiate_flags_) |
NegotiateFlags::kExtendedSessionSecurity;
bool is_unicode = (authenticate_flags & NegotiateFlags::kUnicode) ==
NegotiateFlags::kUnicode;
SecurityBuffer lm_info;
SecurityBuffer ntlm_info;
SecurityBuffer domain_info;
SecurityBuffer username_info;
SecurityBuffer hostname_info;
SecurityBuffer session_key_info;
size_t authenticate_message_len;
CalculatePayloadLayout(is_unicode, domain, username, hostname,
updated_target_info.size(), &lm_info, &ntlm_info,
&domain_info, &username_info, &hostname_info,
&session_key_info, &authenticate_message_len);
NtlmBufferWriter authenticate_writer(authenticate_message_len);
bool writer_result = WriteAuthenticateMessage(
&authenticate_writer, lm_info, ntlm_info, domain_info, username_info,
hostname_info, session_key_info, authenticate_flags);
DCHECK(writer_result);
if (IsNtlmV2()) {
writer_result = authenticate_writer.WriteZeros(kVersionFieldLen) &&
authenticate_writer.WriteZeros(kMicLenV2);
DCHECK(writer_result);
}
DCHECK(authenticate_writer.GetCursor() == GetAuthenticateHeaderLength());
DCHECK(GetAuthenticateHeaderLength() == lm_info.offset);
if (IsNtlmV2()) {
writer_result =
WriteResponsePayloadsV2(&authenticate_writer, lm_response, v2_proof,
v2_proof_input, updated_target_info);
} else {
DCHECK_EQ(kResponseLenV1, lm_info.length);
DCHECK_EQ(kResponseLenV1, ntlm_info.length);
writer_result =
WriteResponsePayloads(&authenticate_writer, lm_response, ntlm_response);
}
DCHECK(writer_result);
DCHECK_EQ(authenticate_writer.GetCursor(), domain_info.offset);
writer_result = WriteStringPayloads(&authenticate_writer, is_unicode, domain,
username, hostname);
DCHECK(writer_result);
DCHECK(authenticate_writer.IsEndOfBuffer());
DCHECK_EQ(authenticate_message_len, authenticate_writer.GetLength());
std::vector<uint8_t> auth_msg = authenticate_writer.Pass();
if (IsMicEnabled()) {
DCHECK_LT(kMicOffsetV2 + kMicLenV2, authenticate_message_len);
base::span<uint8_t, kMicLenV2> mic(
const_cast<uint8_t*>(auth_msg.data()) + kMicOffsetV2, kMicLenV2);
GenerateMicV2(v2_session_key, negotiate_message_, server_challenge_message,
auth_msg, mic);
}
return auth_msg;
}
Vulnerability Type: Dir. Trav.
CWE ID: CWE-22
Summary: Google Chrome before 50.0.2661.102 on Android mishandles / (slash) and (backslash) characters, which allows attackers to conduct directory traversal attacks via a file: URL, related to net/base/escape.cc and net/base/filename_util.cc.
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586657} | Medium | 172,277 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)
{ psf->header [psf->headindex++] = (x >> 56) ;
psf->header [psf->headindex++] = (x >> 48) ;
psf->header [psf->headindex++] = (x >> 40) ;
psf->header [psf->headindex++] = (x >> 32) ;
psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_8byte */
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: In libsndfile before 1.0.28, an error in the *header_read()* function (common.c) when handling ID3 tags can be exploited to cause a stack-based buffer overflow via a specially crafted FLAC file.
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k. | Medium | 170,050 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void f2fs_put_super(struct super_block *sb)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
int i;
f2fs_quota_off_umount(sb);
/* prevent remaining shrinker jobs */
mutex_lock(&sbi->umount_mutex);
/*
* We don't need to do checkpoint when superblock is clean.
* But, the previous checkpoint was not done by umount, it needs to do
* clean checkpoint again.
*/
if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
struct cp_control cpc = {
.reason = CP_UMOUNT,
};
write_checkpoint(sbi, &cpc);
}
/* be sure to wait for any on-going discard commands */
f2fs_wait_discard_bios(sbi);
if (f2fs_discard_en(sbi) && !sbi->discard_blks) {
struct cp_control cpc = {
.reason = CP_UMOUNT | CP_TRIMMED,
};
write_checkpoint(sbi, &cpc);
}
/* write_checkpoint can update stat informaion */
f2fs_destroy_stats(sbi);
/*
* normally superblock is clean, so we need to release this.
* In addition, EIO will skip do checkpoint, we need this as well.
*/
release_ino_entry(sbi, true);
f2fs_leave_shrinker(sbi);
mutex_unlock(&sbi->umount_mutex);
/* our cp_error case, we can wait for any writeback page */
f2fs_flush_merged_writes(sbi);
iput(sbi->node_inode);
iput(sbi->meta_inode);
/* destroy f2fs internal modules */
destroy_node_manager(sbi);
destroy_segment_manager(sbi);
kfree(sbi->ckpt);
f2fs_unregister_sysfs(sbi);
sb->s_fs_info = NULL;
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->raw_super);
destroy_device_list(sbi);
mempool_destroy(sbi->write_io_dummy);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
destroy_percpu_info(sbi);
for (i = 0; i < NR_PAGE_TYPE; i++)
kfree(sbi->write_io[i]);
kfree(sbi);
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The f2fs implementation in the Linux kernel before 4.14 mishandles reference counts associated with f2fs_wait_discard_bios calls, which allows local users to cause a denial of service (BUG), as demonstrated by fstrim.
Commit Message: f2fs: fix potential panic during fstrim
As Ju Hyung Park reported:
"When 'fstrim' is called for manual trim, a BUG() can be triggered
randomly with this patch.
I'm seeing this issue on both x86 Desktop and arm64 Android phone.
On x86 Desktop, this was caused during Ubuntu boot-up. I have a
cronjob installed which calls 'fstrim -v /' during boot. On arm64
Android, this was caused during GC looping with 1ms gc_min_sleep_time
& gc_max_sleep_time."
Root cause of this issue is that f2fs_wait_discard_bios can only be
used by f2fs_put_super, because during put_super there must be no
other referrers, so it can ignore discard entry's reference count
when removing the entry, otherwise in other caller we will hit bug_on
in __remove_discard_cmd as there may be other issuer added reference
count in discard entry.
Thread A Thread B
- issue_discard_thread
- f2fs_ioc_fitrim
- f2fs_trim_fs
- f2fs_wait_discard_bios
- __issue_discard_cmd
- __submit_discard_cmd
- __wait_discard_cmd
- dc->ref++
- __wait_one_discard_bio
- __wait_discard_cmd
- __remove_discard_cmd
- f2fs_bug_on(sbi, dc->ref)
Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de
Reported-by: Ju Hyung Park <[email protected]>
Signed-off-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]> | Medium | 169,415 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult(
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256) {
if (client_) {
base::Value event(base::Value::Type::DICTIONARY);
event.SetStringKey(kKeyUrl, url.spec());
event.SetStringKey(kKeyFileName, file_name);
event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256);
event.SetStringKey(kKeyProfileUserName, GetProfileUserName());
ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event));
}
}
Vulnerability Type:
CWE ID: CWE-416
Summary: A use after free in PDFium in Google Chrome prior to 57.0.2987.98 for Mac, Windows, and Linux and 57.0.2987.108 for Android allowed a remote attacker to have an unspecified impact via a crafted PDF file.
Commit Message: Add reporting for DLP deep scanning
For each triggered rule in the DLP response, we report the download as
violating that rule.
This also implements the UnsafeReportingEnabled enterprise policy, which
controls whether or not we do any reporting.
Bug: 980777
Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381
Commit-Queue: Daniel Rubery <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#691371} | Medium | 172,412 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
if (!restart_required_ && reboot_was_requested_) {
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in modules/webaudio/AudioScheduledSourceNode.cpp in the Web Audio implementation in Blink, as used in Google Chrome before 30.0.1599.66, allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
Commit Message: Rollback option put behind the flag.
BUG=368860
Review URL: https://codereview.chromium.org/267393011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,181 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
{
png_bytep best_row;
#ifdef PNG_WRITE_FILTER_SUPPORTED
png_bytep prev_row, row_buf;
png_uint_32 mins, bpp;
png_byte filter_to_do = png_ptr->do_filter;
png_uint_32 row_bytes = row_info->rowbytes;
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
int num_p_filters = (int)png_ptr->num_prev_filters;
#endif
png_debug(1, "in png_write_find_filter");
#ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
{
/* These will never be selected so we need not test them. */
filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
}
#endif
/* Find out how many bytes offset each pixel is */
bpp = (row_info->pixel_depth + 7) >> 3;
prev_row = png_ptr->prev_row;
#endif
best_row = png_ptr->row_buf;
#ifdef PNG_WRITE_FILTER_SUPPORTED
row_buf = best_row;
mins = PNG_MAXSUM;
/* The prediction method we use is to find which method provides the
* smallest value when summing the absolute values of the distances
* from zero, using anything >= 128 as negative numbers. This is known
* as the "minimum sum of absolute differences" heuristic. Other
* heuristics are the "weighted minimum sum of absolute differences"
* (experimental and can in theory improve compression), and the "zlib
* predictive" method (not implemented yet), which does test compressions
* of lines using different filter methods, and then chooses the
* (series of) filter(s) that give minimum compressed data size (VERY
* computationally expensive).
*
* GRR 980525: consider also
* (1) minimum sum of absolute differences from running average (i.e.,
* keep running sum of non-absolute differences & count of bytes)
* [track dispersion, too? restart average if dispersion too large?]
* (1b) minimum sum of absolute differences from sliding average, probably
* with window size <= deflate window (usually 32K)
* (2) minimum sum of squared differences from zero or running average
* (i.e., ~ root-mean-square approach)
*/
/* We don't need to test the 'no filter' case if this is the only filter
* that has been chosen, as it doesn't actually do anything to the data.
*/
if ((filter_to_do & PNG_FILTER_NONE) &&
filter_to_do != PNG_FILTER_NONE)
{
png_bytep rp;
png_uint_32 sum = 0;
png_uint_32 i;
int v;
for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
{
v = *rp;
sum += (v < 128) ? v : 256 - v;
}
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
png_uint_32 sumhi, sumlo;
int j;
sumlo = sum & PNG_LOMASK;
sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
/* Reduce the sum if we match any of the previous rows */
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
{
sumlo = (sumlo * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
sumhi = (sumhi * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
/* Factor in the cost of this filter (this is here for completeness,
* but it makes no sense to have a "cost" for the NONE filter, as
* it has the minimum possible computational cost - none).
*/
sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
PNG_COST_SHIFT;
sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
PNG_COST_SHIFT;
if (sumhi > PNG_HIMASK)
sum = PNG_MAXSUM;
else
sum = (sumhi << PNG_HISHIFT) + sumlo;
}
#endif
mins = sum;
}
/* Sub filter */
if (filter_to_do == PNG_FILTER_SUB)
/* It's the only filter so no testing is needed */
{
png_bytep rp, lp, dp;
png_uint_32 i;
for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
i++, rp++, dp++)
{
*dp = *rp;
}
for (lp = row_buf + 1; i < row_bytes;
i++, rp++, lp++, dp++)
{
*dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
}
best_row = png_ptr->sub_row;
}
else if (filter_to_do & PNG_FILTER_SUB)
{
png_bytep rp, dp, lp;
png_uint_32 sum = 0, lmins = mins;
png_uint_32 i;
int v;
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
/* We temporarily increase the "minimum sum" by the factor we
* would reduce the sum of this filter, so that we can do the
* early exit comparison without scaling the sum each time.
*/
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 lmhi, lmlo;
lmlo = lmins & PNG_LOMASK;
lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
{
lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
PNG_COST_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
PNG_COST_SHIFT;
if (lmhi > PNG_HIMASK)
lmins = PNG_MAXSUM;
else
lmins = (lmhi << PNG_HISHIFT) + lmlo;
}
#endif
for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
i++, rp++, dp++)
{
v = *dp = *rp;
sum += (v < 128) ? v : 256 - v;
}
for (lp = row_buf + 1; i < row_bytes;
i++, rp++, lp++, dp++)
{
v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
sum += (v < 128) ? v : 256 - v;
if (sum > lmins) /* We are already worse, don't continue. */
break;
}
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 sumhi, sumlo;
sumlo = sum & PNG_LOMASK;
sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
{
sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
PNG_COST_SHIFT;
sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
PNG_COST_SHIFT;
if (sumhi > PNG_HIMASK)
sum = PNG_MAXSUM;
else
sum = (sumhi << PNG_HISHIFT) + sumlo;
}
#endif
if (sum < mins)
{
mins = sum;
best_row = png_ptr->sub_row;
}
}
/* Up filter */
if (filter_to_do == PNG_FILTER_UP)
{
png_bytep rp, dp, pp;
png_uint_32 i;
for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
pp = prev_row + 1; i < row_bytes;
i++, rp++, pp++, dp++)
{
*dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
}
best_row = png_ptr->up_row;
}
else if (filter_to_do & PNG_FILTER_UP)
{
png_bytep rp, dp, pp;
png_uint_32 sum = 0, lmins = mins;
png_uint_32 i;
int v;
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 lmhi, lmlo;
lmlo = lmins & PNG_LOMASK;
lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
{
lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
PNG_COST_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
PNG_COST_SHIFT;
if (lmhi > PNG_HIMASK)
lmins = PNG_MAXSUM;
else
lmins = (lmhi << PNG_HISHIFT) + lmlo;
}
#endif
for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
pp = prev_row + 1; i < row_bytes; i++)
{
v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
sum += (v < 128) ? v : 256 - v;
if (sum > lmins) /* We are already worse, don't continue. */
break;
}
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 sumhi, sumlo;
sumlo = sum & PNG_LOMASK;
sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
{
sumlo = (sumlo * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
sumhi = (sumhi * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
PNG_COST_SHIFT;
sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
PNG_COST_SHIFT;
if (sumhi > PNG_HIMASK)
sum = PNG_MAXSUM;
else
sum = (sumhi << PNG_HISHIFT) + sumlo;
}
#endif
if (sum < mins)
{
mins = sum;
best_row = png_ptr->up_row;
}
}
/* Avg filter */
if (filter_to_do == PNG_FILTER_AVG)
{
png_bytep rp, dp, pp, lp;
png_uint_32 i;
for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
pp = prev_row + 1; i < bpp; i++)
{
*dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
}
for (lp = row_buf + 1; i < row_bytes; i++)
{
*dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
& 0xff);
}
best_row = png_ptr->avg_row;
}
else if (filter_to_do & PNG_FILTER_AVG)
{
png_bytep rp, dp, pp, lp;
png_uint_32 sum = 0, lmins = mins;
png_uint_32 i;
int v;
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 lmhi, lmlo;
lmlo = lmins & PNG_LOMASK;
lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
{
lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
PNG_COST_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
PNG_COST_SHIFT;
if (lmhi > PNG_HIMASK)
lmins = PNG_MAXSUM;
else
lmins = (lmhi << PNG_HISHIFT) + lmlo;
}
#endif
for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
pp = prev_row + 1; i < bpp; i++)
{
v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
sum += (v < 128) ? v : 256 - v;
}
for (lp = row_buf + 1; i < row_bytes; i++)
{
v = *dp++ =
(png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
sum += (v < 128) ? v : 256 - v;
if (sum > lmins) /* We are already worse, don't continue. */
break;
}
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 sumhi, sumlo;
sumlo = sum & PNG_LOMASK;
sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
{
sumlo = (sumlo * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
sumhi = (sumhi * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
PNG_COST_SHIFT;
sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
PNG_COST_SHIFT;
if (sumhi > PNG_HIMASK)
sum = PNG_MAXSUM;
else
sum = (sumhi << PNG_HISHIFT) + sumlo;
}
#endif
if (sum < mins)
{
mins = sum;
best_row = png_ptr->avg_row;
}
}
/* Paeth filter */
if (filter_to_do == PNG_FILTER_PAETH)
{
png_bytep rp, dp, pp, cp, lp;
png_uint_32 i;
for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
pp = prev_row + 1; i < bpp; i++)
{
*dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
}
for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
{
int a, b, c, pa, pb, pc, p;
b = *pp++;
c = *cp++;
a = *lp++;
p = b - c;
pc = a - c;
#ifdef PNG_USE_ABS
pa = abs(p);
pb = abs(pc);
pc = abs(p + pc);
#else
pa = p < 0 ? -p : p;
pb = pc < 0 ? -pc : pc;
pc = (p + pc) < 0 ? -(p + pc) : p + pc;
#endif
p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
*dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
}
best_row = png_ptr->paeth_row;
}
else if (filter_to_do & PNG_FILTER_PAETH)
{
png_bytep rp, dp, pp, cp, lp;
png_uint_32 sum = 0, lmins = mins;
png_uint_32 i;
int v;
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 lmhi, lmlo;
lmlo = lmins & PNG_LOMASK;
lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
{
lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
PNG_COST_SHIFT;
lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
PNG_COST_SHIFT;
if (lmhi > PNG_HIMASK)
lmins = PNG_MAXSUM;
else
lmins = (lmhi << PNG_HISHIFT) + lmlo;
}
#endif
for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
pp = prev_row + 1; i < bpp; i++)
{
v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
sum += (v < 128) ? v : 256 - v;
}
for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
{
int a, b, c, pa, pb, pc, p;
b = *pp++;
c = *cp++;
a = *lp++;
#ifndef PNG_SLOW_PAETH
p = b - c;
pc = a - c;
#ifdef PNG_USE_ABS
pa = abs(p);
pb = abs(pc);
pc = abs(p + pc);
#else
pa = p < 0 ? -p : p;
pb = pc < 0 ? -pc : pc;
pc = (p + pc) < 0 ? -(p + pc) : p + pc;
#endif
p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
#else /* PNG_SLOW_PAETH */
p = a + b - c;
pa = abs(p - a);
pb = abs(p - b);
pc = abs(p - c);
if (pa <= pb && pa <= pc)
p = a;
else if (pb <= pc)
p = b;
else
p = c;
#endif /* PNG_SLOW_PAETH */
v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
sum += (v < 128) ? v : 256 - v;
if (sum > lmins) /* We are already worse, don't continue. */
break;
}
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
{
int j;
png_uint_32 sumhi, sumlo;
sumlo = sum & PNG_LOMASK;
sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
for (j = 0; j < num_p_filters; j++)
{
if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
{
sumlo = (sumlo * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
sumhi = (sumhi * png_ptr->filter_weights[j]) >>
PNG_WEIGHT_SHIFT;
}
}
sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
PNG_COST_SHIFT;
sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
PNG_COST_SHIFT;
if (sumhi > PNG_HIMASK)
sum = PNG_MAXSUM;
else
sum = (sumhi << PNG_HISHIFT) + sumlo;
}
#endif
if (sum < mins)
{
best_row = png_ptr->paeth_row;
}
}
#endif /* PNG_WRITE_FILTER_SUPPORTED */
/* Do the actual writing of the filtered row data from the chosen filter. */
png_write_filtered_row(png_ptr, best_row);
#ifdef PNG_WRITE_FILTER_SUPPORTED
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
/* Save the type of filter we picked this time for future calculations */
if (png_ptr->num_prev_filters > 0)
{
int j;
for (j = 1; j < num_p_filters; j++)
{
png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
}
png_ptr->prev_filters[j] = best_row[0];
}
#endif
#endif /* PNG_WRITE_FILTER_SUPPORTED */
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Multiple buffer overflows in the (1) png_set_PLTE and (2) png_get_PLTE functions in libpng before 1.0.64, 1.1.x and 1.2.x before 1.2.54, 1.3.x and 1.4.x before 1.4.17, 1.5.x before 1.5.24, and 1.6.x before 1.6.19 allow remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a small bit-depth value in an IHDR (aka image header) chunk in a PNG image.
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298} | High | 172,194 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
int ret = 400;
BUFFER *dimensions = NULL;
buffer_flush(w->response.data);
char *google_version = "0.6",
*google_reqId = "0",
*google_sig = "0",
*google_out = "json",
*responseHandler = NULL,
*outFileName = NULL;
time_t last_timestamp_in_data = 0, google_timestamp = 0;
char *chart = NULL
, *before_str = NULL
, *after_str = NULL
, *group_time_str = NULL
, *points_str = NULL;
int group = RRDR_GROUPING_AVERAGE;
uint32_t format = DATASOURCE_JSON;
uint32_t options = 0x00000000;
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
if(!strcmp(name, "chart")) chart = value;
else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
if(!dimensions) dimensions = buffer_create(100);
buffer_strcat(dimensions, "|");
buffer_strcat(dimensions, value);
}
else if(!strcmp(name, "after")) after_str = value;
else if(!strcmp(name, "before")) before_str = value;
else if(!strcmp(name, "points")) points_str = value;
else if(!strcmp(name, "gtime")) group_time_str = value;
else if(!strcmp(name, "group")) {
group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);
}
else if(!strcmp(name, "format")) {
format = web_client_api_request_v1_data_format(value);
}
else if(!strcmp(name, "options")) {
options |= web_client_api_request_v1_data_options(value);
}
else if(!strcmp(name, "callback")) {
responseHandler = value;
}
else if(!strcmp(name, "filename")) {
outFileName = value;
}
else if(!strcmp(name, "tqx")) {
char *tqx_name, *tqx_value;
while(value) {
tqx_value = mystrsep(&value, ";");
if(!tqx_value || !*tqx_value) continue;
tqx_name = mystrsep(&tqx_value, ":");
if(!tqx_name || !*tqx_name) continue;
if(!tqx_value || !*tqx_value) continue;
if(!strcmp(tqx_name, "version"))
google_version = tqx_value;
else if(!strcmp(tqx_name, "reqId"))
google_reqId = tqx_value;
else if(!strcmp(tqx_name, "sig")) {
google_sig = tqx_value;
google_timestamp = strtoul(google_sig, NULL, 0);
}
else if(!strcmp(tqx_name, "out")) {
google_out = tqx_value;
format = web_client_api_request_v1_data_google_format(google_out);
}
else if(!strcmp(tqx_name, "responseHandler"))
responseHandler = tqx_value;
else if(!strcmp(tqx_name, "outFileName"))
outFileName = tqx_value;
}
}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
st->last_accessed_time = now_realtime_sec();
long long before = (before_str && *before_str)?str2l(before_str):0;
long long after = (after_str && *after_str) ?str2l(after_str):0;
int points = (points_str && *points_str)?str2i(points_str):0;
long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
, w->id
, chart
, (dimensions)?buffer_tostring(dimensions):""
, after
, before
, points
, group
, format
, options
);
if(outFileName && *outFileName) {
buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
}
if(format == DATASOURCE_DATATABLE_JSONP) {
if(responseHandler == NULL)
responseHandler = "google.visualization.Query.setResponse";
debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
}
else if(format == DATASOURCE_JSONP) {
if(responseHandler == NULL)
responseHandler = "callback";
buffer_strcat(w->response.data, responseHandler);
buffer_strcat(w->response.data, "(");
}
ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time
, options, &last_timestamp_in_data);
if(format == DATASOURCE_DATATABLE_JSONP) {
if(google_timestamp < last_timestamp_in_data)
buffer_strcat(w->response.data, "});");
else {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
responseHandler, google_version, google_reqId);
}
}
else if(format == DATASOURCE_JSONP)
buffer_strcat(w->response.data, ");");
cleanup:
buffer_free(dimensions);
return ret;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: ** DISPUTED ** An issue was discovered in Netdata 1.10.0. Full Path Disclosure (FPD) exists via api/v1/alarms. NOTE: the vendor says *is intentional.*
Commit Message: fixed vulnerabilities identified by red4sec.com (#4521) | Medium | 169,813 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int __init init_ext2_fs(void)
{
int err = init_ext2_xattr();
if (err)
return err;
err = init_inodecache();
if (err)
goto out1;
err = register_filesystem(&ext2_fs_type);
if (err)
goto out;
return 0;
out:
destroy_inodecache();
out1:
exit_ext2_xattr();
return err;
}
Vulnerability Type: DoS
CWE ID: CWE-19
Summary: The mbcache feature in the ext2 and ext4 filesystem implementations in the Linux kernel before 4.6 mishandles xattr block caching, which allows local users to cause a denial of service (soft lockup) via filesystem operations in environments that use many attributes, as demonstrated by Ceph and Samba.
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]> | Low | 169,975 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
{
spin_unlock(&hb->lock);
drop_futex_key_refs(&q->key);
}
Vulnerability Type: DoS Overflow +Priv
CWE ID: CWE-119
Summary: The futex_wait function in kernel/futex.c in the Linux kernel before 2.6.37 does not properly maintain a certain reference count during requeue operations, which allows local users to cause a denial of service (use-after-free and system crash) or possibly gain privileges via a crafted application that triggers a zero count.
Commit Message: futex: Fix errors in nested key ref-counting
futex_wait() is leaking key references due to futex_wait_setup()
acquiring an additional reference via the queue_lock() routine. The
nested key ref-counting has been masking bugs and complicating code
analysis. queue_lock() is only called with a previously ref-counted
key, so remove the additional ref-counting from the queue_(un)lock()
functions.
Also futex_wait_requeue_pi() drops one key reference too many in
unqueue_me_pi(). Remove the key reference handling from
unqueue_me_pi(). This was paired with a queue_lock() in
futex_lock_pi(), so the count remains unchanged.
Document remaining nested key ref-counting sites.
Signed-off-by: Darren Hart <[email protected]>
Reported-and-tested-by: Matthieu Fertré<[email protected]>
Reported-by: Louis Rilling<[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: John Kacur <[email protected]>
Cc: Rusty Russell <[email protected]>
LKML-Reference: <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: [email protected] | Medium | 166,452 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
unsigned int, flags, struct sockaddr __user *, addr,
int, addr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int err;
struct msghdr msg;
struct iovec iov;
int fput_needed;
if (len > INT_MAX)
len = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
iov.iov_base = buff;
iov.iov_len = len;
msg.msg_name = NULL;
iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len);
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_namelen = 0;
if (addr) {
err = move_addr_to_kernel(addr, addr_len, &address);
if (err < 0)
goto out_put;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = addr_len;
}
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
msg.msg_flags = flags;
err = sock_sendmsg(sock, &msg, len);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
Vulnerability Type: +Priv
CWE ID: CWE-264
Summary: net/socket.c in the Linux kernel 3.19 before 3.19.3 does not validate certain range data for (1) sendto and (2) recvfrom system calls, which allows local users to gain privileges by leveraging a subsystem that uses the copy_from_iter function in the iov_iter interface, as demonstrated by the Bluetooth subsystem.
Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom
Cc: [email protected] # v3.19
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | High | 167,570 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) {
LOG(WARNING) << "IBus connection is terminated.";
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->MaybeDestroyIBusConfig();
if (self->connection_change_handler_) {
LOG(INFO) << "Notifying Chrome that IBus is terminated.";
self->connection_change_handler_(self->language_library_, false);
}
}
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 | High | 170,537 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int ret;
int copylen;
ret = -EOPNOTSUPP;
if (m->msg_flags&MSG_OOB)
goto read_error;
skb = skb_recv_datagram(sk, flags, 0 , &ret);
if (!skb)
goto read_error;
copylen = skb->len;
if (len < copylen) {
m->msg_flags |= MSG_TRUNC;
copylen = len;
}
ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);
if (ret)
goto out_free;
ret = (flags & MSG_TRUNC) ? skb->len : copylen;
out_free:
skb_free_datagram(sk, skb);
caif_check_flow_release(sk);
return ret;
read_error:
return ret;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The caif_seqpkt_recvmsg function in net/caif/caif_socket.c in the Linux kernel before 3.9-rc7 does not initialize a certain length variable, which allows local users to obtain sensitive information from kernel stack memory via a crafted recvmsg or recvfrom system call.
Commit Message: caif: Fix missing msg_namelen update in caif_seqpkt_recvmsg()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about caif_seqpkt_recvmsg() not filling the msg_name in case it was
set.
Cc: Sjur Braendeland <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Medium | 166,040 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0));
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
delayed_send.Cancel();
static const base::TimeDelta swap_delay = GetSwapDelay();
if (swap_delay.ToInternalValue())
base::PlatformThread::Sleep(swap_delay);
view->AcceleratedSurfaceBuffersSwapped(params, host_id_);
}
Vulnerability Type:
CWE ID:
Summary: Google Chrome before 25.0.1364.99 on Mac OS X does not properly implement signal handling for Native Client (aka NaCl) code, which has unspecified impact and attack vectors.
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,357 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Memory leak in the v9fs_link function in hw/9pfs/9p.c in QEMU (aka Quick Emulator) allows local guest OS administrators to cause a denial of service (memory consumption) via vectors involving a reference to the source fid object.
Commit Message: | Low | 164,907 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int ipmi_destroy_user(struct ipmi_user *user)
{
_ipmi_destroy_user(user);
cleanup_srcu_struct(&user->release_barrier);
kref_put(&user->refcount, free_user);
return 0;
}
Vulnerability Type: Exec Code
CWE ID: CWE-416
Summary: In the Linux kernel before 4.20.5, attackers can trigger a drivers/char/ipmi/ipmi_msghandler.c use-after-free and OOPS by arranging for certain simultaneous execution of the code, as demonstrated by a *service ipmievd restart* loop.
Commit Message: ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: [email protected] # 4.18
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]> | High | 169,726 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void TopSitesImpl::SetTopSites(const MostVisitedURLList& new_top_sites,
const CallLocation location) {
DCHECK(thread_checker_.CalledOnValidThread());
MostVisitedURLList top_sites(new_top_sites);
size_t num_forced_urls = MergeCachedForcedURLs(&top_sites);
AddPrepopulatedPages(&top_sites, num_forced_urls);
TopSitesDelta delta;
DiffMostVisited(cache_->top_sites(), top_sites, &delta);
TopSitesBackend::RecordHistogram record_or_not =
TopSitesBackend::RECORD_HISTOGRAM_NO;
if (location == CALL_LOCATION_FROM_ON_GOT_MOST_VISITED_THUMBNAILS &&
!histogram_recorded_) {
size_t delta_size =
delta.deleted.size() + delta.added.size() + delta.moved.size();
UMA_HISTOGRAM_COUNTS_100("History.FirstSetTopSitesDeltaSize", delta_size);
record_or_not = TopSitesBackend::RECORD_HISTOGRAM_YES;
histogram_recorded_ = true;
}
bool should_notify_observers = false;
if (!delta.deleted.empty() || !delta.added.empty() || !delta.moved.empty()) {
backend_->UpdateTopSites(delta, record_or_not);
should_notify_observers = true;
}
if (!should_notify_observers)
should_notify_observers = DoTitlesDiffer(cache_->top_sites(), top_sites);
cache_->SetTopSites(top_sites);
if (!temp_images_.empty()) {
for (const MostVisitedURL& mv : top_sites) {
const GURL& canonical_url = cache_->GetCanonicalURL(mv.url);
for (TempImages::iterator it = temp_images_.begin();
it != temp_images_.end(); ++it) {
if (canonical_url == cache_->GetCanonicalURL(it->first)) {
bool success = SetPageThumbnailEncoded(
mv.url, it->second.thumbnail.get(), it->second.thumbnail_score);
if (success) {
UMA_HISTOGRAM_ENUMERATION("Thumbnails.AddedToTopSites",
THUMBNAIL_PROMOTED_TEMP_TO_REGULAR,
THUMBNAIL_EVENT_COUNT);
}
temp_images_.erase(it);
break;
}
}
}
}
if (top_sites.size() - num_forced_urls >= kNonForcedTopSitesNumber)
temp_images_.clear();
ResetThreadSafeCache();
ResetThreadSafeImageCache();
if (should_notify_observers) {
if (location == CALL_LOCATION_FROM_FORCED_URLS)
NotifyTopSitesChanged(TopSitesObserver::ChangeReason::FORCED_URL);
else
NotifyTopSitesChanged(TopSitesObserver::ChangeReason::MOST_VISITED);
}
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Inappropriate implementation in New Tab Page in Google Chrome prior to 64.0.3282.119 allowed a local attacker to view website thumbnail images after clearing browser data via a crafted HTML page.
Commit Message: TopSites: Clear thumbnails from the cache when their URLs get removed
We already cleared the thumbnails from persistent storage, but they
remained in the in-memory cache, so they remained accessible (until the
next Chrome restart) even after all browsing data was cleared.
Bug: 758169
Change-Id: Id916d22358430a82e6d5043ac04fa463a32f824f
Reviewed-on: https://chromium-review.googlesource.com/758640
Commit-Queue: Marc Treib <[email protected]>
Reviewed-by: Sylvain Defresne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#514861} | Medium | 172,694 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool BrokerDuplicateHandle(HANDLE source_handle,
DWORD target_process_id,
HANDLE* target_handle,
DWORD desired_access,
DWORD options) {
if (!g_target_services) {
base::win::ScopedHandle target_process(::OpenProcess(PROCESS_DUP_HANDLE,
FALSE,
target_process_id));
if (!target_process.IsValid())
return false;
if (!::DuplicateHandle(::GetCurrentProcess(), source_handle,
target_process, target_handle,
desired_access, FALSE,
options)) {
return false;
}
return true;
}
ResultCode result = g_target_services->DuplicateHandle(source_handle,
target_process_id,
target_handle,
desired_access,
options);
return SBOX_ALL_OK == result;
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 | High | 170,946 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool PrintPreviewMessageHandler::OnMessageReceived(
const IPC::Message& message,
content::RenderFrameHost* render_frame_host) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(PrintPreviewMessageHandler, message,
render_frame_host)
IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview,
OnRequestPrintPreview)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount,
OnDidGetPreviewPageCount)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidPreviewPage,
OnDidPreviewPage)
IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting,
OnMetafileReadyForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewFailed,
OnPrintPreviewFailed)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetDefaultPageLayout,
OnDidGetDefaultPageLayout)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewCancelled,
OnPrintPreviewCancelled)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewInvalidPrinterSettings,
OnInvalidPrinterSettings)
IPC_MESSAGE_HANDLER(PrintHostMsg_SetOptionsFromDocument,
OnSetOptionsFromDocument)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
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.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616} | Medium | 171,889 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: PHP_FUNCTION(xml_set_object)
{
xml_parser *parser;
zval *pind, *mythis;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ro", &pind, &mythis) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser);
/* please leave this commented - or ask [email protected] before doing it (again) */
if (parser->object) {
zval_ptr_dtor(&parser->object);
}
/* please leave this commented - or ask [email protected] before doing it (again) */
/* #ifdef ZEND_ENGINE_2
zval_add_ref(&parser->object);
#endif */
ALLOC_ZVAL(parser->object);
MAKE_COPY_ZVAL(&mythis, parser->object);
RETVAL_TRUE;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The xml_parse_into_struct function in ext/xml/xml.c in PHP before 5.5.35, 5.6.x before 5.6.21, and 7.x before 7.0.6 allows remote attackers to cause a denial of service (buffer under-read and segmentation fault) or possibly have unspecified other impact via crafted XML data in the second argument, leading to a parser level of zero.
Commit Message: | High | 165,036 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ExtensionsGuestViewMessageFilter::~ExtensionsGuestViewMessageFilter() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
(*GetProcessIdToFilterMap())[render_process_id_] = nullptr;
base::PostTaskWithTraits(
FROM_HERE, BrowserThread::UI,
base::BindOnce(RemoveProcessIdFromGlobalMap, render_process_id_));
}
Vulnerability Type:
CWE ID: CWE-362
Summary: Data race in extensions guest view in Google Chrome prior to 73.0.3683.75 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155} | Medium | 173,051 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ProcRenderAddGlyphs (ClientPtr client)
{
GlyphSetPtr glyphSet;
REQUEST(xRenderAddGlyphsReq);
GlyphNewRec glyphsLocal[NLOCALGLYPH];
GlyphNewPtr glyphsBase, glyphs, glyph_new;
int remain, nglyphs;
CARD32 *gids;
xGlyphInfo *gi;
CARD8 *bits;
unsigned int size;
int err;
int i, screen;
PicturePtr pSrc = NULL, pDst = NULL;
PixmapPtr pSrcPix = NULL, pDstPix = NULL;
CARD32 component_alpha;
REQUEST_AT_LEAST_SIZE(xRenderAddGlyphsReq);
err = dixLookupResourceByType((pointer *)&glyphSet, stuff->glyphset, GlyphSetType,
client, DixAddAccess);
if (err != Success)
{
client->errorValue = stuff->glyphset;
return err;
}
err = BadAlloc;
nglyphs = stuff->nglyphs;
if (nglyphs > UINT32_MAX / sizeof(GlyphNewRec))
return BadAlloc;
component_alpha = NeedsComponent (glyphSet->format->format);
if (nglyphs <= NLOCALGLYPH) {
memset (glyphsLocal, 0, sizeof (glyphsLocal));
glyphsBase = glyphsLocal;
}
else
{
glyphsBase = (GlyphNewPtr)calloc(nglyphs, sizeof (GlyphNewRec));
if (!glyphsBase)
return BadAlloc;
}
remain = (client->req_len << 2) - sizeof (xRenderAddGlyphsReq);
glyphs = glyphsBase;
gids = (CARD32 *) (stuff + 1);
gi = (xGlyphInfo *) (gids + nglyphs);
bits = (CARD8 *) (gi + nglyphs);
remain -= (sizeof (CARD32) + sizeof (xGlyphInfo)) * nglyphs;
for (i = 0; i < nglyphs; i++)
{
size_t padded_width;
size = gi[i].height * padded_width;
if (remain < size)
break;
err = HashGlyph (&gi[i], bits, size, glyph_new->sha1);
if (err)
goto bail;
glyph_new->glyph = FindGlyphByHash (glyph_new->sha1,
glyphSet->fdepth);
if (glyph_new->glyph && glyph_new->glyph != DeletedGlyph)
{
glyph_new->found = TRUE;
}
else
{
GlyphPtr glyph;
glyph_new->found = FALSE;
glyph_new->glyph = glyph = AllocateGlyph (&gi[i], glyphSet->fdepth);
if (! glyph)
{
err = BadAlloc;
goto bail;
}
for (screen = 0; screen < screenInfo.numScreens; screen++)
{
int width = gi[i].width;
int height = gi[i].height;
int depth = glyphSet->format->depth;
ScreenPtr pScreen;
int error;
/* Skip work if it's invisibly small anyway */
if (!width || !height)
break;
pScreen = screenInfo.screens[screen];
pSrcPix = GetScratchPixmapHeader (pScreen,
width, height,
depth, depth,
-1, bits);
if (! pSrcPix)
{
err = BadAlloc;
goto bail;
}
pSrc = CreatePicture (0, &pSrcPix->drawable,
glyphSet->format, 0, NULL,
serverClient, &error);
if (! pSrc)
{
err = BadAlloc;
goto bail;
}
pDstPix = (pScreen->CreatePixmap) (pScreen,
width, height, depth,
CREATE_PIXMAP_USAGE_GLYPH_PICTURE);
if (!pDstPix)
{
err = BadAlloc;
goto bail;
}
GlyphPicture (glyph)[screen] = pDst =
CreatePicture (0, &pDstPix->drawable,
glyphSet->format,
CPComponentAlpha, &component_alpha,
serverClient, &error);
/* The picture takes a reference to the pixmap, so we
drop ours. */
(pScreen->DestroyPixmap) (pDstPix);
pDstPix = NULL;
if (! pDst)
{
err = BadAlloc;
goto bail;
}
CompositePicture (PictOpSrc,
pSrc,
None,
pDst,
0, 0,
0, 0,
0, 0,
width, height);
FreePicture ((pointer) pSrc, 0);
pSrc = NULL;
FreeScratchPixmapHeader (pSrcPix);
pSrcPix = NULL;
}
memcpy (glyph_new->glyph->sha1, glyph_new->sha1, 20);
}
glyph_new->id = gids[i];
if (size & 3)
size += 4 - (size & 3);
bits += size;
remain -= size;
}
if (remain || i < nglyphs)
{
err = BadLength;
goto bail;
}
if (!ResizeGlyphSet (glyphSet, nglyphs))
{
err = BadAlloc;
goto bail;
}
for (i = 0; i < nglyphs; i++)
AddGlyph (glyphSet, glyphs[i].glyph, glyphs[i].id);
if (glyphsBase != glyphsLocal)
free(glyphsBase);
return Success;
bail:
if (pSrc)
FreePicture ((pointer) pSrc, 0);
if (pSrcPix)
FreeScratchPixmapHeader (pSrcPix);
for (i = 0; i < nglyphs; i++)
if (glyphs[i].glyph && ! glyphs[i].found)
free(glyphs[i].glyph);
if (glyphsBase != glyphsLocal)
free(glyphsBase);
return err;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The ProcRenderAddGlyphs function in the Render extension (render/render.c) in X.Org xserver 1.7.7 and earlier allows local users to read arbitrary memory and possibly cause a denial of service (server crash) via unspecified vectors related to an "input sanitization flaw."
Commit Message: | Low | 165,268 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int strdup_if_nonnull(char **target, char *source)
{
if (source) {
*target = kstrdup(source, GFP_KERNEL);
if (!*target)
return -ENOMEM;
} else
*target = NULL;
return 0;
}
Vulnerability Type: DoS
CWE ID: CWE-404
Summary: The NFSv4 implementation in the Linux kernel through 4.11.1 allows local users to cause a denial of service (resource consumption) by leveraging improper channel callback shutdown when unmounting an NFSv4 filesystem, aka a *module reference and kernel daemon* leak.
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
... | Medium | 168,146 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Multiple integer overflows in the (1) jas_realloc function in base/jas_malloc.c and (2) mem_resize function in base/jas_stream.c in JasPer before 1.900.22 allow remote attackers to cause a denial of service via a crafted image, which triggers use after free vulnerabilities.
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior. | Medium | 168,744 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void opl3_setup_voice(int dev, int voice, int chn)
{
struct channel_info *info =
&synth_devs[dev]->chn_info[chn];
opl3_set_instr(dev, voice, info->pgm_num);
devc->voc[voice].bender = 0;
devc->voc[voice].bender_range = info->bender_range;
devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];
devc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;
}
Vulnerability Type: DoS Overflow +Priv Mem. Corr.
CWE ID: CWE-119
Summary: Multiple array index errors in sound/oss/opl3.c in the Linux kernel before 2.6.39 allow local users to cause a denial of service (heap memory corruption) or possibly gain privileges by leveraging write access to /dev/sequencer.
Commit Message: sound/oss/opl3: validate voice and channel indexes
User-controllable indexes for voice and channel values may cause reading
and writing beyond the bounds of their respective arrays, leading to
potentially exploitable memory corruption. Validate these indexes.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Signed-off-by: Takashi Iwai <[email protected]> | High | 165,891 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct pipe_inode_info *pipe;
long ret;
pipe = get_pipe_info(file);
if (!pipe)
return -EBADF;
__pipe_lock(pipe);
switch (cmd) {
case F_SETPIPE_SZ: {
unsigned int size, nr_pages;
size = round_pipe_size(arg);
nr_pages = size >> PAGE_SHIFT;
ret = -EINVAL;
if (!nr_pages)
goto out;
if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) {
ret = -EPERM;
goto out;
}
ret = pipe_set_size(pipe, nr_pages);
break;
}
case F_GETPIPE_SZ:
ret = pipe->buffers * PAGE_SIZE;
break;
default:
ret = -EINVAL;
break;
}
out:
__pipe_unlock(pipe);
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: fs/pipe.c in the Linux kernel before 4.5 does not limit the amount of unread data in pipes, which allows local users to cause a denial of service (memory consumption) by creating many pipes with non-default sizes.
Commit Message: pipe: limit the per-user amount of pages allocated in pipes
On no-so-small systems, it is possible for a single process to cause an
OOM condition by filling large pipes with data that are never read. A
typical process filling 4000 pipes with 1 MB of data will use 4 GB of
memory. On small systems it may be tricky to set the pipe max size to
prevent this from happening.
This patch makes it possible to enforce a per-user soft limit above
which new pipes will be limited to a single page, effectively limiting
them to 4 kB each, as well as a hard limit above which no new pipes may
be created for this user. This has the effect of protecting the system
against memory abuse without hurting other users, and still allowing
pipes to work correctly though with less data at once.
The limit are controlled by two new sysctls : pipe-user-pages-soft, and
pipe-user-pages-hard. Both may be disabled by setting them to zero. The
default soft limit allows the default number of FDs per process (1024)
to create pipes of the default size (64kB), thus reaching a limit of 64MB
before starting to create only smaller pipes. With 256 processes limited
to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB =
1084 MB of memory allocated for a user. The hard limit is disabled by
default to avoid breaking existing applications that make intensive use
of pipes (eg: for splicing).
Reported-by: [email protected]
Reported-by: Tetsuo Handa <[email protected]>
Mitigates: CVE-2013-4312 (Linux 2.0+)
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Al Viro <[email protected]> | Medium | 167,388 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void UpdateProperty(const ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
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 | High | 170,509 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ExtensionInstallDialogView::ExtensionInstallDialogView(
Profile* profile,
content::PageNavigator* navigator,
const ExtensionInstallPrompt::DoneCallback& done_callback,
std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt)
: profile_(profile),
navigator_(navigator),
done_callback_(done_callback),
prompt_(std::move(prompt)),
container_(NULL),
scroll_view_(NULL),
handled_result_(false) {
InitView();
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Lack of timeout on extension install prompt in Extensions in Google Chrome prior to 68.0.3440.75 allowed a remote attacker to trigger installation of an unwanted extension via a crafted HTML page.
Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period.
BUG=394518
Review-Url: https://codereview.chromium.org/2716353003
Cr-Commit-Position: refs/heads/master@{#461933} | Medium | 173,159 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: base::PlatformFileError ModifyCacheState(
const FilePath& source_path,
const FilePath& dest_path,
GDataCache::FileOperationType file_operation_type,
const FilePath& symlink_path,
bool create_symlink) {
if (source_path != dest_path) {
bool success = false;
if (file_operation_type == GDataCache::FILE_OPERATION_MOVE)
success = file_util::Move(source_path, dest_path);
else if (file_operation_type == GDataCache::FILE_OPERATION_COPY)
success = file_util::CopyFile(source_path, dest_path);
if (!success) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error "
<< (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"moving " : "copying ")
<< source_path.value()
<< " to " << dest_path.value();
return error;
} else {
DVLOG(1) << (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"Moved " : "Copied ")
<< source_path.value()
<< " to " << dest_path.value();
}
} else {
DVLOG(1) << "No need to move file: source = destination";
}
if (symlink_path.empty())
return base::PLATFORM_FILE_OK;
bool deleted = util::DeleteSymlink(symlink_path);
if (deleted) {
DVLOG(1) << "Deleted symlink " << symlink_path.value();
} else {
if (errno != ENOENT)
PLOG(WARNING) << "Error deleting symlink " << symlink_path.value();
}
if (!create_symlink)
return base::PLATFORM_FILE_OK;
if (!file_util::CreateSymbolicLink(dest_path, symlink_path)) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error creating symlink " << symlink_path.value()
<< " for " << dest_path.value();
return error;
} else {
DVLOG(1) << "Created symlink " << symlink_path.value()
<< " to " << dest_path.value();
}
return base::PLATFORM_FILE_OK;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The PDF functionality in Google Chrome before 22.0.1229.79 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger out-of-bounds write operations.
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 170,863 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct sock *sk = sock->sk;
struct tcp_splice_state tss = {
.pipe = pipe,
.len = len,
.flags = flags,
};
long timeo;
ssize_t spliced;
int ret;
sock_rps_record_flow(sk);
/*
* We can't seek on a socket input
*/
if (unlikely(*ppos))
return -ESPIPE;
ret = spliced = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
while (tss.len) {
ret = __tcp_splice_read(sk, &tss);
if (ret < 0)
break;
else if (!ret) {
if (spliced)
break;
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
ret = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
if (!sock_flag(sk, SOCK_DONE))
ret = -ENOTCONN;
break;
}
if (!timeo) {
ret = -EAGAIN;
break;
}
sk_wait_data(sk, &timeo, NULL);
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
continue;
}
tss.len -= ret;
spliced += ret;
if (!timeo)
break;
release_sock(sk);
lock_sock(sk);
if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current))
break;
}
release_sock(sk);
if (spliced)
return spliced;
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-835
Summary: The tcp_splice_read function in net/ipv4/tcp.c in the Linux kernel before 4.9.11 allows remote attackers to cause a denial of service (infinite loop and soft lockup) via vectors involving a TCP packet with the URG flag.
Commit Message: tcp: avoid infinite loop in tcp_splice_read()
Splicing from TCP socket is vulnerable when a packet with URG flag is
received and stored into receive queue.
__tcp_splice_read() returns 0, and sk_wait_data() immediately
returns since there is the problematic skb in queue.
This is a nice way to burn cpu (aka infinite loop) and trigger
soft lockups.
Again, this gem was found by syzkaller tool.
Fixes: 9c55e01c0cc8 ("[TCP]: Splice receive support.")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Medium | 168,361 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void FolderHeaderView::ContentsChanged(views::Textfield* sender,
const base::string16& new_contents) {
if (!folder_item_)
return;
folder_item_->RemoveObserver(this);
std::string name = base::UTF16ToUTF8(folder_name_view_->text());
delegate_->SetItemName(folder_item_, name);
folder_item_->AddObserver(this);
Layout();
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in the HTMLMediaElement::didMoveToNewDocument function in core/html/HTMLMediaElement.cpp in Blink, as used in Google Chrome before 29.0.1547.57, allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving moving a (1) AUDIO or (2) VIDEO element between documents.
Commit Message: Enforce the maximum length of the folder name in UI.
BUG=355797
[email protected]
Review URL: https://codereview.chromium.org/203863005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,200 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: status_t BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
void *params = malloc(size);
data.read(params, size);
status_t err;
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
free(params);
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
status_t err = createInputSurface(node, port_index,
&bufferProducer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(bufferProducer->asBinder());
}
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = storeMetaDataInBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(fillBuffer(node, buffer));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
reply->writeInt32(
emptyBuffer(
node, buffer, range_offset, range_length,
flags, timestamp));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Vulnerability Type: Bypass +Info
CWE ID: CWE-264
Summary: media/libmedia/IOMX.cpp in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-04-01 does not initialize a parameter data structure, which allows attackers to obtain sensitive information from process memory, and consequently bypass an unspecified protection mechanism, via unspecified vectors, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 26914474.
Commit Message: Clear allocation to avoid info leak
Bug: 26914474
Change-Id: Ie1a86e86d78058d041149fe599a4996e7f8185cf
| High | 173,893 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void RecordDailyContentLengthHistograms(
int64 original_length,
int64 received_length,
int64 original_length_with_data_reduction_enabled,
int64 received_length_with_data_reduction_enabled,
int64 original_length_via_data_reduction_proxy,
int64 received_length_via_data_reduction_proxy) {
if (original_length <= 0 || received_length <= 0)
return;
UMA_HISTOGRAM_COUNTS(
"Net.DailyOriginalContentLength", original_length >> 10);
UMA_HISTOGRAM_COUNTS(
"Net.DailyContentLength", received_length >> 10);
int percent = 0;
if (original_length > received_length) {
percent = (100 * (original_length - received_length)) / original_length;
}
UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent);
if (original_length_with_data_reduction_enabled <= 0 ||
received_length_with_data_reduction_enabled <= 0) {
return;
}
UMA_HISTOGRAM_COUNTS(
"Net.DailyOriginalContentLength_DataReductionProxyEnabled",
original_length_with_data_reduction_enabled >> 10);
UMA_HISTOGRAM_COUNTS(
"Net.DailyContentLength_DataReductionProxyEnabled",
received_length_with_data_reduction_enabled >> 10);
int percent_data_reduction_proxy_enabled = 0;
if (original_length_with_data_reduction_enabled >
received_length_with_data_reduction_enabled) {
percent_data_reduction_proxy_enabled =
100 * (original_length_with_data_reduction_enabled -
received_length_with_data_reduction_enabled) /
original_length_with_data_reduction_enabled;
}
UMA_HISTOGRAM_PERCENTAGE(
"Net.DailyContentSavingPercent_DataReductionProxyEnabled",
percent_data_reduction_proxy_enabled);
UMA_HISTOGRAM_PERCENTAGE(
"Net.DailyContentPercent_DataReductionProxyEnabled",
(100 * received_length_with_data_reduction_enabled) / received_length);
if (original_length_via_data_reduction_proxy <= 0 ||
received_length_via_data_reduction_proxy <= 0) {
return;
}
UMA_HISTOGRAM_COUNTS(
"Net.DailyOriginalContentLength_ViaDataReductionProxy",
original_length_via_data_reduction_proxy >> 10);
UMA_HISTOGRAM_COUNTS(
"Net.DailyContentLength_ViaDataReductionProxy",
received_length_via_data_reduction_proxy >> 10);
int percent_via_data_reduction_proxy = 0;
if (original_length_via_data_reduction_proxy >
received_length_via_data_reduction_proxy) {
percent_via_data_reduction_proxy =
100 * (original_length_via_data_reduction_proxy -
received_length_via_data_reduction_proxy) /
original_length_via_data_reduction_proxy;
}
UMA_HISTOGRAM_PERCENTAGE(
"Net.DailyContentSavingPercent_ViaDataReductionProxy",
percent_via_data_reduction_proxy);
UMA_HISTOGRAM_PERCENTAGE(
"Net.DailyContentPercent_ViaDataReductionProxy",
(100 * received_length_via_data_reduction_proxy) / received_length);
}
Vulnerability Type: DoS
CWE ID: CWE-416
Summary: Use-after-free vulnerability in the HTML5 Audio implementation in Google Chrome before 27.0.1453.110 allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,326 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index)
{
struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
int i, err = 0;
int free = -1;
mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac);
mutex_lock(&table->mutex);
for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) {
if (free < 0 && !table->refs[i]) {
free = i;
continue;
}
if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) {
/* MAC already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
mlx4_dbg(dev, "Free MAC index is %d\n", free);
if (table->total == table->max) {
/* No free mac entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID);
err = mlx4_set_port_mac_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: In the Linux kernel before 2.6.37, an out of bounds array access happened in drivers/net/mlx4/port.c. When searching for a free entry in either mlx4_register_vlan() or mlx4_register_mac(), and there is no free entry, the loop terminates without updating the local variable free thus causing out of array bounds access.
Commit Message: mlx4_en: Fix out of bounds array access
When searching for a free entry in either mlx4_register_vlan() or
mlx4_register_mac(), and there is no free entry, the loop terminates without
updating the local variable free thus causing out of array bounds access. Fix
this by adding a proper check outside the loop.
Signed-off-by: Eli Cohen <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | High | 169,871 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct mem_size_stats *mss = walk->private;
struct vm_area_struct *vma = mss->vma;
pte_t *pte;
spinlock_t *ptl;
spin_lock(&walk->mm->page_table_lock);
if (pmd_trans_huge(*pmd)) {
if (pmd_trans_splitting(*pmd)) {
spin_unlock(&walk->mm->page_table_lock);
wait_split_huge_page(vma->anon_vma, pmd);
} else {
smaps_pte_entry(*(pte_t *)pmd, addr,
HPAGE_PMD_SIZE, walk);
spin_unlock(&walk->mm->page_table_lock);
mss->anonymous_thp += HPAGE_PMD_SIZE;
return 0;
}
} else {
spin_unlock(&walk->mm->page_table_lock);
}
/*
* The mmap_sem held all the way back in m_start() is what
* keeps khugepaged out of here and from collapsing things
* in here.
*/
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE)
smaps_pte_entry(*pte, addr, PAGE_SIZE, walk);
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: The Linux kernel before 3.3.1, when KVM is used, allows guest OS users to cause a denial of service (host OS crash) by leveraging administrative access to the guest OS, related to the pmd_none_or_clear_bad function and page faults for huge pages.
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]> | Medium | 165,630 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void V8Window::namedPropertyGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
DOMWindow* window = V8Window::toNative(info.Holder());
if (!window)
return;
Frame* frame = window->frame();
if (!frame)
return;
AtomicString propName = toWebCoreAtomicString(name);
Frame* child = frame->tree().scopedChild(propName);
if (child) {
v8SetReturnValueFast(info, child->domWindow(), window);
return;
}
if (!info.Holder()->GetRealNamedProperty(name).IsEmpty())
return;
Document* doc = frame->document();
if (doc && doc->isHTMLDocument()) {
if (toHTMLDocument(doc)->hasNamedItem(propName.impl()) || doc->hasElementWithId(propName.impl())) {
RefPtr<HTMLCollection> items = doc->windowNamedItems(propName);
if (!items->isEmpty()) {
if (items->hasExactlyOneItem()) {
v8SetReturnValueFast(info, items->item(0), window);
return;
}
v8SetReturnValueFast(info, items.release(), window);
return;
}
}
}
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 31.0.1650.48 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving the string values of id attributes.
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | High | 171,155 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define CFormat "/Filter [ /%s ]\n"
#define ObjectsPerImage 14
#define ThrowPDFException(exception,message) \
{ \
if (xref != (MagickOffsetType *) NULL) \
xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \
ThrowWriterException((exception),(message)); \
}
DisableMSCWarning(4310)
static const char
XMPProfile[]=
{
"<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n"
" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
" <xap:ModifyDate>%s</xap:ModifyDate>\n"
" <xap:CreateDate>%s</xap:CreateDate>\n"
" <xap:MetadataDate>%s</xap:MetadataDate>\n"
" <xap:CreatorTool>%s</xap:CreatorTool>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:format>application/pdf</dc:format>\n"
" <dc:title>\n"
" <rdf:Alt>\n"
" <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n"
" </rdf:Alt>\n"
" </dc:title>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n"
" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
" <pdf:Producer>%s</pdf:Producer>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
" <pdfaid:part>3</pdfaid:part>\n"
" <pdfaid:conformance>B</pdfaid:conformance>\n"
" </rdf:Description>\n"
" </rdf:RDF>\n"
"</x:xmpmeta>\n"
"<?xpacket end=\"w\"?>\n"
},
XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };
RestoreMSCWarning
char
basename[MagickPathExtent],
buffer[MagickPathExtent],
*escape,
date[MagickPathExtent],
**labels,
page_geometry[MagickPathExtent],
*url;
CompressionType
compression;
const char
*device,
*option,
*value;
const StringInfo
*profile;
double
pointsize;
GeometryInfo
geometry_info;
Image
*next,
*tile_image;
MagickBooleanType
status;
MagickOffsetType
offset,
scene,
*xref;
MagickSizeType
number_pixels;
MagickStatusType
flags;
PointInfo
delta,
resolution,
scale;
RectangleInfo
geometry,
media_info,
page_info;
register const Quantum
*p;
register unsigned char
*q;
register ssize_t
i,
x;
size_t
channels,
imageListLength,
info_id,
length,
object,
pages_id,
root_id,
text_size,
version;
ssize_t
count,
page_count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Allocate X ref memory.
*/
xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(xref,0,2048UL*sizeof(*xref));
/*
Write Info object.
*/
object=0;
version=3;
if (image_info->compression == JPEG2000Compression)
version=(size_t) MagickMax(version,5);
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
if (next->alpha_trait != UndefinedPixelTrait)
version=(size_t) MagickMax(version,4);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
version=(size_t) MagickMax(version,6);
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
version=(size_t) MagickMax(version,7);
(void) FormatLocaleString(buffer,MagickPathExtent,"%%PDF-1.%.20g \n",(double)
version);
(void) WriteBlobString(image,buffer);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
(void) WriteBlobByte(image,'%');
(void) WriteBlobByte(image,0xe2);
(void) WriteBlobByte(image,0xe3);
(void) WriteBlobByte(image,0xcf);
(void) WriteBlobByte(image,0xd3);
(void) WriteBlobByte(image,'\n');
}
/*
Write Catalog object.
*/
xref[object++]=TellBlob(image);
root_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") != 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n",
(double) object+1);
else
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/Metadata %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n",
(double) object+2);
}
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Catalog");
option=GetImageOption(image_info,"pdf:page-direction");
if ((option != (const char *) NULL) &&
(LocaleCompare(option,"right-to-left") == 0))
(void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n");
(void) WriteBlobString(image,"\n");
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
GetPathComponent(image->filename,BasePath,basename);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
char
create_date[MagickPathExtent],
modify_date[MagickPathExtent],
timestamp[MagickPathExtent],
*url,
xmp_profile[MagickPathExtent];
/*
Write XMP object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Subtype /XML\n");
*modify_date='\0';
value=GetImageProperty(image,"date:modify",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(modify_date,value,MagickPathExtent);
*create_date='\0';
value=GetImageProperty(image,"date:create",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(create_date,value,MagickPathExtent);
(void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);
url=(char *) MagickAuthoritativeURL;
escape=EscapeParenthesis(basename);
i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,
XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);
escape=DestroyString(escape);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g\n",
(double) i);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Metadata\n");
(void) WriteBlobString(image,">>\nstream\n");
(void) WriteBlobString(image,xmp_profile);
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
}
/*
Write Pages object.
*/
xref[object++]=TellBlob(image);
pages_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Pages\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Kids [ %.20g 0 R ",
(double) object+1);
(void) WriteBlobString(image,buffer);
count=(ssize_t) (pages_id+ObjectsPerImage+1);
page_count=1;
if (image_info->adjoin != MagickFalse)
{
Image
*kid_image;
/*
Predict page object id's.
*/
kid_image=image;
for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)
{
page_count++;
profile=GetImageProfile(kid_image,"icc");
if (profile != (StringInfo *) NULL)
count+=2;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 R ",(double)
count);
(void) WriteBlobString(image,buffer);
kid_image=GetNextImageInList(kid_image);
}
xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,
sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) WriteBlobString(image,"]\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Count %.20g\n",(double)
page_count);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
scene=0;
imageListLength=GetImageListLength(image);
do
{
MagickBooleanType
has_icc_profile;
profile=GetImageProfile(image,"icc");
has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if ((SetImageMonochrome(image,exception) == MagickFalse) ||
(image->alpha_trait != UndefinedPixelTrait))
compression=RLECompression;
break;
}
#if !defined(MAGICKCORE_JPEG_DELEGATE)
case JPEGCompression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
case JPEG2000Compression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_ZLIB_DELEGATE)
case ZipCompression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
image->filename);
break;
}
#endif
case LZWCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* LZW compression is forbidden */
break;
}
case NoCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* ASCII 85 compression is forbidden */
break;
}
default:
break;
}
if (compression == JPEG2000Compression)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Scale relative to dots-per-inch.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
resolution.x=image->resolution.x;
resolution.y=image->resolution.y;
if ((resolution.x == 0.0) || (resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image->units == PixelsPerCentimeterResolution)
{
resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
}
SetGeometry(image,&geometry);
(void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g",
(double) image->columns,(double) image->rows);
if (image_info->page != (char *) NULL)
(void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);
else
if ((image->page.width != 0) && (image->page.height != 0))
(void) FormatLocaleString(page_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
else
if ((image->gravity != UndefinedGravity) &&
(LocaleCompare(image_info->magick,"PDF") == 0))
(void) CopyMagickString(page_geometry,PSPageGeometry,
MagickPathExtent);
(void) ConcatenateMagickString(page_geometry,">",MagickPathExtent);
(void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
scale.x=(double) (geometry.width*delta.x)/resolution.x;
geometry.width=(size_t) floor(scale.x+0.5);
scale.y=(double) (geometry.height*delta.y)/resolution.y;
geometry.height=(size_t) floor(scale.y+0.5);
(void) ParseAbsoluteGeometry(page_geometry,&media_info);
(void) ParseGravityGeometry(image,page_geometry,&page_info,exception);
if (image->gravity != UndefinedGravity)
{
geometry.x=(-page_info.x);
geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
}
pointsize=12.0;
if (image_info->pointsize != 0.0)
pointsize=image_info->pointsize;
text_size=0;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
text_size=(size_t) (MultilineCensus(value)*pointsize+12);
(void) text_size;
/*
Write Page object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Page\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Parent %.20g 0 R\n",
(double) pages_id);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Resources <<\n");
labels=(char **) NULL;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
labels=StringToList(value);
if (labels != (char **) NULL)
{
(void) FormatLocaleString(buffer,MagickPathExtent,
"/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+4);
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MagickPathExtent,
"/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+5);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ProcSet %.20g 0 R >>\n",
(double) object+3);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Contents %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Thumb %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 10 : 8));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Contents object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
(void) WriteBlobString(image,"q\n");
if (labels != (char **) NULL)
for (i=0; labels[i] != (char *) NULL; i++)
{
(void) WriteBlobString(image,"BT\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/F%.20g %g Tf\n",
(double) image->scene,pointsize);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g Td\n",
(double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+
12));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"(%s) Tj\n",
labels[i]);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"ET\n");
labels[i]=DestroyString(labels[i]);
}
(void) FormatLocaleString(buffer,MagickPathExtent,
"%g 0 0 %g %.20g %.20g cm\n",scale.x,scale.y,(double) geometry.x,
(double) geometry.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Im%.20g Do\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"Q\n");
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Procset object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MagickPathExtent);
else
if ((compression == FaxCompression) || (compression == Group4Compression))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MagickPathExtent);
else
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ]\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Font object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (labels != (char **) NULL)
{
(void) WriteBlobString(image,"/Type /Font\n");
(void) WriteBlobString(image,"/Subtype /Type1\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /F%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/BaseFont /Helvetica\n");
(void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n");
labels=(char **) RelinquishMagickMemory(labels);
}
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write XObject object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Im%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) image->columns,(double) image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double)
image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n",
(double) object+2);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
if (image->alpha_trait != UndefinedPixelTrait)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/SMask %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 9 : 7));
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
if ((compression == FaxCompression) || (compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,image,exception);
break;
}
(void) Huffman2DEncodeImage(image_info,image,image,exception);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p))));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runoffset encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
if (image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelBlack(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));
Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));
Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlack(image,p)));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
ThrowPDFException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Colorspace object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
device="DeviceRGB";
channels=0;
if (image->colorspace == CMYKColorspace)
{
device="DeviceCMYK";
channels=4;
}
else
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse)))
{
device="DeviceGray";
channels=1;
}
else
if ((image->storage_class == DirectClass) ||
(image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
{
device="DeviceRGB";
channels=3;
}
profile=GetImageProfile(image,"icc");
if ((profile == (StringInfo *) NULL) || (channels == 0))
{
if (channels != 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/%s\n",device);
else
(void) FormatLocaleString(buffer,MagickPathExtent,
"[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors-
1,(double) object+3);
(void) WriteBlobString(image,buffer);
}
else
{
const unsigned char
*p;
/*
Write ICC profile.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"[/ICCBased %.20g 0 R]\n",(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"<<\n/N %.20g\n"
"/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n"
"stream\n",(double) channels,(double) object+1,device);
(void) WriteBlobString(image,buffer);
offset=TellBlob(image);
Ascii85Initialize(image);
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
Ascii85Encode(image,(unsigned char) *p++);
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"endstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Thumb object.
*/
SetGeometry(image,&geometry);
(void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);
if (tile_image == (Image *) NULL)
return(MagickFalse);
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) tile_image->columns,(double) tile_image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double)
tile_image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double)
tile_image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n",
(double) object-(has_icc_profile != MagickFalse ? 3 : 1));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(tile_image,exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,tile_image,
exception);
break;
}
(void) Huffman2DEncodeImage(image_info,image,tile_image,exception);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(
tile_image,p)));
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p))));
p+=GetPixelChannels(tile_image);
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((tile_image->storage_class == DirectClass) ||
(tile_image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));
if (tile_image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(tile_image,p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(tile_image,p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(tile_image,p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlack(tile_image,p)));
p+=GetPixelChannels(tile_image);
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(tile_image,p);
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,(unsigned char)
GetPixelIndex(tile_image,p));
p+=GetPixelChannels(image);
}
}
Ascii85Flush(image);
break;
}
}
}
tile_image=DestroyImage(tile_image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == FaxCompression) || (compression == Group4Compression))
(void) WriteBlobString(image,">>\n");
else
{
/*
Write Colormap object.
*/
if (compression == NoCompression)
(void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
if (compression == NoCompression)
Ascii85Initialize(image);
for (i=0; i < (ssize_t) image->colors; i++)
{
if (compression == NoCompression)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].red)));
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].green)));
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].blue)));
continue;
}
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].red)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].green)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].blue)));
}
if (compression == NoCompression)
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write softmask object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (image->alpha_trait == UndefinedPixelTrait)
(void) WriteBlobString(image,">>\n");
else
{
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Ma%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",
(double) image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",
(double) image->rows);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/ColorSpace /DeviceGray\n");
(void) FormatLocaleString(buffer,MagickPathExtent,
"/BitsPerComponent %d\n",(compression == FaxCompression) ||
(compression == Group4Compression) ? 1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
image=DestroyImage(image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));
p+=GetPixelChannels(image);
}
}
Ascii85Flush(image);
break;
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
/*
Write Metadata object.
*/
xref[object++]=TellBlob(image);
info_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") == 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n",
EscapeParenthesis(basename));
else
{
wchar_t
*utf16;
utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);
if (utf16 != (wchar_t *) NULL)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff");
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) length; i++)
(void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);
(void) FormatLocaleString(buffer,MagickPathExtent,")\n");
utf16=(wchar_t *) RelinquishMagickMemory(utf16);
}
}
(void) WriteBlobString(image,buffer);
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) FormatLocaleString(date,MagickPathExtent,"D:%04d%02d%02d%02d%02d%02d",
local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,
local_time.tm_hour,local_time.tm_min,local_time.tm_sec);
(void) FormatLocaleString(buffer,MagickPathExtent,"/CreationDate (%s)\n",
date);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ModDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
url=(char *) MagickAuthoritativeURL;
escape=EscapeParenthesis(url);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Producer (%s)\n",escape);
escape=DestroyString(escape);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Xref object.
*/
offset=TellBlob(image)-xref[0]+
(LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10;
(void) WriteBlobString(image,"xref\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"0 %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"0000000000 65535 f \n");
for (i=0; i < (ssize_t) object; i++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%010lu 00000 n \n",
(unsigned long) xref[i]);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"trailer\n");
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Size %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Info %.20g 0 R\n",(double)
info_id);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Root %.20g 0 R\n",(double)
root_id);
(void) WriteBlobString(image,buffer);
(void) SignatureImage(image,exception);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ID [<%s> <%s>]\n",
GetImageProperty(image,"signature",exception),
GetImageProperty(image,"signature",exception));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"startxref\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"%%EOF\n");
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
(void) CloseBlob(image);
return(MagickTrue);
}
Vulnerability Type:
CWE ID: CWE-399
Summary: In ImageMagick before 7.0.8-25 and GraphicsMagick through 1.3.31, several memory leaks exist in WritePDFImage in coders/pdf.c.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1454 | Medium | 169,728 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: omx_vdec::~omx_vdec()
{
m_pmem_info = NULL;
struct v4l2_decoder_cmd dec;
DEBUG_PRINT_HIGH("In OMX vdec Destructor");
if (m_pipe_in) close(m_pipe_in);
if (m_pipe_out) close(m_pipe_out);
m_pipe_in = -1;
m_pipe_out = -1;
DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit");
if (msg_thread_created)
pthread_join(msg_thread_id,NULL);
DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit");
dec.cmd = V4L2_DEC_CMD_STOP;
if (drv_ctx.video_driver_fd >=0 ) {
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec))
DEBUG_PRINT_ERROR("STOP Command failed");
}
if (async_thread_created)
pthread_join(async_thread_id,NULL);
unsubscribe_to_events(drv_ctx.video_driver_fd);
close(drv_ctx.video_driver_fd);
pthread_mutex_destroy(&m_lock);
pthread_mutex_destroy(&c_lock);
sem_destroy(&m_cmd_lock);
if (perf_flag) {
DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME");
dec_time.end();
}
DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd);
}
Vulnerability Type: +Priv
CWE ID:
Summary: Use-after-free vulnerability in the mm-video-v4l2 vdec component in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01 allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27890802.
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
| High | 173,754 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void BrowserContextDestroyer::RenderProcessHostDestroyed(
content::RenderProcessHost* host) {
DCHECK_GT(pending_hosts_, 0U);
if (--pending_hosts_ != 0) {
return;
}
//// static
if (content::RenderProcessHost::run_renderer_in_process()) {
FinishDestroyContext();
} else {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&BrowserContextDestroyer::FinishDestroyContext,
base::Unretained(this)));
}
}
Vulnerability Type:
CWE ID: CWE-20
Summary: A malicious webview could install long-lived unload handlers that re-use an incognito BrowserContext that is queued for destruction in versions of Oxide before 1.18.3.
Commit Message: | Medium | 165,421 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int hwahc_security_create(struct hwahc *hwahc)
{
int result;
struct wusbhc *wusbhc = &hwahc->wusbhc;
struct usb_device *usb_dev = hwahc->wa.usb_dev;
struct device *dev = &usb_dev->dev;
struct usb_security_descriptor *secd;
struct usb_encryption_descriptor *etd;
void *itr, *top;
size_t itr_size, needed, bytes;
u8 index;
char buf[64];
/* Find the host's security descriptors in the config descr bundle */
index = (usb_dev->actconfig - usb_dev->config) /
sizeof(usb_dev->config[0]);
itr = usb_dev->rawdescriptors[index];
itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength);
top = itr + itr_size;
result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index],
le16_to_cpu(usb_dev->actconfig->desc.wTotalLength),
USB_DT_SECURITY, (void **) &secd);
if (result == -1) {
dev_warn(dev, "BUG? WUSB host has no security descriptors\n");
return 0;
}
needed = sizeof(*secd);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptor header (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
needed = le16_to_cpu(secd->wTotalLength);
if (top - (void *)secd < needed) {
dev_err(dev, "BUG? Not enough data to process security "
"descriptors (%zu bytes left vs %zu needed)\n",
top - (void *) secd, needed);
return 0;
}
/* Walk over the sec descriptors and store CCM1's on wusbhc */
itr = (void *) secd + sizeof(*secd);
top = (void *) secd + le16_to_cpu(secd->wTotalLength);
index = 0;
bytes = 0;
while (itr < top) {
etd = itr;
if (top - itr < sizeof(*etd)) {
dev_err(dev, "BUG: bad host security descriptor; "
"not enough data (%zu vs %zu left)\n",
top - itr, sizeof(*etd));
break;
}
if (etd->bLength < sizeof(*etd)) {
dev_err(dev, "BUG: bad host encryption descriptor; "
"descriptor is too short "
"(%zu vs %zu needed)\n",
(size_t)etd->bLength, sizeof(*etd));
break;
}
itr += etd->bLength;
bytes += snprintf(buf + bytes, sizeof(buf) - bytes,
"%s (0x%02x) ",
wusb_et_name(etd->bEncryptionType),
etd->bEncryptionValue);
wusbhc->ccm1_etd = etd;
}
dev_info(dev, "supported encryption types: %s\n", buf);
if (wusbhc->ccm1_etd == NULL) {
dev_err(dev, "E: host doesn't support CCM-1 crypto\n");
return 0;
}
/* Pretty print what we support */
return 0;
}
Vulnerability Type:
CWE ID: CWE-400
Summary: An issue was discovered in the Linux kernel before 4.19.9. The USB subsystem mishandles size checks during the reading of an extra descriptor, related to __usb_get_extra_descriptor in drivers/usb/core/usb.c.
Commit Message: USB: check usb_get_extra_descriptor for proper size
When reading an extra descriptor, we need to properly check the minimum
and maximum size allowed, to prevent from invalid data being sent by a
device.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Co-developed-by: Linus Torvalds <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]> | High | 168,961 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void *arm_coherent_dma_alloc(struct device *dev, size_t size,
dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
void *memory;
if (dma_alloc_from_coherent(dev, size, handle, &memory))
return memory;
return __dma_alloc(dev, size, handle, gfp, prot, true,
__builtin_return_address(0));
}
Vulnerability Type: +Priv
CWE ID: CWE-264
Summary: arch/arm/mm/dma-mapping.c in the Linux kernel before 3.13 on ARM platforms, as used in Android before 2016-08-05 on Nexus 5 and 7 (2013) devices, does not prevent executable DMA mappings, which might allow local users to gain privileges via a crafted application, aka Android internal bug 28803642 and Qualcomm internal bug CR642735.
Commit Message: ARM: dma-mapping: don't allow DMA mappings to be marked executable
DMA mapping permissions were being derived from pgprot_kernel directly
without using PAGE_KERNEL. This causes them to be marked with executable
permission, which is not what we want. Fix this.
Signed-off-by: Russell King <[email protected]> | High | 167,577 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: SecureProxyChecker::SecureProxyChecker(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: url_loader_factory_(std::move(url_loader_factory)) {}
Vulnerability Type:
CWE ID: CWE-416
Summary: A use after free in PDFium in Google Chrome prior to 57.0.2987.98 for Mac, Windows, and Linux and 57.0.2987.108 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted PDF file.
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649} | Medium | 172,423 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg)
{
__be32 *p;
RESERVE_SPACE(4+NFS4_STATEID_SIZE+4);
WRITE32(OP_OPEN_DOWNGRADE);
WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->open_flags);
return 0;
}
Vulnerability Type: DoS
CWE ID:
Summary: The encode_share_access function in fs/nfs/nfs4xdr.c in the Linux kernel before 2.6.29 allows local users to cause a denial of service (BUG and system crash) by using the mknod system call with a pathname on an NFSv4 filesystem.
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]> | Medium | 165,713 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void VirtualAuthenticator::AddRegistration(
blink::test::mojom::RegisteredKeyPtr registration,
AddRegistrationCallback callback) {
if (registration->application_parameter.size() != device::kRpIdHashLength) {
std::move(callback).Run(false);
return;
}
bool success = false;
std::tie(std::ignore, success) = state_->registrations.emplace(
std::move(registration->key_handle),
::device::VirtualFidoDevice::RegistrationData(
crypto::ECPrivateKey::CreateFromPrivateKeyInfo(
registration->private_key),
registration->application_parameter, registration->counter));
std::move(callback).Run(success);
}
Vulnerability Type: Dir. Trav.
CWE ID: CWE-22
Summary: Google Chrome before 50.0.2661.102 on Android mishandles / (slash) and (backslash) characters, which allows attackers to conduct directory traversal attacks via a file: URL, related to net/base/escape.cc and net/base/filename_util.cc.
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586657} | Medium | 172,273 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: device_has_capability (NMDevice *self, NMDeviceCapabilities caps)
{
{
static guint32 devcount = 0;
NMDevicePrivate *priv;
g_return_if_fail (NM_IS_DEVICE (self));
priv = NM_DEVICE_GET_PRIVATE (self);
g_return_if_fail (priv->path == NULL);
priv->path = g_strdup_printf ("/org/freedesktop/NetworkManager/Devices/%d", devcount++);
_LOGI (LOGD_DEVICE, "exported as %s", priv->path);
nm_dbus_manager_register_object (nm_dbus_manager_get (), priv->path, self);
}
const char *
nm_device_get_path (NMDevice *self)
{
g_return_val_if_fail (self != NULL, NULL);
return NM_DEVICE_GET_PRIVATE (self)->path;
}
const char *
nm_device_get_udi (NMDevice *self)
{
g_return_val_if_fail (self != NULL, NULL);
return NM_DEVICE_GET_PRIVATE (self)->udi;
}
const char *
nm_device_get_iface (NMDevice *self)
{
g_return_val_if_fail (NM_IS_DEVICE (self), 0);
return NM_DEVICE_GET_PRIVATE (self)->iface;
}
int
nm_device_get_ifindex (NMDevice *self)
{
g_return_val_if_fail (self != NULL, 0);
return NM_DEVICE_GET_PRIVATE (self)->ifindex;
}
gboolean
nm_device_is_software (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
return priv->is_software;
}
const char *
nm_device_get_ip_iface (NMDevice *self)
{
NMDevicePrivate *priv;
g_return_val_if_fail (self != NULL, NULL);
priv = NM_DEVICE_GET_PRIVATE (self);
/* If it's not set, default to iface */
return priv->ip_iface ? priv->ip_iface : priv->iface;
}
int
nm_device_get_ip_ifindex (NMDevice *self)
{
NMDevicePrivate *priv;
g_return_val_if_fail (self != NULL, 0);
priv = NM_DEVICE_GET_PRIVATE (self);
/* If it's not set, default to iface */
return priv->ip_iface ? priv->ip_ifindex : priv->ifindex;
}
void
nm_device_set_ip_iface (NMDevice *self, const char *iface)
{
NMDevicePrivate *priv;
char *old_ip_iface;
g_return_if_fail (NM_IS_DEVICE (self));
priv = NM_DEVICE_GET_PRIVATE (self);
if (!g_strcmp0 (iface, priv->ip_iface))
return;
old_ip_iface = priv->ip_iface;
priv->ip_ifindex = 0;
priv->ip_iface = g_strdup (iface);
if (priv->ip_iface) {
priv->ip_ifindex = nm_platform_link_get_ifindex (priv->ip_iface);
if (priv->ip_ifindex > 0) {
if (nm_platform_check_support_user_ipv6ll ())
nm_platform_link_set_user_ipv6ll_enabled (priv->ip_ifindex, TRUE);
if (!nm_platform_link_is_up (priv->ip_ifindex))
nm_platform_link_set_up (priv->ip_ifindex);
} else {
/* Device IP interface must always be a kernel network interface */
_LOGW (LOGD_HW, "failed to look up interface index");
}
}
/* We don't care about any saved values from the old iface */
g_hash_table_remove_all (priv->ip6_saved_properties);
/* Emit change notification */
if (g_strcmp0 (old_ip_iface, priv->ip_iface))
g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE);
g_free (old_ip_iface);
}
static gboolean
get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid)
{
NMLinkType link_type;
const guint8 *hwaddr = NULL;
size_t hwaddr_len = 0;
int ifindex;
gboolean success;
/* If we get here, we *must* have a kernel netdev, which implies an ifindex */
ifindex = nm_device_get_ip_ifindex (self);
g_assert (ifindex);
link_type = nm_platform_link_get_type (ifindex);
g_return_val_if_fail (link_type > NM_LINK_TYPE_UNKNOWN, 0);
hwaddr = nm_platform_link_get_address (ifindex, &hwaddr_len);
if (!hwaddr_len)
return FALSE;
success = nm_utils_get_ipv6_interface_identifier (link_type,
hwaddr,
hwaddr_len,
out_iid);
if (!success) {
_LOGW (LOGD_HW, "failed to generate interface identifier "
"for link type %u hwaddr_len %zu", link_type, hwaddr_len);
}
return success;
}
static gboolean
nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid)
{
return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid);
}
const char *
nm_device_get_driver (NMDevice *self)
{
g_return_val_if_fail (self != NULL, NULL);
return NM_DEVICE_GET_PRIVATE (self)->driver;
}
const char *
nm_device_get_driver_version (NMDevice *self)
{
g_return_val_if_fail (self != NULL, NULL);
return NM_DEVICE_GET_PRIVATE (self)->driver_version;
}
NMDeviceType
nm_device_get_device_type (NMDevice *self)
{
g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN);
return NM_DEVICE_GET_PRIVATE (self)->type;
}
/**
* nm_device_get_priority():
* @self: the #NMDevice
*
* Returns: the device's routing priority. Lower numbers means a "better"
* device, eg higher priority.
*/
int
nm_device_get_priority (NMDevice *self)
{
g_return_val_if_fail (NM_IS_DEVICE (self), 1000);
/* Device 'priority' is used for the default route-metric and is based on
* the device type. The settings ipv4.route-metric and ipv6.route-metric
* can overwrite this default.
*
* Currently for both IPv4 and IPv6 we use the same default values.
*
* The route-metric is used for the metric of the routes of device.
* This also applies to the default route. Therefore it affects also
* which device is the "best".
*
* For comparison, note that iproute2 by default adds IPv4 routes with
* metric 0, and IPv6 routes with metric 1024. The latter is the IPv6
* "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6).
* In kernel, the full uint32_t range is available for route
* metrics (except for IPv6, where 0 means 1024).
*/
switch (nm_device_get_device_type (self)) {
/* 50 is reserved for VPN (NM_VPN_ROUTE_METRIC_DEFAULT) */
case NM_DEVICE_TYPE_ETHERNET:
return 100;
case NM_DEVICE_TYPE_INFINIBAND:
return 150;
case NM_DEVICE_TYPE_ADSL:
return 200;
case NM_DEVICE_TYPE_WIMAX:
return 250;
case NM_DEVICE_TYPE_BOND:
return 300;
case NM_DEVICE_TYPE_TEAM:
return 350;
case NM_DEVICE_TYPE_VLAN:
return 400;
case NM_DEVICE_TYPE_BRIDGE:
return 425;
case NM_DEVICE_TYPE_MODEM:
return 450;
case NM_DEVICE_TYPE_BT:
return 550;
case NM_DEVICE_TYPE_WIFI:
return 600;
case NM_DEVICE_TYPE_OLPC_MESH:
return 650;
case NM_DEVICE_TYPE_GENERIC:
return 950;
case NM_DEVICE_TYPE_UNKNOWN:
return 10000;
case NM_DEVICE_TYPE_UNUSED1:
case NM_DEVICE_TYPE_UNUSED2:
/* omit default: to get compiler warning about missing switch cases */
break;
}
return 11000;
}
guint32
nm_device_get_ip4_route_metric (NMDevice *self)
{
NMConnection *connection;
gint64 route_metric = -1;
g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32);
connection = nm_device_get_connection (self);
if (connection)
route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip4_config (connection));
return route_metric >= 0 ? route_metric : nm_device_get_priority (self);
}
guint32
nm_device_get_ip6_route_metric (NMDevice *self)
{
NMConnection *connection;
gint64 route_metric = -1;
g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32);
connection = nm_device_get_connection (self);
if (connection)
route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip6_config (connection));
return route_metric >= 0 ? route_metric : nm_device_get_priority (self);
}
const NMPlatformIP4Route *
nm_device_get_ip4_default_route (NMDevice *self, gboolean *out_is_assumed)
{
NMDevicePrivate *priv;
g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
priv = NM_DEVICE_GET_PRIVATE (self);
if (out_is_assumed)
*out_is_assumed = priv->default_route.v4_is_assumed;
return priv->default_route.v4_has ? &priv->default_route.v4 : NULL;
}
const NMPlatformIP6Route *
nm_device_get_ip6_default_route (NMDevice *self, gboolean *out_is_assumed)
{
NMDevicePrivate *priv;
g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
priv = NM_DEVICE_GET_PRIVATE (self);
if (out_is_assumed)
*out_is_assumed = priv->default_route.v6_is_assumed;
return priv->default_route.v6_has ? &priv->default_route.v6 : NULL;
}
const char *
nm_device_get_type_desc (NMDevice *self)
{
g_return_val_if_fail (self != NULL, NULL);
return NM_DEVICE_GET_PRIVATE (self)->type_desc;
}
gboolean
nm_device_has_carrier (NMDevice *self)
{
return NM_DEVICE_GET_PRIVATE (self)->carrier;
}
NMActRequest *
nm_device_get_act_request (NMDevice *self)
{
g_return_val_if_fail (self != NULL, NULL);
return NM_DEVICE_GET_PRIVATE (self)->act_request;
}
NMConnection *
nm_device_get_connection (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
return priv->act_request ? nm_act_request_get_connection (priv->act_request) : NULL;
}
RfKillType
nm_device_get_rfkill_type (NMDevice *self)
{
g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
return NM_DEVICE_GET_PRIVATE (self)->rfkill_type;
}
static const char *
nm_device_get_physical_port_id (NMDevice *self)
{
return NM_DEVICE_GET_PRIVATE (self)->physical_port_id;
}
/***********************************************************/
static gboolean
nm_device_uses_generated_assumed_connection (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
if ( priv->act_request
&& nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) {
connection = nm_act_request_get_connection (priv->act_request);
if ( connection
&& nm_settings_connection_get_nm_generated_assumed (NM_SETTINGS_CONNECTION (connection)))
return TRUE;
}
return FALSE;
}
gboolean
nm_device_uses_assumed_connection (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if ( priv->act_request
&& nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request)))
return TRUE;
return FALSE;
}
static SlaveInfo *
find_slave_info (NMDevice *self, NMDevice *slave)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
SlaveInfo *info;
GSList *iter;
for (iter = priv->slaves; iter; iter = g_slist_next (iter)) {
info = iter->data;
if (info->slave == slave)
return info;
}
return NULL;
}
static void
free_slave_info (SlaveInfo *info)
{
g_signal_handler_disconnect (info->slave, info->watch_id);
g_clear_object (&info->slave);
memset (info, 0, sizeof (*info));
g_free (info);
}
/**
* nm_device_enslave_slave:
* @self: the master device
* @slave: the slave device to enslave
* @connection: (allow-none): the slave device's connection
*
* If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
* etc) then this function enslaves @slave.
*
* Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave
* other devices.
*/
static gboolean
nm_device_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection)
{
SlaveInfo *info;
gboolean success = FALSE;
gboolean configure;
g_return_val_if_fail (self != NULL, FALSE);
g_return_val_if_fail (slave != NULL, FALSE);
g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE);
info = find_slave_info (self, slave);
if (!info)
return FALSE;
if (info->enslaved)
success = TRUE;
else {
configure = (info->configure && connection != NULL);
if (configure)
g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE);
success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure);
info->enslaved = success;
}
nm_device_slave_notify_enslave (info->slave, success);
/* Ensure the device's hardware address is up-to-date; it often changes
* when slaves change.
*/
nm_device_update_hw_address (self);
/* Restart IP configuration if we're waiting for slaves. Do this
* after updating the hardware address as IP config may need the
* new address.
*/
if (success) {
if (NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT)
nm_device_activate_stage3_ip4_start (self);
if (NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT)
nm_device_activate_stage3_ip6_start (self);
}
return success;
}
/**
* nm_device_release_one_slave:
* @self: the master device
* @slave: the slave device to release
* @configure: whether @self needs to actually release @slave
* @reason: the state change reason for the @slave
*
* If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
* etc) then this function releases the previously enslaved @slave and/or
* updates the state of @self and @slave to reflect its release.
*
* Returns: %TRUE on success, %FALSE on failure, if this device cannot enslave
* other devices, or if @slave was never enslaved.
*/
static gboolean
nm_device_release_one_slave (NMDevice *self, NMDevice *slave, gboolean configure, NMDeviceStateReason reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
SlaveInfo *info;
gboolean success = FALSE;
g_return_val_if_fail (slave != NULL, FALSE);
g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL, FALSE);
info = find_slave_info (self, slave);
if (!info)
return FALSE;
priv->slaves = g_slist_remove (priv->slaves, info);
if (info->enslaved) {
success = NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure);
/* The release_slave() implementation logs success/failure (in the
* correct device-specific log domain), so we don't have to do anything.
*/
}
if (!configure) {
g_warn_if_fail (reason == NM_DEVICE_STATE_REASON_NONE || reason == NM_DEVICE_STATE_REASON_REMOVED);
reason = NM_DEVICE_STATE_REASON_NONE;
} else if (reason == NM_DEVICE_STATE_REASON_NONE) {
g_warn_if_reached ();
reason = NM_DEVICE_STATE_REASON_UNKNOWN;
}
nm_device_slave_notify_release (info->slave, reason);
free_slave_info (info);
/* Ensure the device's hardware address is up-to-date; it often changes
* when slaves change.
*/
nm_device_update_hw_address (self);
return success;
}
static gboolean
is_software_external (NMDevice *self)
{
return nm_device_is_software (self)
&& !nm_device_get_is_nm_owned (self);
}
/**
* nm_device_finish_init:
* @self: the master device
*
* Whatever needs to be done post-initialization, when the device has a DBus
* object name.
*/
void
nm_device_finish_init (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
g_assert (priv->initialized == FALSE);
/* Do not manage externally created software devices until they are IFF_UP */
if ( is_software_external (self)
&& !nm_platform_link_is_up (priv->ifindex)
&& priv->ifindex > 0)
nm_device_set_initial_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE);
if (priv->master)
nm_device_enslave_slave (priv->master, self, NULL);
priv->initialized = TRUE;
}
static void
carrier_changed (NMDevice *self, gboolean carrier)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (!nm_device_get_managed (self))
return;
nm_device_recheck_available_connections (self);
/* ignore-carrier devices ignore all carrier-down events */
if (priv->ignore_carrier && !carrier)
return;
if (priv->is_master) {
/* Bridge/bond/team carrier does not affect its own activation,
* but when carrier comes on, if there are slaves waiting,
* it will restart them.
*/
if (!carrier)
return;
if (nm_device_activate_ip4_state_in_wait (self))
nm_device_activate_stage3_ip4_start (self);
if (nm_device_activate_ip6_state_in_wait (self))
nm_device_activate_stage3_ip6_start (self);
return;
} else if (nm_device_get_enslaved (self) && !carrier) {
/* Slaves don't deactivate when they lose carrier; for
* bonds/teams in particular that would be actively
* counterproductive.
*/
return;
}
if (carrier) {
g_warn_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE);
if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) {
nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED,
NM_DEVICE_STATE_REASON_CARRIER);
} else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) {
/* If the device is already in DISCONNECTED state without a carrier
* (probably because it is tagged for carrier ignore) ensure that
* when the carrier appears, auto connections are rechecked for
* the device.
*/
nm_device_emit_recheck_auto_activate (self);
}
} else {
g_return_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE);
if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) {
if (nm_device_queued_state_peek (self) >= NM_DEVICE_STATE_DISCONNECTED)
nm_device_queued_state_clear (self);
} else {
nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE,
NM_DEVICE_STATE_REASON_CARRIER);
}
}
}
#define LINK_DISCONNECT_DELAY 4
static gboolean
link_disconnect_action_cb (gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
_LOGD (LOGD_DEVICE, "link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id);
priv->carrier_defer_id = 0;
_LOGI (LOGD_DEVICE, "link disconnected (calling deferred action)");
NM_DEVICE_GET_CLASS (self)->carrier_changed (self, FALSE);
return FALSE;
}
static void
link_disconnect_action_cancel (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->carrier_defer_id) {
g_source_remove (priv->carrier_defer_id);
_LOGD (LOGD_DEVICE, "link disconnected (canceling deferred action) (id=%u)", priv->carrier_defer_id);
priv->carrier_defer_id = 0;
}
}
void
nm_device_set_carrier (NMDevice *self, gboolean carrier)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
NMDeviceState state = nm_device_get_state (self);
if (priv->carrier == carrier)
return;
priv->carrier = carrier;
g_object_notify (G_OBJECT (self), NM_DEVICE_CARRIER);
if (priv->carrier) {
_LOGI (LOGD_DEVICE, "link connected");
link_disconnect_action_cancel (self);
klass->carrier_changed (self, TRUE);
if (priv->carrier_wait_id) {
g_source_remove (priv->carrier_wait_id);
priv->carrier_wait_id = 0;
nm_device_remove_pending_action (self, "carrier wait", TRUE);
_carrier_wait_check_queued_act_request (self);
}
} else if (state <= NM_DEVICE_STATE_DISCONNECTED) {
_LOGI (LOGD_DEVICE, "link disconnected");
klass->carrier_changed (self, FALSE);
} else {
_LOGI (LOGD_DEVICE, "link disconnected (deferring action for %d seconds)", LINK_DISCONNECT_DELAY);
priv->carrier_defer_id = g_timeout_add_seconds (LINK_DISCONNECT_DELAY,
link_disconnect_action_cb, self);
_LOGD (LOGD_DEVICE, "link disconnected (deferring action for %d seconds) (id=%u)",
LINK_DISCONNECT_DELAY, priv->carrier_defer_id);
}
}
static void
update_for_ip_ifname_change (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
g_hash_table_remove_all (priv->ip6_saved_properties);
if (priv->dhcp4_client) {
if (!nm_device_dhcp4_renew (self, FALSE)) {
nm_device_state_changed (self,
NM_DEVICE_STATE_FAILED,
NM_DEVICE_STATE_REASON_DHCP_FAILED);
return;
}
}
if (priv->dhcp6_client) {
if (!nm_device_dhcp6_renew (self, FALSE)) {
nm_device_state_changed (self,
NM_DEVICE_STATE_FAILED,
NM_DEVICE_STATE_REASON_DHCP_FAILED);
return;
}
}
if (priv->rdisc) {
/* FIXME: todo */
}
if (priv->dnsmasq_manager) {
/* FIXME: todo */
}
}
static void
device_set_master (NMDevice *self, int ifindex)
{
NMDevice *master;
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
master = nm_manager_get_device_by_ifindex (nm_manager_get (), ifindex);
if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave) {
g_clear_object (&priv->master);
priv->master = g_object_ref (master);
nm_device_master_add_slave (master, self, FALSE);
} else if (master) {
_LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring",
nm_device_get_iface (master));
} else {
_LOGW (LOGD_DEVICE, "enslaved to unknown device %d %s",
ifindex,
nm_platform_link_get_name (ifindex));
}
}
static void
device_link_changed (NMDevice *self, NMPlatformLink *info)
{
NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMUtilsIPv6IfaceId token_iid;
gboolean ip_ifname_changed = FALSE;
if (info->udi && g_strcmp0 (info->udi, priv->udi)) {
/* Update UDI to what udev gives us */
g_free (priv->udi);
priv->udi = g_strdup (info->udi);
g_object_notify (G_OBJECT (self), NM_DEVICE_UDI);
}
/* Update MTU if it has changed. */
if (priv->mtu != info->mtu) {
priv->mtu = info->mtu;
g_object_notify (G_OBJECT (self), NM_DEVICE_MTU);
}
if (info->name[0] && strcmp (priv->iface, info->name) != 0) {
_LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'",
priv->ifindex, priv->iface, info->name);
g_free (priv->iface);
priv->iface = g_strdup (info->name);
/* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */
ip_ifname_changed = !priv->ip_iface;
g_object_notify (G_OBJECT (self), NM_DEVICE_IFACE);
if (ip_ifname_changed)
g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE);
/* Re-match available connections against the new interface name */
nm_device_recheck_available_connections (self);
/* Let any connections that use the new interface name have a chance
* to auto-activate on the device.
*/
nm_device_emit_recheck_auto_activate (self);
}
/* Update slave status for external changes */
if (priv->enslaved && info->master != nm_device_get_ifindex (priv->master))
nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_NONE);
if (info->master && !priv->enslaved) {
device_set_master (self, info->master);
if (priv->master)
nm_device_enslave_slave (priv->master, self, NULL);
}
if (priv->rdisc && nm_platform_link_get_ipv6_token (priv->ifindex, &token_iid)) {
_LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface);
if (nm_rdisc_set_iid (priv->rdisc, token_iid))
nm_rdisc_start (priv->rdisc);
}
if (klass->link_changed)
klass->link_changed (self, info);
/* Update DHCP, etc, if needed */
if (ip_ifname_changed)
update_for_ip_ifname_change (self);
if (priv->up != info->up) {
priv->up = info->up;
/* Manage externally-created software interfaces only when they are IFF_UP */
g_assert (priv->ifindex > 0);
if (is_software_external (self)) {
gboolean external_down = nm_device_get_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN);
if (external_down && info->up) {
if (nm_device_get_state (self) < NM_DEVICE_STATE_DISCONNECTED) {
/* Ensure the assume check is queued before any queued state changes
* from the transition to UNAVAILABLE.
*/
nm_device_queue_recheck_assume (self);
/* Resetting the EXTERNAL_DOWN flag may change the device's state
* to UNAVAILABLE. To ensure that the state change doesn't touch
* the device before assumption occurs, pass
* NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED as the reason.
*/
nm_device_set_unmanaged (self,
NM_UNMANAGED_EXTERNAL_DOWN,
FALSE,
NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
} else {
/* Don't trigger a state change; if the device is in a
* state higher than UNAVAILABLE, it is already IFF_UP
* or an explicit activation request was received.
*/
priv->unmanaged_flags &= ~NM_UNMANAGED_EXTERNAL_DOWN;
}
} else if (!external_down && !info->up && nm_device_get_state (self) <= NM_DEVICE_STATE_DISCONNECTED) {
/* If the device is already disconnected and is set !IFF_UP,
* unmanage it.
*/
nm_device_set_unmanaged (self,
NM_UNMANAGED_EXTERNAL_DOWN,
TRUE,
NM_DEVICE_STATE_REASON_USER_REQUESTED);
}
}
}
}
static void
device_ip_link_changed (NMDevice *self, NMPlatformLink *info)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (info->name[0] && g_strcmp0 (priv->ip_iface, info->name)) {
_LOGI (LOGD_DEVICE, "interface index %d renamed ip_iface (%d) from '%s' to '%s'",
priv->ifindex, nm_device_get_ip_ifindex (self),
priv->ip_iface, info->name);
g_free (priv->ip_iface);
priv->ip_iface = g_strdup (info->name);
g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE);
update_for_ip_ifname_change (self);
}
}
static void
link_changed_cb (NMPlatform *platform,
int ifindex,
NMPlatformLink *info,
NMPlatformSignalChangeType change_type,
NMPlatformReason reason,
NMDevice *self)
{
if (change_type != NM_PLATFORM_SIGNAL_CHANGED)
return;
/* We don't filter by 'reason' because we are interested in *all* link
* changes. For example a call to nm_platform_link_set_up() may result
* in an internal carrier change (i.e. we ask the kernel to set IFF_UP
* and it results in also setting IFF_LOWER_UP.
*/
if (ifindex == nm_device_get_ifindex (self))
device_link_changed (self, info);
else if (ifindex == nm_device_get_ip_ifindex (self))
device_ip_link_changed (self, info);
}
static void
link_changed (NMDevice *self, NMPlatformLink *info)
{
/* Update carrier from link event if applicable. */
if ( device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)
&& !device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER))
nm_device_set_carrier (self, info->connected);
}
/**
* nm_device_notify_component_added():
* @self: the #NMDevice
* @component: the component being added by a plugin
*
* Called by the manager to notify the device that a new component has
* been found. The device implementation should return %TRUE if it
* wishes to claim the component, or %FALSE if it cannot.
*
* Returns: %TRUE to claim the component, %FALSE if the component cannot be
* claimed.
*/
gboolean
nm_device_notify_component_added (NMDevice *self, GObject *component)
{
if (NM_DEVICE_GET_CLASS (self)->component_added)
return NM_DEVICE_GET_CLASS (self)->component_added (self, component);
return FALSE;
}
/**
* nm_device_owns_iface():
* @self: the #NMDevice
* @iface: an interface name
*
* Called by the manager to ask if the device or any of its components owns
* @iface. For example, a WWAN implementation would return %TRUE for an
* ethernet interface name that was owned by the WWAN device's modem component,
* because that ethernet interface is controlled by the WWAN device and cannot
* be used independently of the WWAN device.
*
* Returns: %TRUE if @self or it's components owns the interface name,
* %FALSE if not
*/
gboolean
nm_device_owns_iface (NMDevice *self, const char *iface)
{
if (NM_DEVICE_GET_CLASS (self)->owns_iface)
return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface);
return FALSE;
}
NMConnection *
nm_device_new_default_connection (NMDevice *self)
{
if (NM_DEVICE_GET_CLASS (self)->new_default_connection)
return NM_DEVICE_GET_CLASS (self)->new_default_connection (self);
return NULL;
}
static void
slave_state_changed (NMDevice *slave,
NMDeviceState slave_new_state,
NMDeviceState slave_old_state,
NMDeviceStateReason reason,
NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
gboolean release = FALSE;
_LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)",
nm_device_get_iface (slave),
slave_old_state,
state_to_string (slave_old_state),
slave_new_state,
state_to_string (slave_new_state));
/* Don't try to enslave slaves until the master is ready */
if (priv->state < NM_DEVICE_STATE_CONFIG)
return;
if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG)
nm_device_enslave_slave (self, slave, nm_device_get_connection (slave));
else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED)
release = TRUE;
else if ( slave_new_state <= NM_DEVICE_STATE_DISCONNECTED
&& slave_old_state > NM_DEVICE_STATE_DISCONNECTED) {
/* Catch failures due to unavailable or unmanaged */
release = TRUE;
}
if (release) {
nm_device_release_one_slave (self, slave, TRUE, reason);
/* Bridge/bond/team interfaces are left up until manually deactivated */
if (priv->slaves == NULL && priv->state == NM_DEVICE_STATE_ACTIVATED)
_LOGD (LOGD_DEVICE, "last slave removed; remaining activated");
}
}
/**
* nm_device_master_add_slave:
* @self: the master device
* @slave: the slave device to enslave
* @configure: pass %TRUE if the slave should be configured by the master, or
* %FALSE if it is already configured outside NetworkManager
*
* If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
* etc) then this function adds @slave to the slave list for later enslavement.
*
* Returns: %TRUE on success, %FALSE on failure
*/
static gboolean
nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
SlaveInfo *info;
g_return_val_if_fail (self != NULL, FALSE);
g_return_val_if_fail (slave != NULL, FALSE);
g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE);
if (configure)
g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE);
if (!find_slave_info (self, slave)) {
info = g_malloc0 (sizeof (SlaveInfo));
info->slave = g_object_ref (slave);
info->configure = configure;
info->watch_id = g_signal_connect (slave, "state-changed",
G_CALLBACK (slave_state_changed), self);
priv->slaves = g_slist_append (priv->slaves, info);
}
nm_device_queue_recheck_assume (self);
return TRUE;
}
/**
* nm_device_master_get_slaves:
* @self: the master device
*
* Returns: any slaves of which @self is the master. Caller owns returned list.
*/
GSList *
nm_device_master_get_slaves (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
GSList *slaves = NULL, *iter;
for (iter = priv->slaves; iter; iter = g_slist_next (iter))
slaves = g_slist_prepend (slaves, ((SlaveInfo *) iter->data)->slave);
return slaves;
}
/**
* nm_device_master_get_slave_by_ifindex:
* @self: the master device
* @ifindex: the slave's interface index
*
* Returns: the slave with the given @ifindex of which @self is the master,
* or %NULL if no device with @ifindex is a slave of @self.
*/
NMDevice *
nm_device_master_get_slave_by_ifindex (NMDevice *self, int ifindex)
{
GSList *iter;
for (iter = NM_DEVICE_GET_PRIVATE (self)->slaves; iter; iter = g_slist_next (iter)) {
SlaveInfo *info = iter->data;
if (nm_device_get_ip_ifindex (info->slave) == ifindex)
return info->slave;
}
return NULL;
}
/**
* nm_device_master_check_slave_physical_port:
* @self: the master device
* @slave: a slave device
* @log_domain: domain to log a warning in
*
* Checks if @self already has a slave with the same #NMDevice:physical-port-id
* as @slave, and logs a warning if so.
*/
void
nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave,
guint64 log_domain)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
const char *slave_physical_port_id, *existing_physical_port_id;
SlaveInfo *info;
GSList *iter;
slave_physical_port_id = nm_device_get_physical_port_id (slave);
if (!slave_physical_port_id)
return;
for (iter = priv->slaves; iter; iter = iter->next) {
info = iter->data;
if (info->slave == slave)
continue;
existing_physical_port_id = nm_device_get_physical_port_id (info->slave);
if (!g_strcmp0 (slave_physical_port_id, existing_physical_port_id)) {
_LOGW (log_domain, "slave %s shares a physical port with existing slave %s",
nm_device_get_ip_iface (slave),
nm_device_get_ip_iface (info->slave));
/* Since this function will get called for every slave, we only have
* to warn about the first match we find; if there are other matches
* later in the list, we will have already warned about them matching
* @existing earlier.
*/
return;
}
}
}
/* release all slaves */
static void
nm_device_master_release_slaves (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMDeviceStateReason reason;
/* Don't release the slaves if this connection doesn't belong to NM. */
if (nm_device_uses_generated_assumed_connection (self))
return;
reason = priv->state_reason;
if (priv->state == NM_DEVICE_STATE_FAILED)
reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED;
while (priv->slaves) {
SlaveInfo *info = priv->slaves->data;
nm_device_release_one_slave (self, info->slave, TRUE, reason);
}
}
/**
* nm_device_get_master:
* @self: the device
*
* If @self has been enslaved by another device, this returns that
* device. Otherwise it returns %NULL. (In particular, note that if
* @self is in the process of activating as a slave, but has not yet
* been enslaved by its master, this will return %NULL.)
*
* Returns: (transfer none): @self's master, or %NULL
*/
NMDevice *
nm_device_get_master (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->enslaved)
return priv->master;
else
return NULL;
}
/**
* nm_device_slave_notify_enslave:
* @self: the slave device
* @success: whether the enslaving operation succeeded
*
* Notifies a slave that either it has been enslaved, or else its master tried
* to enslave it and failed.
*/
static void
nm_device_slave_notify_enslave (NMDevice *self, gboolean success)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection = nm_device_get_connection (self);
gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG);
g_assert (priv->master);
if (!priv->enslaved) {
if (success) {
if (activating) {
_LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation",
nm_connection_get_id (connection));
} else
_LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master));
priv->enslaved = TRUE;
g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER);
} else if (activating) {
_LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved",
nm_connection_get_id (connection));
}
}
if (activating) {
priv->ip4_state = IP_DONE;
priv->ip6_state = IP_DONE;
nm_device_queue_state (self,
success ? NM_DEVICE_STATE_SECONDARIES : NM_DEVICE_STATE_FAILED,
NM_DEVICE_STATE_REASON_NONE);
} else
nm_device_queue_recheck_assume (self);
}
/**
* nm_device_slave_notify_release:
* @self: the slave device
* @reason: the reason associated with the state change
*
* Notifies a slave that it has been released, and why.
*/
static void
nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection = nm_device_get_connection (self);
NMDeviceState new_state;
const char *master_status;
if ( reason != NM_DEVICE_STATE_REASON_NONE
&& priv->state > NM_DEVICE_STATE_DISCONNECTED
&& priv->state <= NM_DEVICE_STATE_ACTIVATED) {
if (reason == NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED) {
new_state = NM_DEVICE_STATE_FAILED;
master_status = "failed";
} else if (reason == NM_DEVICE_STATE_REASON_USER_REQUESTED) {
new_state = NM_DEVICE_STATE_DEACTIVATING;
master_status = "deactivated by user request";
} else {
new_state = NM_DEVICE_STATE_DISCONNECTED;
master_status = "deactivated";
}
_LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s",
nm_connection_get_id (connection),
master_status);
nm_device_queue_state (self, new_state, reason);
} else if (priv->master)
_LOGI (LOGD_DEVICE, "released from master %s", nm_device_get_iface (priv->master));
else
_LOGD (LOGD_DEVICE, "released from master%s", priv->enslaved ? "" : " (was not enslaved)");
if (priv->enslaved) {
priv->enslaved = FALSE;
g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER);
}
}
/**
* nm_device_get_enslaved:
* @self: the #NMDevice
*
* Returns: %TRUE if the device is enslaved to a master device (eg bridge or
* bond or team), %FALSE if not
*/
gboolean
nm_device_get_enslaved (NMDevice *self)
{
return NM_DEVICE_GET_PRIVATE (self)->enslaved;
}
/**
* nm_device_removed:
* @self: the #NMDevice
*
* Called by the manager when the device was removed. Releases the device from
* the master in case it's enslaved.
*/
void
nm_device_removed (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->enslaved)
nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_REMOVED);
}
static gboolean
is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->carrier || priv->ignore_carrier)
return TRUE;
if (NM_FLAGS_HAS (flags, NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER))
return TRUE;
return FALSE;
}
/**
* nm_device_is_available:
* @self: the #NMDevice
* @flags: additional flags to influence the check. Flags have the
* meaning to increase the availability of a device.
*
* Checks if @self would currently be capable of activating a
* connection. In particular, it checks that the device is ready (eg,
* is not missing firmware), that it has carrier (if necessary), and
* that any necessary external software (eg, ModemManager,
* wpa_supplicant) is available.
*
* @self can only be in a state higher than
* %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns
* %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED
* when it is available.)
*
* Returns: %TRUE or %FALSE
*/
gboolean
nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->firmware_missing)
return FALSE;
return NM_DEVICE_GET_CLASS (self)->is_available (self, flags);
}
gboolean
nm_device_get_enabled (NMDevice *self)
{
g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
if (NM_DEVICE_GET_CLASS (self)->get_enabled)
return NM_DEVICE_GET_CLASS (self)->get_enabled (self);
return TRUE;
}
void
nm_device_set_enabled (NMDevice *self, gboolean enabled)
{
g_return_if_fail (NM_IS_DEVICE (self));
if (NM_DEVICE_GET_CLASS (self)->set_enabled)
NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled);
}
/**
* nm_device_get_autoconnect:
* @self: the #NMDevice
*
* Returns: %TRUE if the device allows autoconnect connections, or %FALSE if the
* device is explicitly blocking all autoconnect connections. Does not take
* into account transient conditions like companion devices that may wish to
* block the device.
*/
gboolean
nm_device_get_autoconnect (NMDevice *self)
{
g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
return NM_DEVICE_GET_PRIVATE (self)->autoconnect;
}
static void
nm_device_set_autoconnect (NMDevice *self, gboolean autoconnect)
{
NMDevicePrivate *priv;
g_return_if_fail (NM_IS_DEVICE (self));
priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->autoconnect == autoconnect)
return;
if (autoconnect) {
/* Default-unmanaged devices never autoconnect */
if (!nm_device_get_default_unmanaged (self)) {
priv->autoconnect = TRUE;
g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT);
}
} else {
priv->autoconnect = FALSE;
g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT);
}
}
static gboolean
autoconnect_allowed_accumulator (GSignalInvocationHint *ihint,
GValue *return_accu,
const GValue *handler_return, gpointer data)
{
if (!g_value_get_boolean (handler_return))
g_value_set_boolean (return_accu, FALSE);
return TRUE;
}
/**
* nm_device_autoconnect_allowed:
* @self: the #NMDevice
*
* Returns: %TRUE if the device can be auto-connected immediately, taking
* transient conditions into account (like companion devices that may wish to
* block autoconnect for a time).
*/
gboolean
nm_device_autoconnect_allowed (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
GValue instance = G_VALUE_INIT;
GValue retval = G_VALUE_INIT;
if (priv->state < NM_DEVICE_STATE_DISCONNECTED || !priv->autoconnect)
return FALSE;
/* The 'autoconnect-allowed' signal is emitted on a device to allow
* other listeners to block autoconnect on the device if they wish.
* This is mainly used by the OLPC Mesh devices to block autoconnect
* on their companion WiFi device as they share radio resources and
* cannot be connected at the same time.
*/
g_value_init (&instance, G_TYPE_OBJECT);
g_value_set_object (&instance, self);
g_value_init (&retval, G_TYPE_BOOLEAN);
if (priv->autoconnect)
g_value_set_boolean (&retval, TRUE);
else
g_value_set_boolean (&retval, FALSE);
/* Use g_signal_emitv() rather than g_signal_emit() to avoid the return
* value being changed if no handlers are connected */
g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval);
g_value_unset (&instance);
return g_value_get_boolean (&retval);
}
static gboolean
can_auto_connect (NMDevice *self,
NMConnection *connection,
char **specific_object)
{
NMSettingConnection *s_con;
s_con = nm_connection_get_setting_connection (connection);
if (!nm_setting_connection_get_autoconnect (s_con))
return FALSE;
return nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_NONE, NULL);
}
/**
* nm_device_can_auto_connect:
* @self: an #NMDevice
* @connection: a #NMConnection
* @specific_object: (out) (transfer full): on output, the path of an
* object associated with the returned connection, to be passed to
* nm_manager_activate_connection(), or %NULL.
*
* Checks if @connection can be auto-activated on @self right now.
* This requires, at a minimum, that the connection be compatible with
* @self, and that it have the #NMSettingConnection:autoconnect property
* set, and that the device allow auto connections. Some devices impose
* additional requirements. (Eg, a Wi-Fi connection can only be activated
* if its SSID was seen in the last scan.)
*
* Returns: %TRUE, if the @connection can be auto-activated.
**/
gboolean
nm_device_can_auto_connect (NMDevice *self,
NMConnection *connection,
char **specific_object)
{
g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);
g_return_val_if_fail (specific_object && !*specific_object, FALSE);
if (nm_device_autoconnect_allowed (self))
return NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, connection, specific_object);
return FALSE;
}
static gboolean
device_has_config (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
/* Check for IP configuration. */
if (priv->ip4_config && nm_ip4_config_get_num_addresses (priv->ip4_config))
return TRUE;
if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config))
return TRUE;
/* The existence of a software device is good enough. */
if (nm_device_is_software (self))
return TRUE;
/* Slaves are also configured by definition */
if (nm_platform_link_get_master (priv->ifindex) > 0)
return TRUE;
return FALSE;
}
/**
* nm_device_master_update_slave_connection:
* @self: the master #NMDevice
* @slave: the slave #NMDevice
* @connection: the #NMConnection to update with the slave settings
* @GError: (out): error description
*
* Reads the slave configuration for @slave and updates @connection with those
* properties. This invokes a virtual function on the master device @self.
*
* Returns: %TRUE if the configuration was read and @connection updated,
* %FALSE on failure.
*/
gboolean
nm_device_master_update_slave_connection (NMDevice *self,
NMDevice *slave,
NMConnection *connection,
GError **error)
{
NMDeviceClass *klass;
gboolean success;
g_return_val_if_fail (self, FALSE);
g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
g_return_val_if_fail (slave, FALSE);
g_return_val_if_fail (connection, FALSE);
g_return_val_if_fail (!error || !*error, FALSE);
g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE);
g_return_val_if_fail (nm_device_get_iface (self), FALSE);
klass = NM_DEVICE_GET_CLASS (self);
if (klass->master_update_slave_connection) {
success = klass->master_update_slave_connection (self, slave, connection, error);
g_return_val_if_fail (!error || (success && !*error) || *error, success);
return success;
}
g_set_error (error,
NM_DEVICE_ERROR,
NM_DEVICE_ERROR_FAILED,
"master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)",
nm_device_get_iface (self), nm_device_get_iface (slave));
return FALSE;
}
NMConnection *
nm_device_generate_connection (NMDevice *self, NMDevice *master)
{
NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
const char *ifname = nm_device_get_iface (self);
NMConnection *connection;
NMSetting *s_con;
NMSetting *s_ip4;
NMSetting *s_ip6;
gs_free char *uuid = NULL;
const char *ip4_method, *ip6_method;
GError *error = NULL;
/* If update_connection() is not implemented, just fail. */
if (!klass->update_connection)
return NULL;
/* Return NULL if device is unconfigured. */
if (!device_has_config (self)) {
_LOGD (LOGD_DEVICE, "device has no existing configuration");
return NULL;
}
connection = nm_simple_connection_new ();
s_con = nm_setting_connection_new ();
uuid = nm_utils_uuid_generate ();
g_object_set (s_con,
NM_SETTING_CONNECTION_UUID, uuid,
NM_SETTING_CONNECTION_ID, ifname,
NM_SETTING_CONNECTION_AUTOCONNECT, FALSE,
NM_SETTING_CONNECTION_INTERFACE_NAME, ifname,
NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL),
NULL);
if (klass->connection_type)
g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type, NULL);
nm_connection_add_setting (connection, s_con);
/* If the device is a slave, update various slave settings */
if (master) {
if (!nm_device_master_update_slave_connection (master,
self,
connection,
&error))
{
_LOGE (LOGD_DEVICE, "master device '%s' failed to update slave connection: %s",
nm_device_get_iface (master), error ? error->message : "(unknown error)");
g_error_free (error);
g_object_unref (connection);
return NULL;
}
} else {
/* Only regular and master devices get IP configuration; slaves do not */
s_ip4 = nm_ip4_config_create_setting (priv->ip4_config);
nm_connection_add_setting (connection, s_ip4);
s_ip6 = nm_ip6_config_create_setting (priv->ip6_config);
nm_connection_add_setting (connection, s_ip6);
}
klass->update_connection (self, connection);
/* Check the connection in case of update_connection() bug. */
if (!nm_connection_verify (connection, &error)) {
_LOGE (LOGD_DEVICE, "Generated connection does not verify: %s", error->message);
g_clear_error (&error);
g_object_unref (connection);
return NULL;
}
/* Ignore the connection if it has no IP configuration,
* no slave configuration, and is not a master interface.
*/
ip4_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
ip6_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
if ( g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0
&& g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0
&& !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con))
&& !priv->slaves) {
_LOGD (LOGD_DEVICE, "ignoring generated connection (no IP and not in master-slave relationship)");
g_object_unref (connection);
connection = NULL;
}
return connection;
}
gboolean
nm_device_complete_connection (NMDevice *self,
NMConnection *connection,
const char *specific_object,
const GSList *existing_connections,
GError **error)
{
gboolean success = FALSE;
g_return_val_if_fail (self != NULL, FALSE);
g_return_val_if_fail (connection != NULL, FALSE);
if (!NM_DEVICE_GET_CLASS (self)->complete_connection) {
g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION,
"Device class %s had no complete_connection method",
G_OBJECT_TYPE_NAME (self));
return FALSE;
}
success = NM_DEVICE_GET_CLASS (self)->complete_connection (self,
connection,
specific_object,
existing_connections,
error);
if (success)
success = nm_connection_verify (connection, error);
return success;
}
static gboolean
check_connection_compatible (NMDevice *self, NMConnection *connection)
{
NMSettingConnection *s_con;
const char *config_iface, *device_iface;
s_con = nm_connection_get_setting_connection (connection);
g_assert (s_con);
config_iface = nm_setting_connection_get_interface_name (s_con);
device_iface = nm_device_get_iface (self);
if (config_iface && strcmp (config_iface, device_iface) != 0)
return FALSE;
return TRUE;
}
/**
* nm_device_check_connection_compatible:
* @self: an #NMDevice
* @connection: an #NMConnection
*
* Checks if @connection could potentially be activated on @self.
* This means only that @self has the proper capabilities, and that
* @connection is not locked to some other device. It does not
* necessarily mean that @connection could be activated on @self
* right now. (Eg, it might refer to a Wi-Fi network that is not
* currently available.)
*
* Returns: #TRUE if @connection could potentially be activated on
* @self.
*/
gboolean
nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection)
{
g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);
return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection);
}
/**
* nm_device_can_assume_connections:
* @self: #NMDevice instance
*
* This is a convenience function to determine whether connection assumption
* is available for this device.
*
* Returns: %TRUE if the device is capable of assuming connections, %FALSE if not
*/
static gboolean
nm_device_can_assume_connections (NMDevice *self)
{
return !!NM_DEVICE_GET_CLASS (self)->update_connection;
}
/**
* nm_device_can_assume_active_connection:
* @self: #NMDevice instance
*
* This is a convenience function to determine whether the device's active
* connection can be assumed if NetworkManager restarts. This method returns
* %TRUE if and only if the device can assume connections, and the device has
* an active connection, and that active connection can be assumed.
*
* Returns: %TRUE if the device's active connection can be assumed, or %FALSE
* if there is no active connection or the active connection cannot be
* assumed.
*/
gboolean
nm_device_can_assume_active_connection (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
const char *method;
const char *assumable_ip6_methods[] = {
NM_SETTING_IP6_CONFIG_METHOD_IGNORE,
NM_SETTING_IP6_CONFIG_METHOD_AUTO,
NM_SETTING_IP6_CONFIG_METHOD_DHCP,
NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL,
NM_SETTING_IP6_CONFIG_METHOD_MANUAL,
NULL
};
const char *assumable_ip4_methods[] = {
NM_SETTING_IP4_CONFIG_METHOD_DISABLED,
NM_SETTING_IP6_CONFIG_METHOD_AUTO,
NM_SETTING_IP6_CONFIG_METHOD_MANUAL,
NULL
};
if (!nm_device_can_assume_connections (self))
return FALSE;
connection = nm_device_get_connection (self);
if (!connection)
return FALSE;
/* Can't assume connections that aren't yet configured
* FIXME: what about bridges/bonds waiting for slaves?
*/
if (priv->state < NM_DEVICE_STATE_IP_CONFIG)
return FALSE;
if (priv->ip4_state != IP_DONE && priv->ip6_state != IP_DONE)
return FALSE;
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
if (!_nm_utils_string_in_list (method, assumable_ip6_methods))
return FALSE;
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
if (!_nm_utils_string_in_list (method, assumable_ip4_methods))
return FALSE;
return TRUE;
}
static gboolean
nm_device_emit_recheck_assume (gpointer self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
priv->recheck_assume_id = 0;
if (!nm_device_get_act_request (self)) {
_LOGD (LOGD_DEVICE, "emit RECHECK_ASSUME signal");
g_signal_emit (self, signals[RECHECK_ASSUME], 0);
}
return G_SOURCE_REMOVE;
}
void
nm_device_queue_recheck_assume (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (nm_device_can_assume_connections (self) && !priv->recheck_assume_id)
priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self);
}
void
nm_device_emit_recheck_auto_activate (NMDevice *self)
{
g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0);
}
static void
dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
switch (status) {
case NM_DNSMASQ_STATUS_DEAD:
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED);
break;
default:
break;
}
}
static void
activation_source_clear (NMDevice *self, gboolean remove_source, int family)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
guint *act_source_id;
gpointer *act_source_func;
if (family == AF_INET6) {
act_source_id = &priv->act_source6_id;
act_source_func = &priv->act_source6_func;
} else {
act_source_id = &priv->act_source_id;
act_source_func = &priv->act_source_func;
}
if (*act_source_id) {
if (remove_source)
g_source_remove (*act_source_id);
*act_source_id = 0;
*act_source_func = NULL;
}
}
static void
activation_source_schedule (NMDevice *self, GSourceFunc func, int family)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
guint *act_source_id;
gpointer *act_source_func;
if (family == AF_INET6) {
act_source_id = &priv->act_source6_id;
act_source_func = &priv->act_source6_func;
} else {
act_source_id = &priv->act_source_id;
act_source_func = &priv->act_source_func;
}
if (*act_source_id)
_LOGE (LOGD_DEVICE, "activation stage already scheduled");
/* Don't bother rescheduling the same function that's about to
* run anyway. Fixes issues with crappy wireless drivers sending
* streams of associate events before NM has had a chance to process
* the first one.
*/
if (!*act_source_id || (*act_source_func != func)) {
activation_source_clear (self, TRUE, family);
*act_source_id = g_idle_add (func, self);
*act_source_func = func;
}
}
static gboolean
get_ip_config_may_fail (NMDevice *self, int family)
{
NMConnection *connection;
NMSettingIPConfig *s_ip = NULL;
g_return_val_if_fail (self != NULL, TRUE);
connection = nm_device_get_connection (self);
g_assert (connection);
/* Fail the connection if the failed IP method is required to complete */
switch (family) {
case AF_INET:
s_ip = nm_connection_get_setting_ip4_config (connection);
break;
case AF_INET6:
s_ip = nm_connection_get_setting_ip6_config (connection);
break;
default:
g_assert_not_reached ();
}
return nm_setting_ip_config_get_may_fail (s_ip);
}
static void
master_ready_cb (NMActiveConnection *active,
GParamSpec *pspec,
NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMActiveConnection *master;
g_assert (priv->state == NM_DEVICE_STATE_PREPARE);
/* Notify a master device that it has a new slave */
g_assert (nm_active_connection_get_master_ready (active));
master = nm_active_connection_get_master (active);
priv->master = g_object_ref (nm_active_connection_get_device (master));
nm_device_master_add_slave (priv->master,
self,
nm_active_connection_get_assumed (active) ? FALSE : TRUE);
_LOGD (LOGD_DEVICE, "master connection ready; master device %s",
nm_device_get_iface (priv->master));
if (priv->master_ready_id) {
g_signal_handler_disconnect (active, priv->master_ready_id);
priv->master_ready_id = 0;
}
nm_device_activate_schedule_stage2_device_config (self);
}
static NMActStageReturn
act_stage1_prepare (NMDevice *self, NMDeviceStateReason *reason)
{
return NM_ACT_STAGE_RETURN_SUCCESS;
}
/*
* nm_device_activate_stage1_device_prepare
*
* Prepare for device activation
*
*/
static gboolean
nm_device_activate_stage1_device_prepare (gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS;
NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request);
/* Clear the activation source ID now that this stage has run */
activation_source_clear (self, FALSE, 0);
priv->ip4_state = priv->ip6_state = IP_NONE;
/* Notify the new ActiveConnection along with the state change */
g_object_notify (G_OBJECT (self), NM_DEVICE_ACTIVE_CONNECTION);
_LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) started...");
nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE);
/* Assumed connections were already set up outside NetworkManager */
if (!nm_active_connection_get_assumed (active)) {
ret = NM_DEVICE_GET_CLASS (self)->act_stage1_prepare (self, &reason);
if (ret == NM_ACT_STAGE_RETURN_POSTPONE) {
goto out;
} else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
goto out;
}
g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
}
if (nm_active_connection_get_master (active)) {
/* If the master connection is ready for slaves, attach ourselves */
if (nm_active_connection_get_master_ready (active))
master_ready_cb (active, NULL, self);
else {
_LOGD (LOGD_DEVICE, "waiting for master connection to become ready");
/* Attach a signal handler and wait for the master connection to begin activating */
g_assert (priv->master_ready_id == 0);
priv->master_ready_id = g_signal_connect (active,
"notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY,
(GCallback) master_ready_cb,
self);
/* Postpone */
}
} else
nm_device_activate_schedule_stage2_device_config (self);
out:
_LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) complete.");
return FALSE;
}
/*
* nm_device_activate_schedule_stage1_device_prepare
*
* Prepare a device for activation
*
*/
void
nm_device_activate_schedule_stage1_device_prepare (NMDevice *self)
{
NMDevicePrivate *priv;
g_return_if_fail (NM_IS_DEVICE (self));
priv = NM_DEVICE_GET_PRIVATE (self);
g_return_if_fail (priv->act_request);
activation_source_schedule (self, nm_device_activate_stage1_device_prepare, 0);
_LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) scheduled...");
}
static NMActStageReturn
act_stage2_config (NMDevice *self, NMDeviceStateReason *reason)
{
/* Nothing to do */
return NM_ACT_STAGE_RETURN_SUCCESS;
}
/*
* nm_device_activate_stage2_device_config
*
* Determine device parameters and set those on the device, ie
* for wireless devices, set SSID, keys, etc.
*
*/
static gboolean
nm_device_activate_stage2_device_config (gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMActStageReturn ret;
NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
gboolean no_firmware = FALSE;
NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request);
GSList *iter;
/* Clear the activation source ID now that this stage has run */
activation_source_clear (self, FALSE, 0);
_LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) starting...");
nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE);
/* Assumed connections were already set up outside NetworkManager */
if (!nm_active_connection_get_assumed (active)) {
if (!nm_device_bring_up (self, FALSE, &no_firmware)) {
if (no_firmware)
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_FIRMWARE_MISSING);
else
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
goto out;
}
ret = NM_DEVICE_GET_CLASS (self)->act_stage2_config (self, &reason);
if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
goto out;
else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
goto out;
}
g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
}
/* If we have slaves that aren't yet enslaved, do that now */
for (iter = priv->slaves; iter; iter = g_slist_next (iter)) {
SlaveInfo *info = iter->data;
NMDeviceState slave_state = nm_device_get_state (info->slave);
if (slave_state == NM_DEVICE_STATE_IP_CONFIG)
nm_device_enslave_slave (self, info->slave, nm_device_get_connection (info->slave));
else if ( nm_device_uses_generated_assumed_connection (self)
&& slave_state <= NM_DEVICE_STATE_DISCONNECTED)
nm_device_queue_recheck_assume (info->slave);
}
_LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) successful.");
nm_device_activate_schedule_stage3_ip_config_start (self);
out:
_LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) complete.");
return FALSE;
}
/*
* nm_device_activate_schedule_stage2_device_config
*
* Schedule setup of the hardware device
*
*/
void
nm_device_activate_schedule_stage2_device_config (NMDevice *self)
{
NMDevicePrivate *priv;
g_return_if_fail (NM_IS_DEVICE (self));
priv = NM_DEVICE_GET_PRIVATE (self);
g_return_if_fail (priv->act_request);
activation_source_schedule (self, nm_device_activate_stage2_device_config, 0);
_LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) scheduled...");
}
/*********************************************/
/* avahi-autoipd stuff */
static void
aipd_timeout_remove (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->aipd_timeout) {
g_source_remove (priv->aipd_timeout);
priv->aipd_timeout = 0;
}
}
static void
aipd_cleanup (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->aipd_watch) {
g_source_remove (priv->aipd_watch);
priv->aipd_watch = 0;
}
if (priv->aipd_pid > 0) {
nm_utils_kill_child_sync (priv->aipd_pid, SIGKILL, LOGD_AUTOIP4, "avahi-autoipd", NULL, 0, 0);
priv->aipd_pid = -1;
}
aipd_timeout_remove (self);
}
static NMIP4Config *
aipd_get_ip4_config (NMDevice *self, guint32 lla)
{
NMIP4Config *config = NULL;
NMPlatformIP4Address address;
NMPlatformIP4Route route;
config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
g_assert (config);
memset (&address, 0, sizeof (address));
address.address = lla;
address.plen = 16;
address.source = NM_IP_CONFIG_SOURCE_IP4LL;
nm_ip4_config_add_address (config, &address);
/* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */
memset (&route, 0, sizeof (route));
route.network = htonl (0xE0000000L);
route.plen = 4;
route.source = NM_IP_CONFIG_SOURCE_IP4LL;
route.metric = nm_device_get_ip4_route_metric (self);
nm_ip4_config_add_route (config, &route);
return config;
}
#define IPV4LL_NETWORK (htonl (0xA9FE0000L))
#define IPV4LL_NETMASK (htonl (0xFFFF0000L))
void
nm_device_handle_autoip4_event (NMDevice *self,
const char *event,
const char *address)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection = NULL;
const char *method;
NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
g_return_if_fail (event != NULL);
if (priv->act_request == NULL)
return;
connection = nm_act_request_get_connection (priv->act_request);
g_assert (connection);
/* Ignore if the connection isn't an AutoIP connection */
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) != 0)
return;
if (strcmp (event, "BIND") == 0) {
guint32 lla;
NMIP4Config *config;
if (inet_pton (AF_INET, address, &lla) <= 0) {
_LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd.", address);
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR);
return;
}
if ((lla & IPV4LL_NETMASK) != IPV4LL_NETWORK) {
_LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd (not link-local).", address);
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR);
return;
}
config = aipd_get_ip4_config (self, lla);
if (config == NULL) {
_LOGE (LOGD_AUTOIP4, "failed to get autoip config");
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
return;
}
if (priv->ip4_state == IP_CONF) {
aipd_timeout_remove (self);
nm_device_activate_schedule_ip4_config_result (self, config);
} else if (priv->ip4_state == IP_DONE) {
if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) {
_LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change.");
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
}
} else
g_assert_not_reached ();
g_object_unref (config);
} else {
_LOGW (LOGD_AUTOIP4, "autoip address %s no longer valid because '%s'.", address, event);
/* The address is gone; terminate the connection or fail activation */
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
}
}
static void
aipd_watch_cb (GPid pid, gint status, gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMDeviceState state;
if (!priv->aipd_watch)
return;
priv->aipd_watch = 0;
if (WIFEXITED (status))
_LOGD (LOGD_AUTOIP4, "avahi-autoipd exited with error code %d", WEXITSTATUS (status));
else if (WIFSTOPPED (status))
_LOGW (LOGD_AUTOIP4, "avahi-autoipd stopped unexpectedly with signal %d", WSTOPSIG (status));
else if (WIFSIGNALED (status))
_LOGW (LOGD_AUTOIP4, "avahi-autoipd died with signal %d", WTERMSIG (status));
else
_LOGW (LOGD_AUTOIP4, "avahi-autoipd died from an unknown cause");
aipd_cleanup (self);
state = nm_device_get_state (self);
if (nm_device_is_activating (self) || (state == NM_DEVICE_STATE_ACTIVATED))
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_FAILED);
}
static gboolean
aipd_timeout_cb (gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->aipd_timeout) {
_LOGI (LOGD_AUTOIP4, "avahi-autoipd timed out.");
priv->aipd_timeout = 0;
aipd_cleanup (self);
if (priv->ip4_state == IP_CONF)
nm_device_activate_schedule_ip4_config_timeout (self);
}
return FALSE;
}
/* default to installed helper, but can be modified for testing */
const char *nm_device_autoipd_helper_path = LIBEXECDIR "/nm-avahi-autoipd.action";
static NMActStageReturn
aipd_start (NMDevice *self, NMDeviceStateReason *reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
const char *argv[6];
char *cmdline;
const char *aipd_binary;
int i = 0;
GError *error = NULL;
aipd_cleanup (self);
/* Find avahi-autoipd */
aipd_binary = nm_utils_find_helper ("avahi-autoipd", NULL, NULL);
if (!aipd_binary) {
_LOGW (LOGD_DEVICE | LOGD_AUTOIP4,
"Activation: Stage 3 of 5 (IP Configure Start) failed"
" to start avahi-autoipd: not found");
*reason = NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED;
return NM_ACT_STAGE_RETURN_FAILURE;
}
argv[i++] = aipd_binary;
argv[i++] = "--script";
argv[i++] = nm_device_autoipd_helper_path;
if (nm_logging_enabled (LOGL_DEBUG, LOGD_AUTOIP4))
argv[i++] = "--debug";
argv[i++] = nm_device_get_ip_iface (self);
argv[i++] = NULL;
cmdline = g_strjoinv (" ", (char **) argv);
_LOGD (LOGD_AUTOIP4, "running: %s", cmdline);
g_free (cmdline);
if (!g_spawn_async ("/", (char **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD,
nm_utils_setpgid, NULL, &(priv->aipd_pid), &error)) {
_LOGW (LOGD_DEVICE | LOGD_AUTOIP4,
"Activation: Stage 3 of 5 (IP Configure Start) failed"
" to start avahi-autoipd: %s",
error && error->message ? error->message : "(unknown)");
g_clear_error (&error);
aipd_cleanup (self);
return NM_ACT_STAGE_RETURN_FAILURE;
}
_LOGI (LOGD_DEVICE | LOGD_AUTOIP4,
"Activation: Stage 3 of 5 (IP Configure Start) started"
" avahi-autoipd...");
/* Monitor the child process so we know when it dies */
priv->aipd_watch = g_child_watch_add (priv->aipd_pid, aipd_watch_cb, self);
/* Start a timeout to bound the address attempt */
priv->aipd_timeout = g_timeout_add_seconds (20, aipd_timeout_cb, self);
return NM_ACT_STAGE_RETURN_POSTPONE;
}
/*********************************************/
static gboolean
_device_get_default_route_from_platform (NMDevice *self, int addr_family, NMPlatformIPRoute *out_route)
{
gboolean success = FALSE;
int ifindex = nm_device_get_ip_ifindex (self);
GArray *routes;
if (addr_family == AF_INET)
routes = nm_platform_ip4_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT);
else
routes = nm_platform_ip6_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT);
if (routes) {
guint route_metric = G_MAXUINT32, m;
const NMPlatformIPRoute *route = NULL, *r;
guint i;
/* if there are several default routes, find the one with the best metric */
for (i = 0; i < routes->len; i++) {
if (addr_family == AF_INET) {
r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i);
m = r->metric;
} else {
r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i);
m = nm_utils_ip6_route_metric_normalize (r->metric);
}
if (!route || m < route_metric) {
route = r;
route_metric = m;
}
}
if (route) {
if (addr_family == AF_INET)
*((NMPlatformIP4Route *) out_route) = *((NMPlatformIP4Route *) route);
else
*((NMPlatformIP6Route *) out_route) = *((NMPlatformIP6Route *) route);
success = TRUE;
}
g_array_free (routes, TRUE);
}
return success;
}
/*********************************************/
static void
ensure_con_ipx_config (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
int ip_ifindex = nm_device_get_ip_ifindex (self);
NMConnection *connection;
g_assert (!!priv->con_ip4_config == !!priv->con_ip6_config);
if (priv->con_ip4_config)
return;
connection = nm_device_get_connection (self);
if (!connection)
return;
priv->con_ip4_config = nm_ip4_config_new (ip_ifindex);
priv->con_ip6_config = nm_ip6_config_new (ip_ifindex);
nm_ip4_config_merge_setting (priv->con_ip4_config,
nm_connection_get_setting_ip4_config (connection),
nm_device_get_ip4_route_metric (self));
nm_ip6_config_merge_setting (priv->con_ip6_config,
nm_connection_get_setting_ip6_config (connection),
nm_device_get_ip6_route_metric (self));
if (nm_device_uses_assumed_connection (self)) {
/* For assumed connections ignore all addresses and routes. */
nm_ip4_config_reset_addresses (priv->con_ip4_config);
nm_ip4_config_reset_routes (priv->con_ip4_config);
nm_ip6_config_reset_addresses (priv->con_ip6_config);
nm_ip6_config_reset_routes (priv->con_ip6_config);
}
}
/*********************************************/
/* DHCPv4 stuff */
static void
dhcp4_cleanup (NMDevice *self, gboolean stop, gboolean release)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->dhcp4_client) {
/* Stop any ongoing DHCP transaction on this device */
if (priv->dhcp4_state_sigid) {
g_signal_handler_disconnect (priv->dhcp4_client, priv->dhcp4_state_sigid);
priv->dhcp4_state_sigid = 0;
}
nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE);
if (stop)
nm_dhcp_client_stop (priv->dhcp4_client, release);
g_clear_object (&priv->dhcp4_client);
}
if (priv->dhcp4_config) {
g_clear_object (&priv->dhcp4_config);
g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG);
}
}
static gboolean
ip4_config_merge_and_apply (NMDevice *self,
NMIP4Config *config,
gboolean commit,
NMDeviceStateReason *out_reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
gboolean success;
NMIP4Config *composite;
gboolean has_direct_route;
const guint32 default_route_metric = nm_device_get_ip4_route_metric (self);
guint32 gateway;
/* Merge all the configs into the composite config */
if (config) {
g_clear_object (&priv->dev_ip4_config);
priv->dev_ip4_config = g_object_ref (config);
}
composite = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
ensure_con_ipx_config (self);
if (priv->dev_ip4_config)
nm_ip4_config_merge (composite, priv->dev_ip4_config);
if (priv->vpn4_config)
nm_ip4_config_merge (composite, priv->vpn4_config);
if (priv->ext_ip4_config)
nm_ip4_config_merge (composite, priv->ext_ip4_config);
/* Merge WWAN config *last* to ensure modem-given settings overwrite
* any external stuff set by pppd or other scripts.
*/
if (priv->wwan_ip4_config)
nm_ip4_config_merge (composite, priv->wwan_ip4_config);
/* Merge user overrides into the composite config. For assumed connection,
* con_ip4_config is empty. */
if (priv->con_ip4_config)
nm_ip4_config_merge (composite, priv->con_ip4_config);
connection = nm_device_get_connection (self);
/* Add the default route.
*
* We keep track of the default route of a device in a private field.
* NMDevice needs to know the default route at this point, because the gateway
* might require a direct route (see below).
*
* But also, we don't want to add the default route to priv->ip4_config,
* because the default route from the setting might not be the same that
* NMDefaultRouteManager eventually configures (because the it might
* tweak the effective metric).
*/
/* unless we come to a different conclusion below, we have no default route and
* the route is assumed. */
priv->default_route.v4_has = FALSE;
priv->default_route.v4_is_assumed = TRUE;
if (!commit) {
/* during a non-commit event, we always pickup whatever is configured. */
goto END_ADD_DEFAULT_ROUTE;
}
if (nm_device_uses_assumed_connection (self))
goto END_ADD_DEFAULT_ROUTE;
/* we are about to commit (for a non-assumed connection). Enforce whatever we have
* configured. */
priv->default_route.v4_is_assumed = FALSE;
if ( !connection
|| !nm_default_route_manager_ip4_connection_has_default_route (nm_default_route_manager_get (), connection))
goto END_ADD_DEFAULT_ROUTE;
if (!nm_ip4_config_get_num_addresses (composite)) {
/* without addresses we can have no default route. */
goto END_ADD_DEFAULT_ROUTE;
}
gateway = nm_ip4_config_get_gateway (composite);
if ( !gateway
&& nm_device_get_device_type (self) != NM_DEVICE_TYPE_MODEM)
goto END_ADD_DEFAULT_ROUTE;
has_direct_route = ( gateway == 0
|| nm_ip4_config_get_subnet_for_host (composite, gateway)
|| nm_ip4_config_get_direct_route_for_host (composite, gateway));
priv->default_route.v4_has = TRUE;
memset (&priv->default_route.v4, 0, sizeof (priv->default_route.v4));
priv->default_route.v4.source = NM_IP_CONFIG_SOURCE_USER;
priv->default_route.v4.gateway = gateway;
priv->default_route.v4.metric = default_route_metric;
priv->default_route.v4.mss = nm_ip4_config_get_mss (composite);
if (!has_direct_route) {
NMPlatformIP4Route r = priv->default_route.v4;
/* add a direct route to the gateway */
r.network = gateway;
r.plen = 32;
r.gateway = 0;
nm_ip4_config_add_route (composite, &r);
}
END_ADD_DEFAULT_ROUTE:
if (priv->default_route.v4_is_assumed) {
/* If above does not explicitly assign a default route, we always pick up the
* default route based on what is currently configured.
* That means that even managed connections with never-default, can
* get a default route (if configured externally).
*/
priv->default_route.v4_has = _device_get_default_route_from_platform (self, AF_INET, (NMPlatformIPRoute *) &priv->default_route.v4);
}
/* Allow setting MTU etc */
if (commit) {
if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit)
NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, composite);
}
success = nm_device_set_ip4_config (self, composite, default_route_metric, commit, out_reason);
g_object_unref (composite);
return success;
}
static void
dhcp4_lease_change (NMDevice *self, NMIP4Config *config)
{
NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
g_return_if_fail (config != NULL);
if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) {
_LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change.");
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
} else {
/* Notify dispatcher scripts of new DHCP4 config */
nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE,
nm_device_get_connection (self),
self,
NULL,
NULL,
NULL);
}
}
static void
dhcp4_fail (NMDevice *self, gboolean timeout)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
dhcp4_cleanup (self, TRUE, FALSE);
if (timeout || (priv->ip4_state == IP_CONF))
nm_device_activate_schedule_ip4_config_timeout (self);
else if (priv->ip4_state == IP_DONE)
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
else
g_warn_if_reached ();
}
static void
dhcp4_update_config (NMDevice *self, NMDhcp4Config *config, GHashTable *options)
{
GHashTableIter iter;
const char *key, *value;
/* Update the DHCP4 config object with new DHCP options */
nm_dhcp4_config_reset (config);
g_hash_table_iter_init (&iter, options);
while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value))
nm_dhcp4_config_add_option (config, key, value);
g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG);
}
static void
dhcp4_state_changed (NMDhcpClient *client,
NMDhcpState state,
NMIP4Config *ip4_config,
GHashTable *options,
gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == FALSE);
g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config));
_LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state);
switch (state) {
case NM_DHCP_STATE_BOUND:
if (!ip4_config) {
_LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event.");
nm_device_state_changed (self,
NM_DEVICE_STATE_FAILED,
NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
break;
}
dhcp4_update_config (self, priv->dhcp4_config, options);
if (priv->ip4_state == IP_CONF)
nm_device_activate_schedule_ip4_config_result (self, ip4_config);
else if (priv->ip4_state == IP_DONE)
dhcp4_lease_change (self, ip4_config);
break;
case NM_DHCP_STATE_TIMEOUT:
dhcp4_fail (self, TRUE);
break;
case NM_DHCP_STATE_EXPIRE:
/* Ignore expiry before we even have a lease (NAK, old lease, etc) */
if (priv->ip4_state == IP_CONF)
break;
/* Fall through */
case NM_DHCP_STATE_DONE:
case NM_DHCP_STATE_FAIL:
dhcp4_fail (self, FALSE);
break;
default:
break;
}
}
static NMActStageReturn
dhcp4_start (NMDevice *self,
NMConnection *connection,
NMDeviceStateReason *reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMSettingIPConfig *s_ip4;
const guint8 *hw_addr;
size_t hw_addr_len = 0;
GByteArray *tmp = NULL;
s_ip4 = nm_connection_get_setting_ip4_config (connection);
/* Clear old exported DHCP options */
if (priv->dhcp4_config)
g_object_unref (priv->dhcp4_config);
priv->dhcp4_config = nm_dhcp4_config_new ();
hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len);
if (hw_addr_len) {
tmp = g_byte_array_sized_new (hw_addr_len);
g_byte_array_append (tmp, hw_addr, hw_addr_len);
}
/* Begin DHCP on the interface */
g_warn_if_fail (priv->dhcp4_client == NULL);
priv->dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (),
nm_device_get_ip_iface (self),
nm_device_get_ip_ifindex (self),
tmp,
nm_connection_get_uuid (connection),
nm_device_get_ip4_route_metric (self),
nm_setting_ip_config_get_dhcp_send_hostname (s_ip4),
nm_setting_ip_config_get_dhcp_hostname (s_ip4),
nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4)),
priv->dhcp_timeout,
priv->dhcp_anycast_address,
NULL);
if (tmp)
g_byte_array_free (tmp, TRUE);
if (!priv->dhcp4_client) {
*reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED;
return NM_ACT_STAGE_RETURN_FAILURE;
}
priv->dhcp4_state_sigid = g_signal_connect (priv->dhcp4_client,
NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
G_CALLBACK (dhcp4_state_changed),
self);
nm_device_add_pending_action (self, PENDING_ACTION_DHCP4, TRUE);
/* DHCP devices will be notified by the DHCP manager when stuff happens */
return NM_ACT_STAGE_RETURN_POSTPONE;
}
gboolean
nm_device_dhcp4_renew (NMDevice *self, gboolean release)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMActStageReturn ret;
NMDeviceStateReason reason;
NMConnection *connection;
g_return_val_if_fail (priv->dhcp4_client != NULL, FALSE);
_LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested");
/* Terminate old DHCP instance and release the old lease */
dhcp4_cleanup (self, TRUE, release);
connection = nm_device_get_connection (self);
g_assert (connection);
/* Start DHCP again on the interface */
ret = dhcp4_start (self, connection, &reason);
return (ret != NM_ACT_STAGE_RETURN_FAILURE);
}
/*********************************************/
static GHashTable *shared_ips = NULL;
static void
release_shared_ip (gpointer data)
{
g_hash_table_remove (shared_ips, data);
}
static gboolean
reserve_shared_ip (NMDevice *self, NMSettingIPConfig *s_ip4, NMPlatformIP4Address *address)
{
if (G_UNLIKELY (shared_ips == NULL))
shared_ips = g_hash_table_new (g_direct_hash, g_direct_equal);
memset (address, 0, sizeof (*address));
if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) {
/* Use the first user-supplied address */
NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0);
g_assert (user);
nm_ip_address_get_address_binary (user, &address->address);
address->plen = nm_ip_address_get_prefix (user);
} else {
/* Find an unused address in the 10.42.x.x range */
guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */
guint32 count = 0;
while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) {
count += ntohl (0x100);
if (count > ntohl (0xFE00)) {
_LOGE (LOGD_SHARING, "ran out of shared IP addresses!");
return FALSE;
}
}
address->address = start + count;
address->plen = 24;
g_hash_table_insert (shared_ips,
GUINT_TO_POINTER (address->address),
GUINT_TO_POINTER (TRUE));
}
return TRUE;
}
static NMIP4Config *
shared4_new_config (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason)
{
NMIP4Config *config = NULL;
NMPlatformIP4Address address;
g_return_val_if_fail (self != NULL, NULL);
if (!reserve_shared_ip (self, nm_connection_get_setting_ip4_config (connection), &address)) {
*reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE;
return NULL;
}
config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
address.source = NM_IP_CONFIG_SOURCE_SHARED;
nm_ip4_config_add_address (config, &address);
/* Remove the address lock when the object gets disposed */
g_object_set_data_full (G_OBJECT (config), "shared-ip",
GUINT_TO_POINTER (address.address),
release_shared_ip);
return config;
}
/*********************************************/
static gboolean
connection_ip4_method_requires_carrier (NMConnection *connection,
gboolean *out_ip4_enabled)
{
const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
static const char *ip4_carrier_methods[] = {
NM_SETTING_IP4_CONFIG_METHOD_AUTO,
NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL,
NULL
};
if (out_ip4_enabled)
*out_ip4_enabled = !!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED);
return _nm_utils_string_in_list (method, ip4_carrier_methods);
}
static gboolean
connection_ip6_method_requires_carrier (NMConnection *connection,
gboolean *out_ip6_enabled)
{
const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
static const char *ip6_carrier_methods[] = {
NM_SETTING_IP6_CONFIG_METHOD_AUTO,
NM_SETTING_IP6_CONFIG_METHOD_DHCP,
NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL,
NULL
};
if (out_ip6_enabled)
*out_ip6_enabled = !!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE);
return _nm_utils_string_in_list (method, ip6_carrier_methods);
}
static gboolean
connection_requires_carrier (NMConnection *connection)
{
NMSettingIPConfig *s_ip4, *s_ip6;
gboolean ip4_carrier_wanted, ip6_carrier_wanted;
gboolean ip4_used = FALSE, ip6_used = FALSE;
ip4_carrier_wanted = connection_ip4_method_requires_carrier (connection, &ip4_used);
if (ip4_carrier_wanted) {
/* If IPv4 wants a carrier and cannot fail, the whole connection
* requires a carrier regardless of the IPv6 method.
*/
s_ip4 = nm_connection_get_setting_ip4_config (connection);
if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4))
return TRUE;
}
ip6_carrier_wanted = connection_ip6_method_requires_carrier (connection, &ip6_used);
if (ip6_carrier_wanted) {
/* If IPv6 wants a carrier and cannot fail, the whole connection
* requires a carrier regardless of the IPv4 method.
*/
s_ip6 = nm_connection_get_setting_ip6_config (connection);
if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6))
return TRUE;
}
/* If an IP version wants a carrier and and the other IP version isn't
* used, the connection requires carrier since it will just fail without one.
*/
if (ip4_carrier_wanted && !ip6_used)
return TRUE;
if (ip6_carrier_wanted && !ip4_used)
return TRUE;
/* If both want a carrier, the whole connection wants a carrier */
return ip4_carrier_wanted && ip6_carrier_wanted;
}
static gboolean
have_any_ready_slaves (NMDevice *self, const GSList *slaves)
{
const GSList *iter;
/* Any enslaved slave is "ready" in the generic case as it's
* at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2
* properties set up.
*/
for (iter = slaves; iter; iter = g_slist_next (iter)) {
if (nm_device_get_enslaved (iter->data))
return TRUE;
}
return FALSE;
}
static gboolean
ip4_requires_slaves (NMConnection *connection)
{
const char *method;
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
return strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0;
}
static NMActStageReturn
act_stage3_ip4_config_start (NMDevice *self,
NMIP4Config **out_config,
NMDeviceStateReason *reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
const char *method;
GSList *slaves;
gboolean ready_slaves;
g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE);
connection = nm_device_get_connection (self);
g_assert (connection);
if ( connection_ip4_method_requires_carrier (connection, NULL)
&& priv->is_master
&& !priv->carrier) {
_LOGI (LOGD_IP4 | LOGD_DEVICE,
"IPv4 config waiting until carrier is on");
return NM_ACT_STAGE_RETURN_WAIT;
}
if (priv->is_master && ip4_requires_slaves (connection)) {
/* If the master has no ready slaves, and depends on slaves for
* a successful IPv4 attempt, then postpone IPv4 addressing.
*/
slaves = nm_device_master_get_slaves (self);
ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves);
g_slist_free (slaves);
if (ready_slaves == FALSE) {
_LOGI (LOGD_DEVICE | LOGD_IP4,
"IPv4 config waiting until slaves are ready");
return NM_ACT_STAGE_RETURN_WAIT;
}
}
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
/* Start IPv4 addressing based on the method requested */
if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0)
ret = dhcp4_start (self, connection, reason);
else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) == 0)
ret = aipd_start (self, reason);
else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL) == 0) {
/* Use only IPv4 config from the connection data */
*out_config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
g_assert (*out_config);
ret = NM_ACT_STAGE_RETURN_SUCCESS;
} else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) {
*out_config = shared4_new_config (self, connection, reason);
if (*out_config) {
priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self));
ret = NM_ACT_STAGE_RETURN_SUCCESS;
} else
ret = NM_ACT_STAGE_RETURN_FAILURE;
} else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0) {
/* Nothing to do... */
ret = NM_ACT_STAGE_RETURN_STOP;
} else
_LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method);
return ret;
}
/*********************************************/
/* DHCPv6 stuff */
static void
dhcp6_cleanup (NMDevice *self, gboolean stop, gboolean release)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE;
g_clear_object (&priv->dhcp6_ip6_config);
if (priv->dhcp6_client) {
if (priv->dhcp6_state_sigid) {
g_signal_handler_disconnect (priv->dhcp6_client, priv->dhcp6_state_sigid);
priv->dhcp6_state_sigid = 0;
}
if (stop)
nm_dhcp_client_stop (priv->dhcp6_client, release);
g_clear_object (&priv->dhcp6_client);
}
nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE);
if (priv->dhcp6_config) {
g_clear_object (&priv->dhcp6_config);
g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG);
}
}
static gboolean
ip6_config_merge_and_apply (NMDevice *self,
gboolean commit,
NMDeviceStateReason *out_reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
gboolean success;
NMIP6Config *composite;
gboolean has_direct_route;
const struct in6_addr *gateway;
/* If no config was passed in, create a new one */
composite = nm_ip6_config_new (nm_device_get_ip_ifindex (self));
ensure_con_ipx_config (self);
g_assert (composite);
/* Merge all the IP configs into the composite config */
if (priv->ac_ip6_config)
nm_ip6_config_merge (composite, priv->ac_ip6_config);
if (priv->dhcp6_ip6_config)
nm_ip6_config_merge (composite, priv->dhcp6_ip6_config);
if (priv->vpn6_config)
nm_ip6_config_merge (composite, priv->vpn6_config);
if (priv->ext_ip6_config)
nm_ip6_config_merge (composite, priv->ext_ip6_config);
/* Merge WWAN config *last* to ensure modem-given settings overwrite
* any external stuff set by pppd or other scripts.
*/
if (priv->wwan_ip6_config)
nm_ip6_config_merge (composite, priv->wwan_ip6_config);
/* Merge user overrides into the composite config. For assumed connections,
* con_ip6_config is empty. */
if (priv->con_ip6_config)
nm_ip6_config_merge (composite, priv->con_ip6_config);
connection = nm_device_get_connection (self);
/* Add the default route.
*
* We keep track of the default route of a device in a private field.
* NMDevice needs to know the default route at this point, because the gateway
* might require a direct route (see below).
*
* But also, we don't want to add the default route to priv->ip6_config,
* because the default route from the setting might not be the same that
* NMDefaultRouteManager eventually configures (because the it might
* tweak the effective metric).
*/
/* unless we come to a different conclusion below, we have no default route and
* the route is assumed. */
priv->default_route.v6_has = FALSE;
priv->default_route.v6_is_assumed = TRUE;
if (!commit) {
/* during a non-commit event, we always pickup whatever is configured. */
goto END_ADD_DEFAULT_ROUTE;
}
if (nm_device_uses_assumed_connection (self))
goto END_ADD_DEFAULT_ROUTE;
/* we are about to commit (for a non-assumed connection). Enforce whatever we have
* configured. */
priv->default_route.v6_is_assumed = FALSE;
if ( !connection
|| !nm_default_route_manager_ip6_connection_has_default_route (nm_default_route_manager_get (), connection))
goto END_ADD_DEFAULT_ROUTE;
if (!nm_ip6_config_get_num_addresses (composite)) {
/* without addresses we can have no default route. */
goto END_ADD_DEFAULT_ROUTE;
}
gateway = nm_ip6_config_get_gateway (composite);
if (!gateway)
goto END_ADD_DEFAULT_ROUTE;
has_direct_route = nm_ip6_config_get_direct_route_for_host (composite, gateway) != NULL;
priv->default_route.v6_has = TRUE;
memset (&priv->default_route.v6, 0, sizeof (priv->default_route.v6));
priv->default_route.v6.source = NM_IP_CONFIG_SOURCE_USER;
priv->default_route.v6.gateway = *gateway;
priv->default_route.v6.metric = nm_device_get_ip6_route_metric (self);
priv->default_route.v6.mss = nm_ip6_config_get_mss (composite);
if (!has_direct_route) {
NMPlatformIP6Route r = priv->default_route.v6;
/* add a direct route to the gateway */
r.network = *gateway;
r.plen = 128;
r.gateway = in6addr_any;
nm_ip6_config_add_route (composite, &r);
}
END_ADD_DEFAULT_ROUTE:
if (priv->default_route.v6_is_assumed) {
/* If above does not explicitly assign a default route, we always pick up the
* default route based on what is currently configured.
* That means that even managed connections with never-default, can
* get a default route (if configured externally).
*/
priv->default_route.v6_has = _device_get_default_route_from_platform (self, AF_INET6, (NMPlatformIPRoute *) &priv->default_route.v6);
}
nm_ip6_config_addresses_sort (composite,
priv->rdisc ? priv->rdisc_use_tempaddr : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
/* Allow setting MTU etc */
if (commit) {
if (NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit)
NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit (self, composite);
}
success = nm_device_set_ip6_config (self, composite, commit, out_reason);
g_object_unref (composite);
return success;
}
static void
dhcp6_lease_change (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
if (priv->dhcp6_ip6_config == NULL) {
_LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind");
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
return;
}
g_assert (priv->dhcp6_client); /* sanity check */
connection = nm_device_get_connection (self);
g_assert (connection);
/* Apply the updated config */
if (ip6_config_merge_and_apply (self, TRUE, &reason) == FALSE) {
_LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event.");
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
} else {
/* Notify dispatcher scripts of new DHCPv6 config */
nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE, connection, self, NULL, NULL, NULL);
}
}
static void
dhcp6_fail (NMDevice *self, gboolean timeout)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
dhcp6_cleanup (self, TRUE, FALSE);
if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) {
if (timeout || (priv->ip6_state == IP_CONF))
nm_device_activate_schedule_ip6_config_timeout (self);
else if (priv->ip6_state == IP_DONE)
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
else
g_warn_if_reached ();
} else {
/* not a hard failure; just live with the RA info */
if (priv->ip6_state == IP_CONF)
nm_device_activate_schedule_ip6_config_result (self);
}
}
static void
dhcp6_timeout (NMDevice *self, NMDhcpClient *client)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED)
dhcp6_fail (self, TRUE);
else {
/* not a hard failure; just live with the RA info */
dhcp6_cleanup (self, TRUE, FALSE);
if (priv->ip6_state == IP_CONF)
nm_device_activate_schedule_ip6_config_result (self);
}
}
static void
dhcp6_update_config (NMDevice *self, NMDhcp6Config *config, GHashTable *options)
{
GHashTableIter iter;
const char *key, *value;
/* Update the DHCP6 config object with new DHCP options */
nm_dhcp6_config_reset (config);
g_hash_table_iter_init (&iter, options);
while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value))
nm_dhcp6_config_add_option (config, key, value);
g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG);
}
static void
dhcp6_state_changed (NMDhcpClient *client,
NMDhcpState state,
NMIP6Config *ip6_config,
GHashTable *options,
gpointer user_data)
{
NMDevice *self = NM_DEVICE (user_data);
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == TRUE);
g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config));
_LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state);
switch (state) {
case NM_DHCP_STATE_BOUND:
g_clear_object (&priv->dhcp6_ip6_config);
if (ip6_config) {
priv->dhcp6_ip6_config = g_object_ref (ip6_config);
dhcp6_update_config (self, priv->dhcp6_config, options);
}
if (priv->ip6_state == IP_CONF) {
if (priv->dhcp6_ip6_config == NULL) {
/* FIXME: Initial DHCP failed; should we fail IPv6 entirely then? */
nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED);
break;
}
nm_device_activate_schedule_ip6_config_result (self);
} else if (priv->ip6_state == IP_DONE)
dhcp6_lease_change (self);
break;
case NM_DHCP_STATE_TIMEOUT:
dhcp6_timeout (self, client);
break;
case NM_DHCP_STATE_EXPIRE:
/* Ignore expiry before we even have a lease (NAK, old lease, etc) */
if (priv->ip6_state != IP_CONF)
dhcp6_fail (self, FALSE);
break;
case NM_DHCP_STATE_DONE:
/* In IPv6 info-only mode, the client doesn't handle leases so it
* may exit right after getting a response from the server. That's
* normal. In that case we just ignore the exit.
*/
if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF)
break;
/* Otherwise, fall through */
case NM_DHCP_STATE_FAIL:
dhcp6_fail (self, FALSE);
break;
default:
break;
}
}
static gboolean
dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMSettingIPConfig *s_ip6;
GByteArray *tmp = NULL;
const guint8 *hw_addr;
size_t hw_addr_len = 0;
g_assert (connection);
s_ip6 = nm_connection_get_setting_ip6_config (connection);
g_assert (s_ip6);
hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len);
if (hw_addr_len) {
tmp = g_byte_array_sized_new (hw_addr_len);
g_byte_array_append (tmp, hw_addr, hw_addr_len);
}
priv->dhcp6_client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (),
nm_device_get_ip_iface (self),
nm_device_get_ip_ifindex (self),
tmp,
nm_connection_get_uuid (connection),
nm_device_get_ip6_route_metric (self),
nm_setting_ip_config_get_dhcp_send_hostname (s_ip6),
nm_setting_ip_config_get_dhcp_hostname (s_ip6),
priv->dhcp_timeout,
priv->dhcp_anycast_address,
(priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE,
nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6)));
if (tmp)
g_byte_array_free (tmp, TRUE);
if (priv->dhcp6_client) {
priv->dhcp6_state_sigid = g_signal_connect (priv->dhcp6_client,
NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
G_CALLBACK (dhcp6_state_changed),
self);
}
return !!priv->dhcp6_client;
}
static gboolean
dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
NMSettingIPConfig *s_ip6;
g_clear_object (&priv->dhcp6_config);
priv->dhcp6_config = nm_dhcp6_config_new ();
g_warn_if_fail (priv->dhcp6_ip6_config == NULL);
g_clear_object (&priv->dhcp6_ip6_config);
connection = nm_device_get_connection (self);
g_assert (connection);
s_ip6 = nm_connection_get_setting_ip6_config (connection);
if (!nm_setting_ip_config_get_may_fail (s_ip6) ||
!strcmp (nm_setting_ip_config_get_method (s_ip6), NM_SETTING_IP6_CONFIG_METHOD_DHCP))
nm_device_add_pending_action (self, PENDING_ACTION_DHCP6, TRUE);
if (wait_for_ll) {
NMActStageReturn ret;
/* ensure link local is ready... */
ret = linklocal6_start (self);
if (ret == NM_ACT_STAGE_RETURN_POSTPONE) {
/* success; wait for the LL address to show up */
return TRUE;
}
/* success; already have the LL address; kick off DHCP */
g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
}
if (!dhcp6_start_with_link_ready (self, connection)) {
*reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED;
return FALSE;
}
return TRUE;
}
gboolean
nm_device_dhcp6_renew (NMDevice *self, gboolean release)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
g_return_val_if_fail (priv->dhcp6_client != NULL, FALSE);
_LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested");
/* Terminate old DHCP instance and release the old lease */
dhcp6_cleanup (self, TRUE, release);
/* Start DHCP again on the interface */
return dhcp6_start (self, FALSE, NULL);
}
/******************************************/
static gboolean
have_ip6_address (const NMIP6Config *ip6_config, gboolean linklocal)
{
guint i;
if (!ip6_config)
return FALSE;
linklocal = !!linklocal;
for (i = 0; i < nm_ip6_config_get_num_addresses (ip6_config); i++) {
const NMPlatformIP6Address *addr = nm_ip6_config_get_address (ip6_config, i);
if ((IN6_IS_ADDR_LINKLOCAL (&addr->address) == linklocal) &&
!(addr->flags & IFA_F_TENTATIVE))
return TRUE;
}
return FALSE;
}
static void
linklocal6_cleanup (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
if (priv->linklocal6_timeout_id) {
g_source_remove (priv->linklocal6_timeout_id);
priv->linklocal6_timeout_id = 0;
}
}
static gboolean
linklocal6_timeout_cb (gpointer user_data)
{
NMDevice *self = user_data;
linklocal6_cleanup (self);
_LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout");
nm_device_activate_schedule_ip6_config_timeout (self);
return G_SOURCE_REMOVE;
}
static void
linklocal6_complete (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
const char *method;
g_assert (priv->linklocal6_timeout_id);
g_assert (have_ip6_address (priv->ip6_config, TRUE));
linklocal6_cleanup (self);
connection = nm_device_get_connection (self);
g_assert (connection);
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
_LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method);
if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) {
if (!addrconf6_start_with_link_ready (self)) {
/* Time out IPv6 instead of failing the entire activation */
nm_device_activate_schedule_ip6_config_timeout (self);
}
} else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) {
if (!dhcp6_start_with_link_ready (self, connection)) {
/* Time out IPv6 instead of failing the entire activation */
nm_device_activate_schedule_ip6_config_timeout (self);
}
} else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0)
nm_device_activate_schedule_ip6_config_result (self);
else
g_return_if_fail (FALSE);
}
static void
check_and_add_ipv6ll_addr (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
int ip_ifindex = nm_device_get_ip_ifindex (self);
NMUtilsIPv6IfaceId iid;
struct in6_addr lladdr;
guint i, n;
if (priv->nm_ipv6ll == FALSE)
return;
if (priv->ip6_config) {
n = nm_ip6_config_get_num_addresses (priv->ip6_config);
for (i = 0; i < n; i++) {
const NMPlatformIP6Address *addr;
addr = nm_ip6_config_get_address (priv->ip6_config, i);
if (IN6_IS_ADDR_LINKLOCAL (&addr->address)) {
/* Already have an LL address, nothing to do */
return;
}
}
}
if (!nm_device_get_ip_iface_identifier (self, &iid)) {
_LOGW (LOGD_IP6, "failed to get interface identifier; IPv6 may be broken");
return;
}
memset (&lladdr, 0, sizeof (lladdr));
lladdr.s6_addr16[0] = htons (0xfe80);
nm_utils_ipv6_addr_set_interface_identfier (&lladdr, iid);
_LOGD (LOGD_IP6, "adding IPv6LL address %s", nm_utils_inet6_ntop (&lladdr, NULL));
if (!nm_platform_ip6_address_add (ip_ifindex,
lladdr,
in6addr_any,
64,
NM_PLATFORM_LIFETIME_PERMANENT,
NM_PLATFORM_LIFETIME_PERMANENT,
0)) {
_LOGW (LOGD_IP6, "failed to add IPv6 link-local address %s",
nm_utils_inet6_ntop (&lladdr, NULL));
}
}
static NMActStageReturn
linklocal6_start (NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
NMConnection *connection;
const char *method;
linklocal6_cleanup (self);
if (have_ip6_address (priv->ip6_config, TRUE))
return NM_ACT_STAGE_RETURN_SUCCESS;
connection = nm_device_get_connection (self);
g_assert (connection);
method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
_LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.", method);
check_and_add_ipv6ll_addr (self);
priv->linklocal6_timeout_id = g_timeout_add_seconds (5, linklocal6_timeout_cb, self);
return NM_ACT_STAGE_RETURN_POSTPONE;
}
/******************************************/
static void
print_support_extended_ifa_flags (NMSettingIP6ConfigPrivacy use_tempaddr)
{
static gint8 warn = 0;
static gint8 s_libnl = -1, s_kernel;
if (warn >= 2)
return;
if (s_libnl == -1) {
s_libnl = !!nm_platform_check_support_libnl_extended_ifa_flags ();
s_kernel = !!nm_platform_check_support_kernel_extended_ifa_flags ();
if (s_libnl && s_kernel) {
nm_log_dbg (LOGD_IP6, "kernel and libnl support extended IFA_FLAGS (needed by NM for IPv6 private addresses)");
warn = 2;
return;
}
}
if ( use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR
&& use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR) {
if (warn == 0) {
nm_log_dbg (LOGD_IP6, "%s%s%s %s not support extended IFA_FLAGS (needed by NM for IPv6 private addresses)",
!s_kernel ? "kernel" : "",
!s_kernel && !s_libnl ? " and " : "",
!s_libnl ? "libnl" : "",
!s_kernel && !s_libnl ? "do" : "does");
warn = 1;
}
return;
}
if (!s_libnl && !s_kernel) {
nm_log_warn (LOGD_IP6, "libnl and the kernel do not support extended IFA_FLAGS needed by NM for "
"IPv6 private addresses. This feature is not available");
} else if (!s_libnl) {
nm_log_warn (LOGD_IP6, "libnl does not support extended IFA_FLAGS needed by NM for "
"IPv6 private addresses. This feature is not available");
} else if (!s_kernel) {
nm_log_warn (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for "
"IPv6 private addresses. This feature is not available");
}
warn = 2;
}
static void
rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self)
{
NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
warn = 2;
}
static void
rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self)
{
address.preferred = discovered_address->preferred;
if (address.preferred > address.lifetime)
address.preferred = address.lifetime;
address.source = NM_IP_CONFIG_SOURCE_RDISC;
address.flags = ifa_flags;
nm_ip6_config_add_address (priv->ac_ip6_config, &address);
}
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: GNOME NetworkManager allows remote attackers to cause a denial of service (IPv6 traffic disruption) via a crafted MTU value in an IPv6 Router Advertisement (RA) message, a different vulnerability than CVE-2015-8215.
Commit Message: | Medium | 164,814 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 484 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 835 "ext/standard/var_unserializer.re"
{ return 0; }
#line 546 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
goto yy3;
yy14:
++YYCURSOR;
#line 829 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 595 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
goto yy20;
}
Vulnerability Type: Exec Code
CWE ID:
Summary: Use-after-free vulnerability in the process_nested_data function in ext/standard/var_unserializer.re in PHP before 5.4.36, 5.5.x before 5.5.20, and 5.6.x before 5.6.4 allows remote attackers to execute arbitrary code via a crafted unserialize call that leverages improper handling of duplicate keys within the serialized properties of an object, a different vulnerability than CVE-2004-1019.
Commit Message: | High | 164,892 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: OMX_ERRORTYPE SoftG711::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
return OMX_ErrorUndefined;
}
if(pcmParams->nPortIndex == 0) {
mNumChannels = pcmParams->nChannels;
}
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (mIsMLaw) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711mlaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711alaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Vulnerability Type: Overflow +Priv
CWE ID: CWE-119
Summary: mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 does not validate OMX buffer sizes, which allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27207275.
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
| High | 174,206 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: unset_and_free_gvalue (gpointer val)
{
g_value_unset (val);
g_free (val);
}
Vulnerability Type: DoS Bypass
CWE ID: CWE-264
Summary: DBus-GLib 0.73 disregards the access flag of exported GObject properties, which allows local users to bypass intended access restrictions and possibly cause a denial of service by modifying properties, as demonstrated by properties of the (1) DeviceKit-Power, (2) NetworkManager, and (3) ModemManager services.
Commit Message: | Low | 165,127 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void WebContentsImpl::LoadingStateChanged(bool to_different_document,
bool due_to_interstitial,
LoadNotificationDetails* details) {
if (ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber() &&
!due_to_interstitial) {
return;
}
bool is_loading = IsLoading();
if (!is_loading) {
load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
load_state_host_.clear();
upload_size_ = 0;
upload_position_ = 0;
}
GetRenderManager()->SetIsLoading(is_loading);
waiting_for_response_ = is_loading;
is_load_to_different_document_ = to_different_document;
if (delegate_)
delegate_->LoadingStateChanged(this, to_different_document);
NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
if (is_loading) {
TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
this, "URL", url, "Main FrameTreeNode id",
GetFrameTree()->root()->frame_tree_node_id());
for (auto& observer : observers_)
observer.DidStartLoading();
} else {
TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
this, "URL", url);
for (auto& observer : observers_)
observer.DidStopLoading();
}
int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
NotificationDetails det = NotificationService::NoDetails();
if (details)
det = Details<LoadNotificationDetails>(details);
NotificationService::current()->Notify(
type, Source<NavigationController>(&controller_), det);
}
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,332 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
unsigned int, flags, struct sockaddr __user *, addr,
int __user *, addr_len)
{
struct socket *sock;
struct iovec iov;
struct msghdr msg;
struct sockaddr_storage address;
int err, err2;
int fput_needed;
if (size > INT_MAX)
size = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
msg.msg_control = NULL;
msg.msg_controllen = 0;
iov.iov_len = size;
iov.iov_base = ubuf;
iov_iter_init(&msg.msg_iter, READ, &iov, 1, size);
/* Save some cycles and don't copy the address if not needed */
msg.msg_name = addr ? (struct sockaddr *)&address : NULL;
/* We assume all kernel code knows the size of sockaddr_storage */
msg.msg_namelen = 0;
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
err = sock_recvmsg(sock, &msg, size, flags);
if (err >= 0 && addr != NULL) {
err2 = move_addr_to_user(&address,
msg.msg_namelen, addr, addr_len);
if (err2 < 0)
err = err2;
}
fput_light(sock->file, fput_needed);
out:
return err;
}
Vulnerability Type: +Priv
CWE ID: CWE-264
Summary: net/socket.c in the Linux kernel 3.19 before 3.19.3 does not validate certain range data for (1) sendto and (2) recvfrom system calls, which allows local users to gain privileges by leveraging a subsystem that uses the copy_from_iter function in the iov_iter interface, as demonstrated by the Bluetooth subsystem.
Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom
Cc: [email protected] # v3.19
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | High | 167,571 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void InitializeOriginStatFromOriginRequestSummary(
OriginStat* origin,
const OriginRequestSummary& summary) {
origin->set_origin(summary.origin.spec());
origin->set_number_of_hits(1);
origin->set_average_position(summary.first_occurrence + 1);
origin->set_always_access_network(summary.always_access_network);
origin->set_accessed_network(summary.accessed_network);
}
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 <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311} | Medium | 172,379 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
std::string url_string = GetContextualSuggestionsUrl();
GURL suggest_url(url_string);
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (OmniboxFieldTrial::InZeroSuggestRedirectToChromeFieldTrial()) {
url_string +=
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields();
suggest_url = GURL(url_string);
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 42.0.2311.90 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
Commit Message: Provide experimental contextual suggestions when current URL comes from a google domain.
The counts for the Omnibox.ZeroSuggestRequests historgram are 35% smaller for groups that are running under the ZeroSuggestRedirectToChrome flag. Note that previous to this CL, a request was not made when the user was visiting an HTTPS page and the domain of the current was different from that of the service providing zero suggestions. This CL addresses this restrictions by making sure that requests are sent to the experimental service when Google is the default search engine AND the same request was validated to be sent to Google.
BUG=692471
Review-Url: https://codereview.chromium.org/2915163003
Cr-Commit-Position: refs/heads/master@{#476786} | High | 172,013 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: MirrorMockURLRequestJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const base::FilePath& file_path,
ReportResponseHeadersOnUI report_on_ui)
: net::URLRequestMockHTTPJob(request, network_delegate, file_path),
report_on_ui_(report_on_ui) {}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 50.0.2661.94 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652} | High | 172,578 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() {
return syslogs_lib_.GetDefaultImpl(use_stub_impl_);
}
Vulnerability Type: Exec Code
CWE ID: CWE-189
Summary: The Program::getActiveUniformMaxLength function in libGLESv2/Program.cpp in libGLESv2.dll in the WebGLES library in Almost Native Graphics Layer Engine (ANGLE), as used in Mozilla Firefox 4.x before 4.0.1 on Windows and in the GPU process in Google Chrome before 10.0.648.205 on Windows, allows remote attackers to execute arbitrary code via unspecified vectors, related to an *off-by-three* error.
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 | High | 170,631 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: DecodeTime(char *str, int *tmask, struct tm * tm, fsec_t *fsec)
{
char *cp;
*tmask = DTK_TIME_M;
tm->tm_hour = strtol(str, &cp, 10);
if (*cp != ':')
return -1;
str = cp + 1;
tm->tm_min = strtol(str, &cp, 10);
if (*cp == '\0')
{
tm->tm_sec = 0;
*fsec = 0;
}
else if (*cp != ':')
return -1;
else
{
str = cp + 1;
tm->tm_sec = strtol(str, &cp, 10);
if (*cp == '\0')
*fsec = 0;
else if (*cp == '.')
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[MAXDATELEN + 1];
/*
* OK, we have at most six digits to work with. Let's construct a
* string and then do the conversion to an integer.
*/
strncpy(fstr, (cp + 1), 7);
strcpy(fstr + strlen(fstr), "000000");
*(fstr + 6) = '\0';
*fsec = strtol(fstr, &cp, 10);
#else
str = cp;
*fsec = strtod(str, &cp);
#endif
if (*cp != '\0')
return -1;
}
else
return -1;
}
/* do a sanity check */
#ifdef HAVE_INT64_TIMESTAMP
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC)
return -1;
#else
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= 1)
return -1;
#endif
return 0;
} /* DecodeTime() */
Vulnerability Type: DoS Exec Code Overflow
CWE ID: CWE-119
Summary: Multiple stack-based buffer overflows in PostgreSQL before 8.4.20, 9.0.x before 9.0.16, 9.1.x before 9.1.12, 9.2.x before 9.2.7, and 9.3.x before 9.3.3 allow remote authenticated users to cause a denial of service (crash) or possibly execute arbitrary code via vectors related to an incorrect MAXDATELEN constant and datetime values involving (1) intervals, (2) timestamps, or (3) timezones, a different vulnerability than CVE-2014-0065.
Commit Message: Fix handling of wide datetime input/output.
Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value. It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer. ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own. In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly. Back-patch to 8.4
(all supported versions).
Reported by Daniel Schüssler, reviewed by Tom Lane.
Security: CVE-2014-0063 | Medium | 166,465 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: juniper_mlppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLPPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link
* best indicator if the cookie looks like a proto */
if (ndo->ndo_eflag &&
EXTRACT_16BITS(&l2info.cookie) != PPP_OSI &&
EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL))
ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle));
p+=l2info.header_len;
/* first try the LSQ protos */
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
/* IP traffic going to the RE would not have a cookie
* -> this must be incoming IS-IS over PPP
*/
if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR))
ppp_print(ndo, p, l2info.length);
else
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length, l2info.caplen);
return l2info.header_len;
default:
break;
}
/* zero length cookie ? */
switch (EXTRACT_16BITS(&l2info.cookie)) {
case PPP_OSI:
ppp_print(ndo, p - 2, l2info.length + 2);
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */
default:
ppp_print(ndo, p, l2info.length);
break;
}
return l2info.header_len;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The ISO CLNS parser in tcpdump before 4.9.2 has a buffer over-read in print-isoclns.c:isoclns_print().
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s). | High | 167,952 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void ScrollHitTestDisplayItem::PropertiesAsJSON(JSONObject& json) const {
DisplayItem::PropertiesAsJSON(json);
json.SetString("scrollOffsetNode",
String::Format("%p", scroll_offset_node_.get()));
}
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 <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> 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 <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# 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 <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930} | High | 171,840 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ShellWindow::ShellWindow(Profile* profile,
const extensions::Extension* extension,
const GURL& url)
: profile_(profile),
extension_(extension),
ALLOW_THIS_IN_INITIALIZER_LIST(
extension_function_dispatcher_(profile, this)) {
web_contents_ = WebContents::Create(
profile, SiteInstance::CreateForURL(profile, url), MSG_ROUTING_NONE, NULL,
NULL);
contents_.reset(new TabContents(web_contents_));
content::WebContentsObserver::Observe(web_contents_);
web_contents_->SetDelegate(this);
chrome::SetViewType(web_contents_, chrome::VIEW_TYPE_APP_SHELL);
web_contents_->GetMutableRendererPrefs()->
browser_handles_all_top_level_requests = true;
web_contents_->GetRenderViewHost()->SyncRendererPrefs();
web_contents_->GetController().LoadURL(
url, content::Referrer(), content::PAGE_TRANSITION_LINK,
std::string());
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
content::Source<Profile>(profile_));
registrar_.Add(this, content::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
TabContents* tab_contents = TabContents::FromWebContents(web_contents_);
InfoBarTabHelper* infobar_helper = tab_contents->infobar_tab_helper();
infobar_helper->set_infobars_enabled(false);
browser::StartKeepAlive();
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in the PDF functionality in Google Chrome before 22.0.1229.79 allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted document.
Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time.
When you first create a window with chrome.appWindow.create(), it won't have
loaded any resources. So, at create time, you are guaranteed that:
child_window.location.href == 'about:blank'
child_window.document.documentElement.outerHTML ==
'<html><head></head><body></body></html>'
This is in line with the behaviour of window.open().
BUG=131735
TEST=browser_tests:PlatformAppBrowserTest.WindowsApi
Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072
Review URL: https://chromiumcodereview.appspot.com/10644006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 170,814 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p,
unsigned char *limit, 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, limit);
# endif /* !OPENSSL_NO_EC */
# ifndef OPENSSL_NO_SRP
if (s->srp_ctx.login != NULL) {
OPENSSL_free(s->srp_ctx.login);
s->srp_ctx.login = NULL;
}
# endif
s->srtp_profile = NULL;
if (data == limit)
goto ri_check;
if (limit - data < 2)
goto err;
n2s(data, len);
if (limit - data != len)
goto err;
while (limit - data >= 4) {
n2s(data, type);
n2s(data, size);
if (limit - data < size)
goto err;
# 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)
goto err;
n2s(data, dsize);
size -= 2;
if (dsize > size)
goto err;
sdata = data;
while (dsize > 3) {
servname_type = *(sdata++);
n2s(sdata, len);
dsize -= 3;
if (len > dsize)
goto err;
if (s->servername_done == 0)
switch (servname_type) {
case TLSEXT_NAMETYPE_host_name:
if (!s->hit) {
if (s->session->tlsext_hostname)
goto err;
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)
goto err;
}
# ifndef OPENSSL_NO_SRP
else if (type == TLSEXT_TYPE_srp) {
if (size == 0 || ((len = data[0])) != (size - 1))
goto err;
if (s->srp_ctx.login != NULL)
goto err;
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)
goto err;
}
# 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)
goto err;
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 ||
/* Each NamedCurve is 2 bytes. */
ellipticcurvelist_length & 1)
goto err;
if (!s->hit) {
if (s->session->tlsext_ellipticcurvelist)
goto err;
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);
}
/* dummy byte just to get non-NULL */
if (s->s3->client_opaque_prf_input_len == 0)
s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
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)
goto err;
sigalg_seen = 1;
n2s(data, dsize);
size -= 2;
if (dsize != size || dsize & 1)
goto err;
if (!tls1_process_sigalgs(s, data, dsize))
goto err;
} else if (type == TLSEXT_TYPE_status_request &&
s->version != DTLS1_VERSION) {
if (size < 5)
goto err;
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)
goto err;
while (dsize > 0) {
OCSP_RESPID *id;
int idsize;
&& !(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;
}
}
OCSP_RESPID_free(id);
goto err;
}
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;
goto err;
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))
goto err;
}
}
/*
* 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 (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
&& type == TLSEXT_TYPE_use_srtp) {
if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
return 0;
}
# endif
data += size;
}
/* Spurious data on the end */
if (data != limit)
goto err;
*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;
err:
*al = SSL_AD_DECODE_ERROR;
return 0;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Multiple memory leaks in t1_lib.c in OpenSSL before 1.0.1u, 1.0.2 before 1.0.2i, and 1.1.0 before 1.1.0a allow remote attackers to cause a denial of service (memory consumption) via large OCSP Status Request extensions.
Commit Message: | High | 164,964 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n)
{
cmsSEQ* Seq;
cmsUInt32Number i;
if (n == 0) return NULL;
if (n > 255) return NULL;
Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ));
if (Seq == NULL) return NULL;
Seq -> ContextID = ContextID;
Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
Seq -> n = n;
for (i=0; i < n; i++) {
Seq -> seq[i].Manufacturer = NULL;
Seq -> seq[i].Model = NULL;
Seq -> seq[i].Description = NULL;
}
return Seq;
}
Vulnerability Type: DoS
CWE ID:
Summary: Little CMS (lcms2) before 2.5, as used in OpenJDK 7 and possibly other products, allows remote attackers to cause a denial of service (NULL pointer dereference and crash) via vectors related to (1) cmsStageAllocLabV2ToV4curves, (2) cmsPipelineDup, (3) cmsAllocProfileSequenceDescription, (4) CurvesAlloc, and (5) cmsnamed.
Commit Message: Non happy-path fixes | Medium | 166,542 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 495 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 860 "ext/standard/var_unserializer.re"
{ return 0; }
#line 557 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 854 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 606 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych <= '/') goto yy18;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 707 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
long elements;
char *class_name;
zend_class_entry *ce;
zend_class_entry **pce;
int incomplete_class = 0;
int custom_object = 0;
zval *user_func;
zval *retval_ptr;
zval **args[1];
zval *arg_func_name;
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
INIT_PZVAL(*rval);
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
class_name = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(class_name, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = estrndup(class_name, len);
do {
/* Try to find class directly */
BG(serialize_lock)++;
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
ce = *pce;
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
MAKE_STD_ZVAL(user_func);
ZVAL_STRING(user_func, PG(unserialize_callback_func), 1);
args[0] = &arg_func_name;
MAKE_STD_ZVAL(arg_func_name);
ZVAL_STRING(arg_func_name, class_name, 1);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "defined (%s) but not found", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
}
BG(serialize_lock)--;
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
/* The callback function may have defined the class */
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
ce = *pce;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Function %s() hasn't defined the class it was called for", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 784 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 698 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
INIT_PZVAL(*rval);
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 818 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 677 "ext/standard/var_unserializer.re"
{
long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
INIT_PZVAL(*rval);
array_init_size(*rval, elements);
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 860 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 642 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
efree(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 0);
return 1;
}
#line 916 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 609 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 1);
return 1;
}
#line 970 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 599 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
use_double:
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1068 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 584 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
if (!strncmp(start + 2, "NAN", 3)) {
ZVAL_DOUBLE(*rval, php_get_nan());
} else if (!strncmp(start + 2, "INF", 3)) {
ZVAL_DOUBLE(*rval, php_get_inf());
} else if (!strncmp(start + 2, "-INF", 4)) {
ZVAL_DOUBLE(*rval, -php_get_inf());
}
return 1;
}
#line 1142 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 557 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp(YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_LONG(*rval, parse_iv(start + 2));
return 1;
}
#line 1196 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 550 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_BOOL(*rval, parse_iv(start + 2));
return 1;
}
#line 1211 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 543 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_NULL(*rval);
return 1;
}
#line 1221 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 520 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval == *rval_ref) return 0;
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_UNSET_ISREF_PP(rval);
return 1;
}
#line 1267 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 499 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_SET_ISREF_PP(rval);
return 1;
}
#line 1311 "ext/standard/var_unserializer.c"
}
#line 862 "ext/standard/var_unserializer.re"
return 0;
}
Vulnerability Type: DoS Overflow Mem. Corr.
CWE ID: CWE-119
Summary: ext/standard/var_unserializer.re in PHP before 5.6.26 mishandles object-deserialization failures, which allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via an unserialize call that references a partially constructed object.
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction | High | 166,941 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int propagate_one(struct mount *m)
{
struct mount *child;
int type;
/* skip ones added by this propagate_mnt() */
if (IS_MNT_NEW(m))
return 0;
/* skip if mountpoint isn't covered by it */
if (!is_subdir(mp->m_dentry, m->mnt.mnt_root))
return 0;
if (peers(m, last_dest)) {
type = CL_MAKE_SHARED;
} else {
struct mount *n, *p;
for (n = m; ; n = p) {
p = n->mnt_master;
if (p == dest_master || IS_MNT_MARKED(p)) {
while (last_dest->mnt_master != p) {
last_source = last_source->mnt_master;
last_dest = last_source->mnt_parent;
}
if (!peers(n, last_dest)) {
last_source = last_source->mnt_master;
last_dest = last_source->mnt_parent;
}
break;
}
}
type = CL_SLAVE;
/* beginning of peer group among the slaves? */
if (IS_MNT_SHARED(m))
type |= CL_MAKE_SHARED;
}
/* Notice when we are propagating across user namespaces */
if (m->mnt_ns->user_ns != user_ns)
type |= CL_UNPRIVILEGED;
child = copy_tree(last_source, last_source->mnt.mnt_root, type);
if (IS_ERR(child))
return PTR_ERR(child);
child->mnt.mnt_flags &= ~MNT_LOCKED;
mnt_set_mountpoint(m, mp, child);
last_dest = m;
last_source = child;
if (m->mnt_master != dest_master) {
read_seqlock_excl(&mount_lock);
SET_MNT_MARK(m->mnt_master);
read_sequnlock_excl(&mount_lock);
}
hlist_add_head(&child->mnt_hash, list);
return 0;
}
Vulnerability Type: DoS
CWE ID:
Summary: fs/pnode.c in the Linux kernel before 4.5.4 does not properly traverse a mount propagation tree in a certain case involving a slave mount, which allows local users to cause a denial of service (NULL pointer dereference and OOPS) via a crafted series of mount system calls.
Commit Message: propogate_mnt: Handle the first propogated copy being a slave
When the first propgated copy was a slave the following oops would result:
> BUG: unable to handle kernel NULL pointer dereference at 0000000000000010
> IP: [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0
> PGD bacd4067 PUD bac66067 PMD 0
> Oops: 0000 [#1] SMP
> Modules linked in:
> CPU: 1 PID: 824 Comm: mount Not tainted 4.6.0-rc5userns+ #1523
> Hardware name: Bochs Bochs, BIOS Bochs 01/01/2007
> task: ffff8800bb0a8000 ti: ffff8800bac3c000 task.ti: ffff8800bac3c000
> RIP: 0010:[<ffffffff811fba4e>] [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0
> RSP: 0018:ffff8800bac3fd38 EFLAGS: 00010283
> RAX: 0000000000000000 RBX: ffff8800bb77ec00 RCX: 0000000000000010
> RDX: 0000000000000000 RSI: ffff8800bb58c000 RDI: ffff8800bb58c480
> RBP: ffff8800bac3fd48 R08: 0000000000000001 R09: 0000000000000000
> R10: 0000000000001ca1 R11: 0000000000001c9d R12: 0000000000000000
> R13: ffff8800ba713800 R14: ffff8800bac3fda0 R15: ffff8800bb77ec00
> FS: 00007f3c0cd9b7e0(0000) GS:ffff8800bfb00000(0000) knlGS:0000000000000000
> CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
> CR2: 0000000000000010 CR3: 00000000bb79d000 CR4: 00000000000006e0
> Stack:
> ffff8800bb77ec00 0000000000000000 ffff8800bac3fd88 ffffffff811fbf85
> ffff8800bac3fd98 ffff8800bb77f080 ffff8800ba713800 ffff8800bb262b40
> 0000000000000000 0000000000000000 ffff8800bac3fdd8 ffffffff811f1da0
> Call Trace:
> [<ffffffff811fbf85>] propagate_mnt+0x105/0x140
> [<ffffffff811f1da0>] attach_recursive_mnt+0x120/0x1e0
> [<ffffffff811f1ec3>] graft_tree+0x63/0x70
> [<ffffffff811f1f6b>] do_add_mount+0x9b/0x100
> [<ffffffff811f2c1a>] do_mount+0x2aa/0xdf0
> [<ffffffff8117efbe>] ? strndup_user+0x4e/0x70
> [<ffffffff811f3a45>] SyS_mount+0x75/0xc0
> [<ffffffff8100242b>] do_syscall_64+0x4b/0xa0
> [<ffffffff81988f3c>] entry_SYSCALL64_slow_path+0x25/0x25
> Code: 00 00 75 ec 48 89 0d 02 22 22 01 8b 89 10 01 00 00 48 89 05 fd 21 22 01 39 8e 10 01 00 00 0f 84 e0 00 00 00 48 8b 80 d8 00 00 00 <48> 8b 50 10 48 89 05 df 21 22 01 48 89 15 d0 21 22 01 8b 53 30
> RIP [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0
> RSP <ffff8800bac3fd38>
> CR2: 0000000000000010
> ---[ end trace 2725ecd95164f217 ]---
This oops happens with the namespace_sem held and can be triggered by
non-root users. An all around not pleasant experience.
To avoid this scenario when finding the appropriate source mount to
copy stop the walk up the mnt_master chain when the first source mount
is encountered.
Further rewrite the walk up the last_source mnt_master chain so that
it is clear what is going on.
The reason why the first source mount is special is that it it's
mnt_parent is not a mount in the dest_mnt propagation tree, and as
such termination conditions based up on the dest_mnt mount propgation
tree do not make sense.
To avoid other kinds of confusion last_dest is not changed when
computing last_source. last_dest is only used once in propagate_one
and that is above the point of the code being modified, so changing
the global variable is meaningless and confusing.
Cc: [email protected]
fixes: f2ebb3a921c1ca1e2ddd9242e95a1989a50c4c68 ("smarter propagate_mnt()")
Reported-by: Tycho Andersen <[email protected]>
Reviewed-by: Seth Forshee <[email protected]>
Tested-by: Seth Forshee <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]> | Medium | 167,234 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pentry, *pmembers, *pcount = NULL, *pinf;
long count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pcount);
if (!php_var_unserialize(&pcount, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
while(count-- > 0) {
spl_SplObjectStorageElement *pelement;
char *hash;
int hash_len;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
ALLOC_INIT_ZVAL(pentry);
if (!php_var_unserialize(&pentry, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pentry);
goto outexcept;
}
if(Z_TYPE_P(pentry) != IS_OBJECT) {
zval_ptr_dtor(&pentry);
goto outexcept;
}
ALLOC_INIT_ZVAL(pinf);
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&pinf, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pinf);
goto outexcept;
}
}
hash = spl_object_storage_get_hash(intern, getThis(), pentry, &hash_len TSRMLS_CC);
if (!hash) {
zval_ptr_dtor(&pentry);
zval_ptr_dtor(&pinf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC);
spl_object_storage_free_hash(intern, hash);
if(pelement) {
if(pelement->inf) {
var_push_dtor(&var_hash, &pelement->inf);
}
if(pelement->obj) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
spl_object_storage_attach(intern, getThis(), pentry, pinf TSRMLS_CC);
zval_ptr_dtor(&pentry);
zval_ptr_dtor(&pinf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
if (pcount) {
zval_ptr_dtor(&pcount);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
if (pcount) {
zval_ptr_dtor(&pcount);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
Vulnerability Type: Exec Code
CWE ID:
Summary: The SPL component in PHP before 5.4.30 and 5.5.x before 5.5.14 incorrectly anticipates that certain data structures will have the array data type after unserialization, which allows remote attackers to execute arbitrary code via a crafted string that triggers use of a Hashtable destructor, related to "type confusion" issues in (1) ArrayObject and (2) SPLObjectStorage.
Commit Message: | High | 165,167 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 && p[0] != 0x80 && p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: Various out of bounds reads when handling responses in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to potentially crash the opensc library using programs.
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes. | Low | 169,047 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: struct snd_seq_client_port *snd_seq_create_port(struct snd_seq_client *client,
int port)
{
unsigned long flags;
struct snd_seq_client_port *new_port, *p;
int num = -1;
/* sanity check */
if (snd_BUG_ON(!client))
return NULL;
if (client->num_ports >= SNDRV_SEQ_MAX_PORTS) {
pr_warn("ALSA: seq: too many ports for client %d\n", client->number);
return NULL;
}
/* create a new port */
new_port = kzalloc(sizeof(*new_port), GFP_KERNEL);
if (!new_port)
return NULL; /* failure, out of memory */
/* init port data */
new_port->addr.client = client->number;
new_port->addr.port = -1;
new_port->owner = THIS_MODULE;
sprintf(new_port->name, "port-%d", num);
snd_use_lock_init(&new_port->use_lock);
port_subs_info_init(&new_port->c_src);
port_subs_info_init(&new_port->c_dest);
num = port >= 0 ? port : 0;
mutex_lock(&client->ports_mutex);
write_lock_irqsave(&client->ports_lock, flags);
list_for_each_entry(p, &client->ports_list_head, list) {
if (p->addr.port > num)
break;
if (port < 0) /* auto-probe mode */
num = p->addr.port + 1;
}
/* insert the new port */
list_add_tail(&new_port->list, &p->list);
client->num_ports++;
new_port->addr.port = num; /* store the port number in the port */
write_unlock_irqrestore(&client->ports_lock, flags);
mutex_unlock(&client->ports_mutex);
sprintf(new_port->name, "port-%d", num);
return new_port;
}
Vulnerability Type: DoS
CWE ID: CWE-416
Summary: Race condition in the ALSA subsystem in the Linux kernel before 4.13.8 allows local users to cause a denial of service (use-after-free) or possibly have unspecified other impact via crafted /dev/snd/seq ioctl calls, related to sound/core/seq/seq_clientmgr.c and sound/core/seq/seq_ports.c.
Commit Message: ALSA: seq: Fix use-after-free at creating a port
There is a potential race window opened at creating and deleting a
port via ioctl, as spotted by fuzzing. snd_seq_create_port() creates
a port object and returns its pointer, but it doesn't take the
refcount, thus it can be deleted immediately by another thread.
Meanwhile, snd_seq_ioctl_create_port() still calls the function
snd_seq_system_client_ev_port_start() with the created port object
that is being deleted, and this triggers use-after-free like:
BUG: KASAN: use-after-free in snd_seq_ioctl_create_port+0x504/0x630 [snd_seq] at addr ffff8801f2241cb1
=============================================================================
BUG kmalloc-512 (Tainted: G B ): kasan: bad access detected
-----------------------------------------------------------------------------
INFO: Allocated in snd_seq_create_port+0x94/0x9b0 [snd_seq] age=1 cpu=3 pid=4511
___slab_alloc+0x425/0x460
__slab_alloc+0x20/0x40
kmem_cache_alloc_trace+0x150/0x190
snd_seq_create_port+0x94/0x9b0 [snd_seq]
snd_seq_ioctl_create_port+0xd1/0x630 [snd_seq]
snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
snd_seq_ioctl+0x40/0x80 [snd_seq]
do_vfs_ioctl+0x54b/0xda0
SyS_ioctl+0x79/0x90
entry_SYSCALL_64_fastpath+0x16/0x75
INFO: Freed in port_delete+0x136/0x1a0 [snd_seq] age=1 cpu=2 pid=4717
__slab_free+0x204/0x310
kfree+0x15f/0x180
port_delete+0x136/0x1a0 [snd_seq]
snd_seq_delete_port+0x235/0x350 [snd_seq]
snd_seq_ioctl_delete_port+0xc8/0x180 [snd_seq]
snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
snd_seq_ioctl+0x40/0x80 [snd_seq]
do_vfs_ioctl+0x54b/0xda0
SyS_ioctl+0x79/0x90
entry_SYSCALL_64_fastpath+0x16/0x75
Call Trace:
[<ffffffff81b03781>] dump_stack+0x63/0x82
[<ffffffff81531b3b>] print_trailer+0xfb/0x160
[<ffffffff81536db4>] object_err+0x34/0x40
[<ffffffff815392d3>] kasan_report.part.2+0x223/0x520
[<ffffffffa07aadf4>] ? snd_seq_ioctl_create_port+0x504/0x630 [snd_seq]
[<ffffffff815395fe>] __asan_report_load1_noabort+0x2e/0x30
[<ffffffffa07aadf4>] snd_seq_ioctl_create_port+0x504/0x630 [snd_seq]
[<ffffffffa07aa8f0>] ? snd_seq_ioctl_delete_port+0x180/0x180 [snd_seq]
[<ffffffff8136be50>] ? taskstats_exit+0xbc0/0xbc0
[<ffffffffa07abc5c>] snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
[<ffffffffa07abd10>] snd_seq_ioctl+0x40/0x80 [snd_seq]
[<ffffffff8136d433>] ? acct_account_cputime+0x63/0x80
[<ffffffff815b515b>] do_vfs_ioctl+0x54b/0xda0
.....
We may fix this in a few different ways, and in this patch, it's fixed
simply by taking the refcount properly at snd_seq_create_port() and
letting the caller unref the object after use. Also, there is another
potential use-after-free by sprintf() call in snd_seq_create_port(),
and this is moved inside the lock.
This fix covers CVE-2017-15265.
Reported-and-tested-by: Michael23 Yu <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]> | Medium | 167,729 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
int i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: ghostscript before version 9.21 is vulnerable to a heap based buffer overflow that was found in the ghostscript jbig2_decode_gray_scale_image function which is used to decode halftone segments in a JBIG2 image. A document (PostScript or PDF) with an embedded, specially crafted, jbig2 image could trigger a segmentation fault in ghostscript.
Commit Message: | Medium | 165,485 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: 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(("%d) id=%x type=%x offs=%x,%d\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_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 = %d\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 = %d, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
l = 4 + (uint32_t)CDF_ROUND(l, sizeof(l));
o += l >> 2;
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));
goto out;
}
}
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: add more check found by cert's fuzzer. | Medium | 169,882 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int cma_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event)
{
struct rdma_id_private *listen_id, *conn_id;
struct rdma_cm_event event;
int offset, ret;
u8 smac[ETH_ALEN];
u8 alt_smac[ETH_ALEN];
u8 *psmac = smac;
u8 *palt_smac = alt_smac;
int is_iboe = ((rdma_node_get_transport(cm_id->device->node_type) ==
RDMA_TRANSPORT_IB) &&
(rdma_port_get_link_layer(cm_id->device,
ib_event->param.req_rcvd.port) ==
IB_LINK_LAYER_ETHERNET));
listen_id = cm_id->context;
if (!cma_check_req_qp_type(&listen_id->id, ib_event))
return -EINVAL;
if (cma_disable_callback(listen_id, RDMA_CM_LISTEN))
return -ECONNABORTED;
memset(&event, 0, sizeof event);
offset = cma_user_data_offset(listen_id);
event.event = RDMA_CM_EVENT_CONNECT_REQUEST;
if (ib_event->event == IB_CM_SIDR_REQ_RECEIVED) {
conn_id = cma_new_udp_id(&listen_id->id, ib_event);
event.param.ud.private_data = ib_event->private_data + offset;
event.param.ud.private_data_len =
IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE - offset;
} else {
conn_id = cma_new_conn_id(&listen_id->id, ib_event);
cma_set_req_event_data(&event, &ib_event->param.req_rcvd,
ib_event->private_data, offset);
}
if (!conn_id) {
ret = -ENOMEM;
goto err1;
}
mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING);
ret = cma_acquire_dev(conn_id, listen_id);
if (ret)
goto err2;
conn_id->cm_id.ib = cm_id;
cm_id->context = conn_id;
cm_id->cm_handler = cma_ib_handler;
/*
* Protect against the user destroying conn_id from another thread
* until we're done accessing it.
*/
atomic_inc(&conn_id->refcount);
ret = conn_id->id.event_handler(&conn_id->id, &event);
if (ret)
goto err3;
if (is_iboe) {
if (ib_event->param.req_rcvd.primary_path != NULL)
rdma_addr_find_smac_by_sgid(
&ib_event->param.req_rcvd.primary_path->sgid,
psmac, NULL);
else
psmac = NULL;
if (ib_event->param.req_rcvd.alternate_path != NULL)
rdma_addr_find_smac_by_sgid(
&ib_event->param.req_rcvd.alternate_path->sgid,
palt_smac, NULL);
else
palt_smac = NULL;
}
/*
* Acquire mutex to prevent user executing rdma_destroy_id()
* while we're accessing the cm_id.
*/
mutex_lock(&lock);
if (is_iboe)
ib_update_cm_av(cm_id, psmac, palt_smac);
if (cma_comp(conn_id, RDMA_CM_CONNECT) &&
(conn_id->id.qp_type != IB_QPT_UD))
ib_send_cm_mra(cm_id, CMA_CM_MRA_SETTING, NULL, 0);
mutex_unlock(&lock);
mutex_unlock(&conn_id->handler_mutex);
mutex_unlock(&listen_id->handler_mutex);
cma_deref_id(conn_id);
return 0;
err3:
cma_deref_id(conn_id);
/* Destroy the CM ID by returning a non-zero value. */
conn_id->cm_id.ib = NULL;
err2:
cma_exch(conn_id, RDMA_CM_DESTROYING);
mutex_unlock(&conn_id->handler_mutex);
err1:
mutex_unlock(&listen_id->handler_mutex);
if (conn_id)
rdma_destroy_id(&conn_id->id);
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The cma_req_handler function in drivers/infiniband/core/cma.c in the Linux kernel 3.14.x through 3.14.1 attempts to resolve an RDMA over Converged Ethernet (aka RoCE) address that is properly resolved within a different module, which allows remote attackers to cause a denial of service (incorrect pointer dereference and system crash) via crafted network traffic.
Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler
The code that resolves the passive side source MAC within the rdma_cm
connection request handler was both redundant and buggy, so remove it.
It was redundant since later, when an RC QP is modified to RTR state,
the resolution will take place in the ib_core module. It was buggy
because this callback also deals with UD SIDR exchange, for which we
incorrectly looked at the REQ member of the CM event and dereferenced
a random value.
Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures")
Signed-off-by: Moni Shoua <[email protected]>
Signed-off-by: Or Gerlitz <[email protected]>
Signed-off-by: Roland Dreier <[email protected]> | Medium | 166,390 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static NTSTATUS do_connect(TALLOC_CTX *ctx,
const char *server,
const char *share,
const struct user_auth_info *auth_info,
bool show_sessetup,
bool force_encrypt,
int max_protocol,
int port,
int name_type,
struct cli_state **pcli)
{
struct cli_state *c = NULL;
char *servicename;
char *sharename;
char *newserver, *newshare;
const char *username;
const char *password;
const char *domain;
NTSTATUS status;
int flags = 0;
/* make a copy so we don't modify the global string 'service' */
servicename = talloc_strdup(ctx,share);
sharename += 2;
if (server == NULL) {
server = sharename;
}
sharename = strchr_m(sharename,'\\');
if (!sharename) {
return NT_STATUS_NO_MEMORY;
}
*sharename = 0;
sharename++;
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Samba 3.x and 4.x before 4.1.22, 4.2.x before 4.2.7, and 4.3.x before 4.3.3 supports connections that are encrypted but unsigned, which allows man-in-the-middle attackers to conduct encrypted-to-unencrypted downgrade attacks by modifying the client-server data stream, related to clidfs.c, libsmb_server.c, and smbXcli_base.c.
Commit Message: | Medium | 164,676 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void PrintWebViewHelper::OnPrintPages() {
blink::WebLocalFrame* frame;
if (!GetPrintFrame(&frame))
return;
auto plugin = delegate_->GetPdfElement(frame);
Print(frame, plugin, false);
}
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} | High | 171,875 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: DECLAREwriteFunc(writeBufferToContigTiles)
{
uint32 imagew = TIFFScanlineSize(out);
uint32 tilew = TIFFTileRowSize(out);
int iskew = imagew - tilew;
tsize_t tilesize = TIFFTileSize(out);
tdata_t obuf;
uint8* bufp = (uint8*) buf;
uint32 tl, tw;
uint32 row;
(void) spp;
obuf = _TIFFmalloc(TIFFTileSize(out));
if (obuf == NULL)
return 0;
_TIFFmemset(obuf, 0, tilesize);
(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
for (row = 0; row < imagelength; row += tilelength) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth; col += tw) {
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew > imagew) {
uint32 width = imagew - colb;
int oskew = tilew - width;
cpStripToTile(obuf, bufp + colb, nrow, width,
oskew, oskew + iskew);
} else
cpStripToTile(obuf, bufp + colb, nrow, tilew,
0, iskew);
if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write tile at %lu %lu",
(unsigned long) col,
(unsigned long) row);
_TIFFfree(obuf);
return 0;
}
colb += tilew;
}
bufp += nrow * imagew;
}
_TIFFfree(obuf);
return 1;
}
Vulnerability Type: Overflow
CWE ID: CWE-787
Summary: tools/tiffcp.c in libtiff 4.0.6 has an out-of-bounds write on tiled images with odd tile width versus image width. Reported as MSVR 35103, aka *cpStripToTile heap-buffer-overflow.*
Commit Message: * tools/tiffcp.c: fix out-of-bounds write on tiled images with odd
tile width vs image width. Reported as MSVR 35103
by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team. | High | 166,863 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int xfrm6_tunnel_rcv(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
__be32 spi;
spi = xfrm6_tunnel_spi_lookup((xfrm_address_t *)&iph->saddr);
return xfrm6_rcv_spi(skb, spi);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Double free vulnerability in the xfrm6_tunnel_rcv function in net/ipv6/xfrm6_tunnel.c in the Linux kernel before 2.6.22, when the xfrm6_tunnel module is enabled, allows remote attackers to cause a denial of service (panic) via crafted IPv6 packets.
Commit Message: [IPV6]: Fix slab corruption running ip6sic
From: Eric Sesterhenn <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Medium | 165,622 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: virtual void TearDown() {
delete[] src_;
delete[] ref_;
libvpx_test::ClearSystemState();
}
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
| High | 174,591 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.