
project
stringclasses 765
values | commit_id
stringlengths 6
81
| func
stringlengths 19
482k
| vul
int64 0
1
| CVE ID
stringlengths 13
16
| CWE ID
stringclasses 13
values | CWE Name
stringclasses 13
values | CWE Description
stringclasses 13
values | Potential Mitigation
stringclasses 11
values | __index_level_0__
int64 0
23.9k
|
---|---|---|---|---|---|---|---|---|---|
poppler | a9b8ab4657dec65b8b86c225d12c533ad7e984e2 | void Splash::strokeWide(SplashPath *path, SplashCoord w) {
SplashPath *path2;
path2 = makeStrokePath(path, w, gFalse);
fillWithPattern(path2, gFalse, state->strokePattern, state->strokeAlpha);
delete path2;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,137 |
linux | ea04efee7635c9120d015dcdeeeb6988130cb67a | ims_pcu_get_cdc_union_desc(struct usb_interface *intf)
{
const void *buf = intf->altsetting->extra;
size_t buflen = intf->altsetting->extralen;
struct usb_cdc_union_desc *union_desc;
if (!buf) {
dev_err(&intf->dev, "Missing descriptor data\n");
return NULL;
}
if (!buflen) {
dev_err(&intf->dev, "Zero length descriptor\n");
return NULL;
}
while (buflen >= sizeof(*union_desc)) {
union_desc = (struct usb_cdc_union_desc *)buf;
if (union_desc->bLength > buflen) {
dev_err(&intf->dev, "Too large descriptor\n");
return NULL;
}
if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&
union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {
dev_dbg(&intf->dev, "Found union header\n");
if (union_desc->bLength >= sizeof(*union_desc))
return union_desc;
dev_err(&intf->dev,
"Union descriptor to short (%d vs %zd\n)",
union_desc->bLength, sizeof(*union_desc));
return NULL;
}
buflen -= union_desc->bLength;
buf += union_desc->bLength;
}
dev_err(&intf->dev, "Missing CDC union descriptor\n");
return NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,065 |
libevt | 444ca3ce7853538c577e0ec3f6146d2d65780734 | int libevt_record_values_read_element_data(
libevt_io_handle_t *io_handle,
libbfio_handle_t *file_io_handle,
libfdata_list_element_t *element,
libfcache_cache_t *cache,
int element_file_index LIBEVT_ATTRIBUTE_UNUSED,
off64_t element_offset,
size64_t element_size LIBEVT_ATTRIBUTE_UNUSED,
uint32_t element_flags LIBEVT_ATTRIBUTE_UNUSED,
uint8_t read_flags LIBEVT_ATTRIBUTE_UNUSED,
libcerror_error_t **error )
{
libevt_record_values_t *record_values = NULL;
static char *function = "libevt_record_values_read_element_data";
off64_t file_offset = 0;
ssize_t read_count = 0;
LIBEVT_UNREFERENCED_PARAMETER( element_size )
LIBEVT_UNREFERENCED_PARAMETER( element_file_index )
LIBEVT_UNREFERENCED_PARAMETER( element_flags )
LIBEVT_UNREFERENCED_PARAMETER( read_flags )
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: reading record at offset: %" PRIi64 " (0x%08" PRIx64 ")\n",
function,
element_offset,
element_offset );
}
#endif
if( libbfio_handle_seek_offset(
file_io_handle,
element_offset,
SEEK_SET,
error ) == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_SEEK_FAILED,
"%s: unable to seek record offset: %" PRIi64 ".",
function,
element_offset );
goto on_error;
}
if( libevt_record_values_initialize(
&record_values,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create record values.",
function );
goto on_error;
}
/* File offset must be before being passed to libevt_record_values_read
*/
file_offset = element_offset;
read_count = libevt_record_values_read(
record_values,
file_io_handle,
io_handle,
&file_offset,
0,
error );
if( read_count == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record at offset: %" PRIi64 ".",
function,
element_offset );
goto on_error;
}
if( libfdata_list_element_set_element_value(
element,
(intptr_t *) file_io_handle,
cache,
(intptr_t *) record_values,
(int (*)(intptr_t **, libcerror_error_t **)) &libevt_record_values_free,
LIBFDATA_LIST_ELEMENT_VALUE_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set record values as element value.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values != NULL )
{
libevt_record_values_free(
&record_values,
NULL );
}
return( -1 );
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,537 |
php-src | 7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1 | SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
| 1 | CVE-2016-5770 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 2,586 |
linux | 92964c79b357efd980812c4de5c1fd2ec8bb5520 | static int netlink_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct netlink_table *table = &nl_table[sk->sk_protocol];
s32 portid = task_tgid_vnr(current);
int err;
s32 rover = -4096;
bool ok;
retry:
cond_resched();
rcu_read_lock();
ok = !__netlink_lookup(table, portid, net);
rcu_read_unlock();
if (!ok) {
/* Bind collision, search negative portid values. */
if (rover == -4096)
/* rover will be in range [S32_MIN, -4097] */
rover = S32_MIN + prandom_u32_max(-4096 - S32_MIN);
else if (rover >= -4096)
rover = -4097;
portid = rover--;
goto retry;
}
err = netlink_insert(sk, portid);
if (err == -EADDRINUSE)
goto retry;
/* If 2 threads race to autobind, that is fine. */
if (err == -EBUSY)
err = 0;
return err;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,720 |
linux | a8b0ca17b80e92faab46ee7179ba9e99ccb61233 | int handle_unaligned_access(insn_size_t instruction, struct pt_regs *regs,
struct mem_access *ma, int expected,
unsigned long address)
{
u_int rm;
int ret, index;
/*
* XXX: We can't handle mixed 16/32-bit instructions yet
*/
if (instruction_size(instruction) != 2)
return -EINVAL;
index = (instruction>>8)&15; /* 0x0F00 */
rm = regs->regs[index];
/*
* Log the unexpected fixups, and then pass them on to perf.
*
* We intentionally don't report the expected cases to perf as
* otherwise the trapped I/O case will skew the results too much
* to be useful.
*/
if (!expected) {
unaligned_fixups_notify(current, instruction, regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0,
regs, address);
}
ret = -EFAULT;
switch (instruction&0xF000) {
case 0x0000:
if (instruction==0x000B) {
/* rts */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc = regs->pr;
}
else if ((instruction&0x00FF)==0x0023) {
/* braf @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc += rm + 4;
}
else if ((instruction&0x00FF)==0x0003) {
/* bsrf @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc += rm + 4;
}
}
else {
/* mov.[bwl] to/from memory via r0+rn */
goto simple;
}
break;
case 0x1000: /* mov.l Rm,@(disp,Rn) */
goto simple;
case 0x2000: /* mov.[bwl] to memory, possibly with pre-decrement */
goto simple;
case 0x4000:
if ((instruction&0x00FF)==0x002B) {
/* jmp @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc = rm;
}
else if ((instruction&0x00FF)==0x000B) {
/* jsr @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc = rm;
}
}
else {
/* mov.[bwl] to/from memory via r0+rn */
goto simple;
}
break;
case 0x5000: /* mov.l @(disp,Rm),Rn */
goto simple;
case 0x6000: /* mov.[bwl] from memory, possibly with post-increment */
goto simple;
case 0x8000: /* bf lab, bf/s lab, bt lab, bt/s lab */
switch (instruction&0x0F00) {
case 0x0100: /* mov.w R0,@(disp,Rm) */
goto simple;
case 0x0500: /* mov.w @(disp,Rm),R0 */
goto simple;
case 0x0B00: /* bf lab - no delayslot*/
break;
case 0x0F00: /* bf/s lab */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB)
if ((regs->sr & 0x00000001) != 0)
regs->pc += 4; /* next after slot */
else
#endif
regs->pc += SH_PC_8BIT_OFFSET(instruction);
}
break;
case 0x0900: /* bt lab - no delayslot */
break;
case 0x0D00: /* bt/s lab */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB)
if ((regs->sr & 0x00000001) == 0)
regs->pc += 4; /* next after slot */
else
#endif
regs->pc += SH_PC_8BIT_OFFSET(instruction);
}
break;
}
break;
case 0xA000: /* bra label */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc += SH_PC_12BIT_OFFSET(instruction);
break;
case 0xB000: /* bsr label */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc += SH_PC_12BIT_OFFSET(instruction);
}
break;
}
return ret;
/* handle non-delay-slot instruction */
simple:
ret = handle_unaligned_ins(instruction, regs, ma);
if (ret==0)
regs->pc += instruction_size(instruction);
return ret;
}
| 1 | CVE-2011-2918 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 9,478 |
qemu | 99545751734035b76bd372c4e7215bb337428d89 | static void do_busid_cmd(ESPState *s, uint8_t busid)
{
uint32_t cmdlen;
int32_t datalen;
int lun;
SCSIDevice *current_lun;
uint8_t buf[ESP_CMDFIFO_SZ];
trace_esp_do_busid_cmd(busid);
lun = busid & 7;
cmdlen = fifo8_num_used(&s->cmdfifo);
esp_fifo_pop_buf(&s->cmdfifo, buf, cmdlen);
current_lun = scsi_device_find(&s->bus, 0, s->current_dev->id, lun);
s->current_req = scsi_req_new(current_lun, 0, lun, buf, s);
datalen = scsi_req_enqueue(s->current_req);
s->ti_size = datalen;
fifo8_reset(&s->cmdfifo);
if (datalen != 0) {
s->rregs[ESP_RSTAT] = STAT_TC;
s->rregs[ESP_RSEQ] = SEQ_CD;
s->ti_cmd = 0;
esp_set_tc(s, 0);
if (datalen > 0) {
/*
* Switch to DATA IN phase but wait until initial data xfer is
* complete before raising the command completion interrupt
*/
s->data_in_ready = false;
s->rregs[ESP_RSTAT] |= STAT_DI;
} else {
s->rregs[ESP_RSTAT] |= STAT_DO;
s->rregs[ESP_RINTR] |= INTR_BS | INTR_FC;
esp_raise_irq(s);
esp_lower_drq(s);
}
scsi_req_continue(s->current_req);
return;
}
} | 1 | CVE-2020-35504 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 6,018 |
Android | 6c327afb263837bc90760c55c6605b26161a4eb9 | WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
if (j >= MAX_REF_BUFS)
{
#ifdef __ANDROID__
ALOGE("b/25818142");
android_errorWriteLog(0x534e4554, "25818142");
#endif
ps_dpb_cmds->u1_num_of_commands = 0;
return -1;
}
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
| 1 | CVE-2017-13186 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 3,023 |
Chrome | 6a60f01228557982e6508c5919cc21fcfddf110b | void ComponentControllerImpl::OnNavigationStateChanged(
chromium::web::NavigationStateChangeDetails change,
OnNavigationStateChangedCallback callback) {}
| 1 | CVE-2016-1636 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 2,294 |
Android | c9ab2b0bb05a7e19fb057e79b36e232809d70122 | status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
| 1 | CVE-2016-0826 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 7,868 |
Chrome | d926098e2e2be270c80a5ba25ab8a611b80b8556 | void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
const base::string16& jscript,
int id,
bool notify_result,
int world_id) {
TRACE_EVENT_INSTANT0("test_tracing",
"OnJavaScriptExecuteRequestInIsolatedWorld",
TRACE_EVENT_SCOPE_THREAD);
if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
world_id > ISOLATED_WORLD_ID_MAX) {
NOTREACHED();
return;
}
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
WebScriptSource script = WebScriptSource(jscript);
JavaScriptIsolatedWorldRequest* request = new JavaScriptIsolatedWorldRequest(
id, notify_result, routing_id_, weak_factory_.GetWeakPtr());
frame_->requestExecuteScriptInIsolatedWorld(world_id, &script, 1, 0, false,
request);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,188 |
OpenSC | 03628449b75a93787eb2359412a3980365dda49b | iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY];
int rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
LOG_FUNC_CALLED(ctx);
if (pin_cmd_data->pin_type != SC_AC_CHV)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification");
sc_log(ctx, "Verify ACL(method:%X;ref:%X)", acl.method, acl.key_ref);
if (acl.method != IASECC_SCB_ALWAYS)
LOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED);
pin_cmd = *pin_cmd_data;
pin_cmd.pin1.data = (unsigned char *)"";
pin_cmd.pin1.len = 0;
rv = iasecc_chv_verify(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,642 |
Android | cc274e2abe8b2a6698a5c47d8aa4bb45f1f9538d | long Cluster::Parse(long long& pos, long& len) const {
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; // nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total)) {
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; // consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0) {
if (block_stop > cluster_stop) {
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
} else if ((total >= 0) && (block_stop > total)) {
m_element_size = total - m_element_start;
pos = total;
break;
} else if (block_stop > avail) {
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) // BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) // SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; // consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0) {
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; // defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; // defend against trucated stream
}
return 1; // no more entries
}
| 1 | CVE-2016-2464 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 6,445 |
Android | 1f24c730ab6ca5aff1e3137b340b8aeaeda4bdbc | void CameraSource::signalBufferReturned(MediaBuffer *buffer) {
ALOGV("signalBufferReturned: %p", buffer->data());
Mutex::Autolock autoLock(mLock);
for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin();
it != mFramesBeingEncoded.end(); ++it) {
if ((*it)->pointer() == buffer->data()) {
releaseOneRecordingFrame((*it));
mFramesBeingEncoded.erase(it);
++mNumFramesEncoded;
buffer->setObserver(0);
buffer->release();
mFrameCompleteCondition.signal();
return;
}
}
CHECK(!"signalBufferReturned: bogus buffer");
}
| 1 | CVE-2016-3834 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 6,215 |
libxml2 | bdd66182ef53fe1f7209ab6535fda56366bd7ac9 | xmlStringGetNodeList(const xmlDoc *doc, const xmlChar *value) {
xmlNodePtr ret = NULL, last = NULL;
xmlNodePtr node;
xmlChar *val;
const xmlChar *cur = value;
const xmlChar *q;
xmlEntityPtr ent;
xmlBufPtr buf;
if (value == NULL) return(NULL);
buf = xmlBufCreateSize(0);
if (buf == NULL) return(NULL);
xmlBufSetAllocationScheme(buf, XML_BUFFER_ALLOC_HYBRID);
q = cur;
while (*cur != 0) {
if (cur[0] == '&') {
int charval = 0;
xmlChar tmp;
/*
* Save the current text.
*/
if (cur != q) {
if (xmlBufAdd(buf, q, cur - q))
goto out;
}
q = cur;
if ((cur[1] == '#') && (cur[2] == 'x')) {
cur += 3;
tmp = *cur;
while (tmp != ';') { /* Non input consuming loop */
if ((tmp >= '0') && (tmp <= '9'))
charval = charval * 16 + (tmp - '0');
else if ((tmp >= 'a') && (tmp <= 'f'))
charval = charval * 16 + (tmp - 'a') + 10;
else if ((tmp >= 'A') && (tmp <= 'F'))
charval = charval * 16 + (tmp - 'A') + 10;
else {
xmlTreeErr(XML_TREE_INVALID_HEX, (xmlNodePtr) doc,
NULL);
charval = 0;
break;
}
cur++;
tmp = *cur;
}
if (tmp == ';')
cur++;
q = cur;
} else if (cur[1] == '#') {
cur += 2;
tmp = *cur;
while (tmp != ';') { /* Non input consuming loops */
if ((tmp >= '0') && (tmp <= '9'))
charval = charval * 10 + (tmp - '0');
else {
xmlTreeErr(XML_TREE_INVALID_DEC, (xmlNodePtr) doc,
NULL);
charval = 0;
break;
}
cur++;
tmp = *cur;
}
if (tmp == ';')
cur++;
q = cur;
} else {
/*
* Read the entity string
*/
cur++;
q = cur;
while ((*cur != 0) && (*cur != ';')) cur++;
if (*cur == 0) {
xmlTreeErr(XML_TREE_UNTERMINATED_ENTITY,
(xmlNodePtr) doc, (const char *) q);
goto out;
}
if (cur != q) {
/*
* Predefined entities don't generate nodes
*/
val = xmlStrndup(q, cur - q);
ent = xmlGetDocEntity(doc, val);
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (xmlBufCat(buf, ent->content))
goto out;
} else {
/*
* Flush buffer so far
*/
if (!xmlBufIsEmpty(buf)) {
node = xmlNewDocText(doc, NULL);
node->content = xmlBufDetach(buf);
if (last == NULL) {
last = ret = node;
} else {
last = xmlAddNextSibling(last, node);
}
}
/*
* Create a new REFERENCE_REF node
*/
node = xmlNewReference(doc, val);
if (node == NULL) {
if (val != NULL) xmlFree(val);
goto out;
}
else if ((ent != NULL) && (ent->children == NULL)) {
xmlNodePtr temp;
ent->children = xmlStringGetNodeList(doc,
(const xmlChar*)node->content);
ent->owner = 1;
temp = ent->children;
while (temp) {
temp->parent = (xmlNodePtr)ent;
temp = temp->next;
}
}
if (last == NULL) {
last = ret = node;
} else {
last = xmlAddNextSibling(last, node);
}
}
xmlFree(val);
}
cur++;
q = cur;
}
if (charval != 0) {
xmlChar buffer[10];
int len;
len = xmlCopyCharMultiByte(buffer, charval);
buffer[len] = 0;
if (xmlBufCat(buf, buffer))
goto out;
charval = 0;
}
} else
cur++;
}
if ((cur != q) || (ret == NULL)) {
/*
* Handle the last piece of text.
*/
xmlBufAdd(buf, q, cur - q);
}
if (!xmlBufIsEmpty(buf)) {
node = xmlNewDocText(doc, NULL);
node->content = xmlBufDetach(buf);
if (last == NULL) {
ret = node;
} else {
xmlAddNextSibling(last, node);
}
}
out:
xmlBufFree(buf);
return(ret);
} | 1 | CVE-2016-3627 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 1,827 |
vim | 399c297aa93afe2c0a39e2a1b3f972aebba44c9d | read_prefcond_section(FILE *fd, slang_T *lp)
{
int cnt;
int i;
int n;
char_u *p;
char_u buf[MAXWLEN + 1];
/* <prefcondcnt> <prefcond> ... */
cnt = get2c(fd); /* <prefcondcnt> */
if (cnt <= 0)
return SP_FORMERROR;
lp->sl_prefprog = (regprog_T **)alloc_clear(
(unsigned)sizeof(regprog_T *) * cnt);
if (lp->sl_prefprog == NULL)
return SP_OTHERERROR;
lp->sl_prefixcnt = cnt;
for (i = 0; i < cnt; ++i)
{
/* <prefcond> : <condlen> <condstr> */
n = getc(fd); /* <condlen> */
if (n < 0 || n >= MAXWLEN)
return SP_FORMERROR;
/* When <condlen> is zero we have an empty condition. Otherwise
* compile the regexp program used to check for the condition. */
if (n > 0)
{
buf[0] = '^'; /* always match at one position only */
p = buf + 1;
while (n-- > 0)
*p++ = getc(fd); /* <condstr> */
*p = NUL;
lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC + RE_STRING);
}
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,810 |
linux-2.6 | 9926e4c74300c4b31dee007298c6475d33369df0 | asmlinkage long sys_setrlimit(unsigned int resource, struct rlimit __user *rlim)
{
struct rlimit new_rlim, *old_rlim;
unsigned long it_prof_secs;
int retval;
if (resource >= RLIM_NLIMITS)
return -EINVAL;
if (copy_from_user(&new_rlim, rlim, sizeof(*rlim)))
return -EFAULT;
if (new_rlim.rlim_cur > new_rlim.rlim_max)
return -EINVAL;
old_rlim = current->signal->rlim + resource;
if ((new_rlim.rlim_max > old_rlim->rlim_max) &&
!capable(CAP_SYS_RESOURCE))
return -EPERM;
if (resource == RLIMIT_NOFILE && new_rlim.rlim_max > NR_OPEN)
return -EPERM;
retval = security_task_setrlimit(resource, &new_rlim);
if (retval)
return retval;
task_lock(current->group_leader);
*old_rlim = new_rlim;
task_unlock(current->group_leader);
if (resource != RLIMIT_CPU)
goto out;
/*
* RLIMIT_CPU handling. Note that the kernel fails to return an error
* code if it rejected the user's attempt to set RLIMIT_CPU. This is a
* very long-standing error, and fixing it now risks breakage of
* applications, so we live with it
*/
if (new_rlim.rlim_cur == RLIM_INFINITY)
goto out;
it_prof_secs = cputime_to_secs(current->signal->it_prof_expires);
if (it_prof_secs == 0 || new_rlim.rlim_cur <= it_prof_secs) {
unsigned long rlim_cur = new_rlim.rlim_cur;
cputime_t cputime;
if (rlim_cur == 0) {
/*
* The caller is asking for an immediate RLIMIT_CPU
* expiry. But we use the zero value to mean "it was
* never set". So let's cheat and make it one second
* instead
*/
rlim_cur = 1;
}
cputime = secs_to_cputime(rlim_cur);
read_lock(&tasklist_lock);
spin_lock_irq(¤t->sighand->siglock);
set_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL);
spin_unlock_irq(¤t->sighand->siglock);
read_unlock(&tasklist_lock);
}
out:
return 0;
} | 1 | CVE-2008-1294 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 9,096 |
gpac | 1c449a34fe0b50aaffb881bfb9d7c5ab0bb18cdd | Bool GPAC_EventProc(void *ptr, GF_Event *evt)
{
if (!term) return 0;
if (gui_mode==1) {
if (evt->type==GF_EVENT_QUIT) {
Run = 0;
} else if (evt->type==GF_EVENT_KEYDOWN) {
switch (evt->key.key_code) {
case GF_KEY_C:
if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) {
hide_shell(shell_visible ? 1 : 0);
if (shell_visible) gui_mode=2;
}
break;
default:
break;
}
}
return 0;
}
switch (evt->type) {
case GF_EVENT_DURATION:
Duration = (u64) ( 1000 * (s64) evt->duration.duration);
CanSeek = evt->duration.can_seek;
break;
case GF_EVENT_MESSAGE:
{
const char *servName;
if (!evt->message.service || !strcmp(evt->message.service, the_url)) {
servName = "";
} else if (!strnicmp(evt->message.service, "data:", 5)) {
servName = "(embedded data)";
} else {
servName = evt->message.service;
}
if (!evt->message.message) return 0;
if (evt->message.error) {
if (!is_connected) last_error = evt->message.error;
if (evt->message.error==GF_SCRIPT_INFO) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s\n", evt->message.message));
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s %s: %s\n", servName, evt->message.message, gf_error_to_string(evt->message.error)));
}
} else if (!be_quiet)
GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s %s\n", servName, evt->message.message));
}
break;
case GF_EVENT_PROGRESS:
{
char *szTitle = "";
if (evt->progress.progress_type==0) {
szTitle = "Buffer ";
if (bench_mode && (bench_mode!=3) ) {
if (evt->progress.done >= evt->progress.total) bench_buffer = 0;
else bench_buffer = 1 + 100*evt->progress.done / evt->progress.total;
break;
}
}
else if (evt->progress.progress_type==1) {
if (bench_mode) break;
szTitle = "Download ";
}
else if (evt->progress.progress_type==2) szTitle = "Import ";
gf_set_progress(szTitle, evt->progress.done, evt->progress.total);
}
break;
case GF_EVENT_DBLCLICK:
gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN));
return 0;
case GF_EVENT_MOUSEDOWN:
if (evt->mouse.button==GF_MOUSE_RIGHT) {
right_down = 1;
last_x = evt->mouse.x;
last_y = evt->mouse.y;
}
return 0;
case GF_EVENT_MOUSEUP:
if (evt->mouse.button==GF_MOUSE_RIGHT) {
right_down = 0;
last_x = evt->mouse.x;
last_y = evt->mouse.y;
}
return 0;
case GF_EVENT_MOUSEMOVE:
if (right_down && (user.init_flags & GF_TERM_WINDOWLESS) ) {
GF_Event move;
move.move.x = evt->mouse.x - last_x;
move.move.y = last_y-evt->mouse.y;
move.type = GF_EVENT_MOVE;
move.move.relative = 1;
gf_term_user_event(term, &move);
}
return 0;
case GF_EVENT_KEYUP:
switch (evt->key.key_code) {
case GF_KEY_SPACE:
if (evt->key.flags & GF_KEY_MOD_CTRL) switch_bench(!bench_mode);
break;
}
break;
case GF_EVENT_KEYDOWN:
gf_term_process_shortcut(term, evt);
switch (evt->key.key_code) {
case GF_KEY_SPACE:
if (evt->key.flags & GF_KEY_MOD_CTRL) {
/*ignore key repeat*/
if (!bench_mode) switch_bench(!bench_mode);
}
break;
case GF_KEY_PAGEDOWN:
case GF_KEY_MEDIANEXTTRACK:
request_next_playlist_item = 1;
break;
case GF_KEY_MEDIAPREVIOUSTRACK:
break;
case GF_KEY_ESCAPE:
gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN));
break;
case GF_KEY_C:
if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) {
hide_shell(shell_visible ? 1 : 0);
if (!shell_visible) gui_mode=1;
}
break;
case GF_KEY_F:
if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Rendering rate: %f FPS\n", gf_term_get_framerate(term, 0));
break;
case GF_KEY_T:
if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Scene Time: %f \n", gf_term_get_time_in_ms(term)/1000.0);
break;
case GF_KEY_D:
if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_DRAW_MODE, (gf_term_get_option(term, GF_OPT_DRAW_MODE)==GF_DRAW_MODE_DEFER) ? GF_DRAW_MODE_IMMEDIATE : GF_DRAW_MODE_DEFER );
break;
case GF_KEY_4:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3);
break;
case GF_KEY_5:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9);
break;
case GF_KEY_6:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN);
break;
case GF_KEY_7:
if (evt->key.flags & GF_KEY_MOD_CTRL)
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP);
break;
case GF_KEY_O:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
if (gf_term_get_option(term, GF_OPT_MAIN_ADDON)) {
fprintf(stderr, "Resuming to main content\n");
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE);
} else {
fprintf(stderr, "Main addon not enabled\n");
}
}
break;
case GF_KEY_P:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
u32 pause_state = gf_term_get_option(term, GF_OPT_PLAY_STATE) ;
fprintf(stderr, "[Status: %s]\n", pause_state ? "Playing" : "Paused");
if ((pause_state == GF_STATE_PAUSED) && (evt->key.flags & GF_KEY_MOD_SHIFT)) {
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE);
} else {
gf_term_set_option(term, GF_OPT_PLAY_STATE, (pause_state==GF_STATE_PAUSED) ? GF_STATE_PLAYING : GF_STATE_PAUSED);
}
}
break;
case GF_KEY_S:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE);
fprintf(stderr, "Step time: ");
PrintTime(gf_term_get_time_in_ms(term));
fprintf(stderr, "\n");
}
break;
case GF_KEY_B:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected)
ViewODs(term, 1);
break;
case GF_KEY_M:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected)
ViewODs(term, 0);
break;
case GF_KEY_H:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
gf_term_switch_quality(term, 1);
}
break;
case GF_KEY_L:
if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) {
gf_term_switch_quality(term, 0);
}
break;
case GF_KEY_F5:
if (is_connected)
reload = 1;
break;
case GF_KEY_A:
addon_visible = !addon_visible;
gf_term_toggle_addons(term, addon_visible);
break;
case GF_KEY_UP:
if ((evt->key.flags & VK_MOD) && is_connected) {
do_set_speed(playback_speed * 2);
}
break;
case GF_KEY_DOWN:
if ((evt->key.flags & VK_MOD) && is_connected) {
do_set_speed(playback_speed / 2);
}
break;
case GF_KEY_LEFT:
if ((evt->key.flags & VK_MOD) && is_connected) {
do_set_speed(-1 * playback_speed );
}
break;
}
break;
case GF_EVENT_CONNECT:
if (evt->connect.is_connected) {
is_connected = 1;
fprintf(stderr, "Service Connected\n");
eos_seen = GF_FALSE;
if (playback_speed != FIX_ONE)
gf_term_set_speed(term, playback_speed);
} else if (is_connected) {
fprintf(stderr, "Service %s\n", is_connected ? "Disconnected" : "Connection Failed");
is_connected = 0;
Duration = 0;
}
if (init_w && init_h) {
gf_term_set_size(term, init_w, init_h);
}
ResetCaption();
break;
case GF_EVENT_EOS:
eos_seen = GF_TRUE;
if (playlist) {
if (Duration>1500)
request_next_playlist_item = GF_TRUE;
}
else if (loop_at_end) {
restart = 1;
}
break;
case GF_EVENT_SIZE:
if (user.init_flags & GF_TERM_WINDOWLESS) {
GF_Event move;
move.type = GF_EVENT_MOVE;
move.move.align_x = align_mode & 0xFF;
move.move.align_y = (align_mode>>8) & 0xFF;
move.move.relative = 2;
gf_term_user_event(term, &move);
}
break;
case GF_EVENT_SCENE_SIZE:
if (forced_width && forced_height) {
GF_Event size;
size.type = GF_EVENT_SIZE;
size.size.width = forced_width;
size.size.height = forced_height;
gf_term_user_event(term, &size);
}
break;
case GF_EVENT_METADATA:
ResetCaption();
break;
case GF_EVENT_RELOAD:
if (is_connected)
reload = 1;
break;
case GF_EVENT_DROPFILE:
{
u32 i, pos;
/*todo - force playlist mode*/
if (readonly_playlist) {
gf_fclose(playlist);
playlist = NULL;
}
readonly_playlist = 0;
if (!playlist) {
readonly_playlist = 0;
playlist = gf_temp_file_new(NULL);
}
pos = ftell(playlist);
i=0;
while (i<evt->open_file.nb_files) {
if (evt->open_file.files[i] != NULL) {
fprintf(playlist, "%s\n", evt->open_file.files[i]);
}
i++;
}
fseek(playlist, pos, SEEK_SET);
request_next_playlist_item = 1;
}
return 1;
case GF_EVENT_QUIT:
if (evt->message.error) {
fprintf(stderr, "A fatal error was encoutered: %s (%s) - exiting ...\n", evt->message.message ? evt->message.message : "no details", gf_error_to_string(evt->message.error) );
}
Run = 0;
break;
case GF_EVENT_DISCONNECT:
gf_term_disconnect(term);
break;
case GF_EVENT_MIGRATE:
{
}
break;
case GF_EVENT_NAVIGATE_INFO:
if (evt->navigate.to_url) fprintf(stderr, "Go to URL: \"%s\"\r", evt->navigate.to_url);
break;
case GF_EVENT_NAVIGATE:
if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, no_mime_check)) {
strncpy(the_url, evt->navigate.to_url, sizeof(the_url)-1);
the_url[sizeof(the_url) - 1] = 0;
fprintf(stderr, "Navigating to URL %s\n", the_url);
gf_term_navigate_to(term, evt->navigate.to_url);
return 1;
} else {
fprintf(stderr, "Navigation destination not supported\nGo to URL: %s\n", evt->navigate.to_url);
}
break;
case GF_EVENT_SET_CAPTION:
gf_term_user_event(term, evt);
break;
case GF_EVENT_AUTHORIZATION:
{
int maxTries = 1;
assert( evt->type == GF_EVENT_AUTHORIZATION);
assert( evt->auth.user);
assert( evt->auth.password);
assert( evt->auth.site_url);
while ((!strlen(evt->auth.user) || !strlen(evt->auth.password)) && (maxTries--) >= 0) {
fprintf(stderr, "**** Authorization required for site %s ****\n", evt->auth.site_url);
fprintf(stderr, "login : ");
read_line_input(evt->auth.user, 50, 1);
fprintf(stderr, "\npassword: ");
read_line_input(evt->auth.password, 50, 0);
fprintf(stderr, "*********\n");
}
if (maxTries < 0) {
fprintf(stderr, "**** No User or password has been filled, aborting ***\n");
return 0;
}
return 1;
}
case GF_EVENT_ADDON_DETECTED:
if (enable_add_ons) {
fprintf(stderr, "Media Addon %s detected - enabling it\n", evt->addon_connect.addon_url);
addon_visible = 1;
}
return enable_add_ons;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,002 |
spice-vd_agent | b7db1c20c9f80154fb54392eb44add3486d3e427 | static void do_client_file_xfer(VirtioPort *vport,
VDAgentMessage *message_header,
uint8_t *data)
{
uint32_t msg_type, id;
UdscsConnection *conn;
switch (message_header->type) {
case VD_AGENT_FILE_XFER_START: {
VDAgentFileXferStartMessage *s = (VDAgentFileXferStartMessage *)data;
if (!active_session_conn) {
send_file_xfer_status(vport,
"Could not find an agent connection belonging to the "
"active session, cancelling client file-xfer request %u",
s->id, VD_AGENT_FILE_XFER_STATUS_VDAGENT_NOT_CONNECTED, NULL, 0);
return;
} else if (session_info_session_is_locked(session_info)) {
syslog(LOG_DEBUG, "Session is locked, skipping file-xfer-start");
send_file_xfer_status(vport,
"User's session is locked and cannot start file transfer. "
"Cancelling client file-xfer request %u",
s->id, VD_AGENT_FILE_XFER_STATUS_SESSION_LOCKED, NULL, 0);
return;
} else if (g_hash_table_size(active_xfers) >= MAX_ACTIVE_TRANSFERS) {
VDAgentFileXferStatusError error = {
GUINT32_TO_LE(VD_AGENT_FILE_XFER_STATUS_ERROR_GLIB_IO),
GUINT32_TO_LE(G_IO_ERROR_TOO_MANY_OPEN_FILES),
};
size_t detail_size = sizeof(error);
if (!VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size,
VD_AGENT_CAP_FILE_XFER_DETAILED_ERRORS)) {
detail_size = 0;
}
send_file_xfer_status(vport,
"Too many transfers ongoing. "
"Cancelling client file-xfer request %u",
s->id, VD_AGENT_FILE_XFER_STATUS_ERROR, (void*) &error, detail_size);
return;
}
msg_type = VDAGENTD_FILE_XFER_START;
id = s->id;
// associate the id with the active connection
g_hash_table_insert(active_xfers, GUINT_TO_POINTER(id), active_session_conn);
break;
}
case VD_AGENT_FILE_XFER_STATUS: {
VDAgentFileXferStatusMessage *s = (VDAgentFileXferStatusMessage *)data;
msg_type = VDAGENTD_FILE_XFER_STATUS;
id = s->id;
break;
}
case VD_AGENT_FILE_XFER_DATA: {
VDAgentFileXferDataMessage *d = (VDAgentFileXferDataMessage *)data;
msg_type = VDAGENTD_FILE_XFER_DATA;
id = d->id;
break;
}
default:
g_return_if_reached(); /* quiet uninitialized variable warning */
}
conn = g_hash_table_lookup(active_xfers, GUINT_TO_POINTER(id));
if (!conn) {
if (debug)
syslog(LOG_DEBUG, "Could not find file-xfer %u (cancelled?)", id);
return;
}
udscs_write(conn, msg_type, 0, 0, data, message_header->size);
// client told that transfer is ended, agents too stop the transfer
// and release resources
if (message_header->type == VD_AGENT_FILE_XFER_STATUS) {
g_hash_table_remove(active_xfers, GUINT_TO_POINTER(id));
}
} | 1 | CVE-2020-25651 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 8,312 |
mapserver | 3a10f6b829297dae63492a8c63385044bc6953ed | char *msPostGISBuildSQL(layerObj *layer, rectObj *rect, long *uid)
{
msPostGISLayerInfo *layerinfo = 0;
char *strFrom = 0;
char *strItems = 0;
char *strWhere = 0;
char *strSQL = 0;
static char *strSQLTemplate0 = "select %s from %s where %s";
static char *strSQLTemplate1 = "select %s from %s%s";
char *strSQLTemplate = 0;
if (layer->debug) {
msDebug("msPostGISBuildSQL called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
strItems = msPostGISBuildSQLItems(layer);
if ( ! strItems ) {
msSetError(MS_MISCERR, "Failed to build SQL items.", "msPostGISBuildSQL()");
return NULL;
}
strFrom = msPostGISBuildSQLFrom(layer, rect);
if ( ! strFrom ) {
msSetError(MS_MISCERR, "Failed to build SQL 'from'.", "msPostGISBuildSQL()");
return NULL;
}
/* If there's BOX hackery going on, we don't want to append a box index test at
the end of the query, the user is going to be responsible for making things
work with their hackery. */
if ( strstr(layerinfo->fromsource, BOXTOKEN) )
strWhere = msPostGISBuildSQLWhere(layer, NULL, uid);
else
strWhere = msPostGISBuildSQLWhere(layer, rect, uid);
if ( ! strWhere ) {
msSetError(MS_MISCERR, "Failed to build SQL 'where'.", "msPostGISBuildSQL()");
return NULL;
}
strSQLTemplate = strlen(strWhere) ? strSQLTemplate0 : strSQLTemplate1;
strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere));
sprintf(strSQL, strSQLTemplate, strItems, strFrom, strWhere);
if (strItems) free(strItems);
if (strFrom) free(strFrom);
if (strWhere) free(strWhere);
return strSQL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,251 |
linux | 47abea041f897d64dbd5777f0cf7745148f85d75 | int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
{
struct io_cancel *cancel = io_kiocb_to_cmd(req, struct io_cancel);
struct io_cancel_data cd = {
.ctx = req->ctx,
.data = cancel->addr,
.flags = cancel->flags,
.seq = atomic_inc_return(&req->ctx->cancel_seq),
};
struct io_uring_task *tctx = req->task->io_uring;
int ret;
if (cd.flags & IORING_ASYNC_CANCEL_FD) {
if (req->flags & REQ_F_FIXED_FILE ||
cd.flags & IORING_ASYNC_CANCEL_FD_FIXED) {
req->flags |= REQ_F_FIXED_FILE;
req->file = io_file_get_fixed(req, cancel->fd,
issue_flags);
} else {
req->file = io_file_get_normal(req, cancel->fd);
}
if (!req->file) {
ret = -EBADF;
goto done;
}
cd.file = req->file;
}
ret = __io_async_cancel(&cd, tctx, issue_flags);
done:
if (ret < 0)
req_set_fail(req);
io_req_set_res(req, ret, 0);
return IOU_OK;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,457 |
miniupnp | 13585f15c7f7dc28bbbba1661efb280d530d114c | GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
| 1 | CVE-2019-12109 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 1,060 |
openssl | cfd40fd39e69f5e3c654ae8fbf9acb1d2a051144 | void dtls1_reset_seq_numbers(SSL *s, int rw)
{
unsigned char *seq;
unsigned int seq_bytes = sizeof(s->s3->read_sequence);
if (rw & SSL3_CC_READ) {
seq = s->s3->read_sequence;
s->d1->r_epoch++;
memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
} else {
seq = s->s3->write_sequence;
memcpy(s->d1->last_write_sequence, seq,
sizeof(s->s3->write_sequence));
s->d1->w_epoch++;
}
memset(seq, 0x00, seq_bytes);
} | 1 | CVE-2016-2179 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 9,721 |
linux | 65d8fc777f6dcfee12785c057a6b57f679641c90 | static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
ktime_t *abs_time, u32 bitset)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct restart_block *restart;
struct futex_hash_bucket *hb;
struct futex_q q = futex_q_init;
int ret;
if (!bitset)
return -EINVAL;
q.bitset = bitset;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
CLOCK_REALTIME : CLOCK_MONOTONIC,
HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
retry:
/*
* Prepare to wait on uaddr. On success, holds hb lock and increments
* q.key refs.
*/
ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
if (ret)
goto out;
/* queue_me and wait for wakeup, timeout, or a signal. */
futex_wait_queue_me(hb, &q, to);
/* If we were woken (and unqueued), we succeeded, whatever. */
ret = 0;
/* unqueue_me() drops q.key ref */
if (!unqueue_me(&q))
goto out;
ret = -ETIMEDOUT;
if (to && !to->task)
goto out;
/*
* We expect signal_pending(current), but we might be the
* victim of a spurious wakeup as well.
*/
if (!signal_pending(current))
goto retry;
ret = -ERESTARTSYS;
if (!abs_time)
goto out;
restart = ¤t->restart_block;
restart->fn = futex_wait_restart;
restart->futex.uaddr = uaddr;
restart->futex.val = val;
restart->futex.time = abs_time->tv64;
restart->futex.bitset = bitset;
restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
ret = -ERESTART_RESTARTBLOCK;
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,324 |
Chrome | 6d2aef28cb0b677af468ebf3e32a176a7c37086e | void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) {
DCHECK(message_loop()->BelongsToCurrentThread());
if (!stream_id_)
return;
if (state == AudioOutputIPCDelegate::kError) {
DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)";
base::AutoLock auto_lock_(audio_thread_lock_);
if (audio_thread_.get() && !audio_thread_->IsStopped())
callback_->OnRenderError();
}
}
| 1 | CVE-2012-5108 | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently. | Phase: Architecture and Design
In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.
Phase: Architecture and Design
Use thread-safe capabilities such as the data access abstraction in Spring.
Phase: Architecture and Design
Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring.
Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).
Phase: Implementation
When using multithreading and operating on shared variables, only use thread-safe functions.
Phase: Implementation
Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.
Phase: Implementation
Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.
Phase: Implementation
Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.
Phase: Implementation
Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.
Phase: Implementation
Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help.
Phases: Architecture and Design; Operation
Strategy: Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations | 7,443 |
linux | 363b02dab09b3226f3bd1420dad9c72b79a42a76 | int key_update(key_ref_t key_ref, const void *payload, size_t plen)
{
struct key_preparsed_payload prep;
struct key *key = key_ref_to_ptr(key_ref);
int ret;
key_check(key);
/* the key must be writable */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
return ret;
/* attempt to update it if supported */
if (!key->type->update)
return -EOPNOTSUPP;
memset(&prep, 0, sizeof(prep));
prep.data = payload;
prep.datalen = plen;
prep.quotalen = key->type->def_datalen;
prep.expiry = TIME_T_MAX;
if (key->type->preparse) {
ret = key->type->preparse(&prep);
if (ret < 0)
goto error;
}
down_write(&key->sem);
ret = key->type->update(key, &prep);
if (ret == 0)
/* updating a negative key instantiates it */
clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
up_write(&key->sem);
error:
if (key->type->preparse)
key->type->free_preparse(&prep);
return ret;
}
| 1 | CVE-2017-15951 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 1,945 |
linux | 497de07d89c1410d76a15bec2bb41f24a2a89f31 | static void posix_acl_fix_xattr_userns(
struct user_namespace *to, struct user_namespace *from,
void *value, size_t size)
{
struct posix_acl_xattr_header *header = value;
struct posix_acl_xattr_entry *entry = (void *)(header + 1), *end;
int count;
kuid_t uid;
kgid_t gid;
if (!value)
return;
if (size < sizeof(struct posix_acl_xattr_header))
return;
if (header->a_version != cpu_to_le32(POSIX_ACL_XATTR_VERSION))
return;
count = posix_acl_xattr_count(size);
if (count < 0)
return;
if (count == 0)
return;
for (end = entry + count; entry != end; entry++) {
switch(le16_to_cpu(entry->e_tag)) {
case ACL_USER:
uid = make_kuid(from, le32_to_cpu(entry->e_id));
entry->e_id = cpu_to_le32(from_kuid(to, uid));
break;
case ACL_GROUP:
gid = make_kgid(from, le32_to_cpu(entry->e_id));
entry->e_id = cpu_to_le32(from_kgid(to, gid));
break;
default:
break;
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,943 |
vim | 4bf1006cae7e87259ccd5219128c3dba75774441 | get_function_body(
exarg_T *eap,
garray_T *newlines,
char_u *line_arg_in,
char_u **line_to_free)
{
linenr_T sourcing_lnum_top = SOURCING_LNUM;
linenr_T sourcing_lnum_off;
int saved_wait_return = need_wait_return;
char_u *line_arg = line_arg_in;
int vim9_function = eap->cmdidx == CMD_def
|| eap->cmdidx == CMD_block;
#define MAX_FUNC_NESTING 50
char nesting_def[MAX_FUNC_NESTING];
char nesting_inline[MAX_FUNC_NESTING];
int nesting = 0;
getline_opt_T getline_options;
int indent = 2;
char_u *skip_until = NULL;
int ret = FAIL;
int is_heredoc = FALSE;
int heredoc_concat_len = 0;
garray_T heredoc_ga;
char_u *heredoc_trimmed = NULL;
ga_init2(&heredoc_ga, 1, 500);
// Detect having skipped over comment lines to find the return
// type. Add NULL lines to keep the line count correct.
sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie);
if (SOURCING_LNUM < sourcing_lnum_off)
{
sourcing_lnum_off -= SOURCING_LNUM;
if (ga_grow(newlines, sourcing_lnum_off) == FAIL)
goto theend;
while (sourcing_lnum_off-- > 0)
((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL;
}
nesting_def[0] = vim9_function;
nesting_inline[0] = eap->cmdidx == CMD_block;
getline_options = vim9_function
? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT;
for (;;)
{
char_u *theline;
char_u *p;
char_u *arg;
if (KeyTyped)
{
msg_scroll = TRUE;
saved_wait_return = FALSE;
}
need_wait_return = FALSE;
if (line_arg != NULL)
{
// Use eap->arg, split up in parts by line breaks.
theline = line_arg;
p = vim_strchr(theline, '\n');
if (p == NULL)
line_arg += STRLEN(line_arg);
else
{
*p = NUL;
line_arg = p + 1;
}
}
else
{
if (eap->getline == NULL)
theline = getcmdline(':', 0L, indent, getline_options);
else
theline = eap->getline(':', eap->cookie, indent,
getline_options);
if (*eap->cmdlinep == *line_to_free)
*eap->cmdlinep = theline;
vim_free(*line_to_free);
*line_to_free = theline;
}
if (KeyTyped)
lines_left = Rows - 1;
if (theline == NULL)
{
// Use the start of the function for the line number.
SOURCING_LNUM = sourcing_lnum_top;
if (skip_until != NULL)
semsg(_(e_missing_heredoc_end_marker_str), skip_until);
else if (nesting_inline[nesting])
emsg(_(e_missing_end_block));
else if (eap->cmdidx == CMD_def)
emsg(_(e_missing_enddef));
else
emsg(_(e_missing_endfunction));
goto theend;
}
// Detect line continuation: SOURCING_LNUM increased more than one.
sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie);
if (SOURCING_LNUM < sourcing_lnum_off)
sourcing_lnum_off -= SOURCING_LNUM;
else
sourcing_lnum_off = 0;
if (skip_until != NULL)
{
// Don't check for ":endfunc"/":enddef" between
// * ":append" and "."
// * ":python <<EOF" and "EOF"
// * ":let {var-name} =<< [trim] {marker}" and "{marker}"
if (heredoc_trimmed == NULL
|| (is_heredoc && skipwhite(theline) == theline)
|| STRNCMP(theline, heredoc_trimmed,
STRLEN(heredoc_trimmed)) == 0)
{
if (heredoc_trimmed == NULL)
p = theline;
else if (is_heredoc)
p = skipwhite(theline) == theline
? theline : theline + STRLEN(heredoc_trimmed);
else
p = theline + STRLEN(heredoc_trimmed);
if (STRCMP(p, skip_until) == 0)
{
VIM_CLEAR(skip_until);
VIM_CLEAR(heredoc_trimmed);
getline_options = vim9_function
? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT;
is_heredoc = FALSE;
if (heredoc_concat_len > 0)
{
// Replace the starting line with all the concatenated
// lines.
ga_concat(&heredoc_ga, theline);
vim_free(((char_u **)(newlines->ga_data))[
heredoc_concat_len - 1]);
((char_u **)(newlines->ga_data))[
heredoc_concat_len - 1] = heredoc_ga.ga_data;
ga_init(&heredoc_ga);
heredoc_concat_len = 0;
theline += STRLEN(theline); // skip the "EOF"
}
}
}
}
else
{
int c;
char_u *end;
// skip ':' and blanks
for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)
;
// Check for "endfunction", "enddef" or "}".
// When a ":" follows it must be a dict key; "enddef: value,"
if (nesting_inline[nesting]
? *p == '}'
: (checkforcmd(&p, nesting_def[nesting]
? "enddef" : "endfunction", 4)
&& *p != ':'))
{
if (nesting-- == 0)
{
char_u *nextcmd = NULL;
if (*p == '|' || *p == '}')
nextcmd = p + 1;
else if (line_arg != NULL && *skipwhite(line_arg) != NUL)
nextcmd = line_arg;
else if (*p != NUL && *p != (vim9_function ? '#' : '"')
&& (vim9_function || p_verbose > 0))
{
SOURCING_LNUM = sourcing_lnum_top
+ newlines->ga_len + 1;
if (eap->cmdidx == CMD_def)
semsg(_(e_text_found_after_enddef_str), p);
else
give_warning2((char_u *)
_("W22: Text found after :endfunction: %s"),
p, TRUE);
}
if (nextcmd != NULL && *skipwhite(nextcmd) != NUL)
{
// Another command follows. If the line came from "eap"
// we can simply point into it, otherwise we need to
// change "eap->cmdlinep".
eap->nextcmd = nextcmd;
if (*line_to_free != NULL
&& *eap->cmdlinep != *line_to_free)
{
vim_free(*eap->cmdlinep);
*eap->cmdlinep = *line_to_free;
*line_to_free = NULL;
}
}
break;
}
}
// Check for mismatched "endfunc" or "enddef".
// We don't check for "def" inside "func" thus we also can't check
// for "enddef".
// We continue to find the end of the function, although we might
// not find it.
else if (nesting_def[nesting])
{
if (checkforcmd(&p, "endfunction", 4) && *p != ':')
emsg(_(e_mismatched_endfunction));
}
else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4))
emsg(_(e_mismatched_enddef));
// Increase indent inside "if", "while", "for" and "try", decrease
// at "end".
if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0))
indent -= 2;
else if (STRNCMP(p, "if", 2) == 0
|| STRNCMP(p, "wh", 2) == 0
|| STRNCMP(p, "for", 3) == 0
|| STRNCMP(p, "try", 3) == 0)
indent += 2;
// Check for defining a function inside this function.
// Only recognize "def" inside "def", not inside "function",
// For backwards compatibility, see Test_function_python().
c = *p;
if (is_function_cmd(&p)
|| (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3)))
{
if (*p == '!')
p = skipwhite(p + 1);
p += eval_fname_script(p);
vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL,
NULL, NULL));
if (*skipwhite(p) == '(')
{
if (nesting == MAX_FUNC_NESTING - 1)
emsg(_(e_function_nesting_too_deep));
else
{
++nesting;
nesting_def[nesting] = (c == 'd');
nesting_inline[nesting] = FALSE;
indent += 2;
}
}
}
if (nesting_def[nesting] ? *p != '#' : *p != '"')
{
// Not a comment line: check for nested inline function.
end = p + STRLEN(p) - 1;
while (end > p && VIM_ISWHITE(*end))
--end;
if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1]))
{
int is_block;
// check for trailing "=> {": start of an inline function
--end;
while (end > p && VIM_ISWHITE(*end))
--end;
is_block = end > p + 2 && end[-1] == '=' && end[0] == '>';
if (!is_block)
{
char_u *s = p;
// check for line starting with "au" for :autocmd or
// "com" for :command, these can use a {} block
is_block = checkforcmd_noparen(&s, "autocmd", 2)
|| checkforcmd_noparen(&s, "command", 3);
}
if (is_block)
{
if (nesting == MAX_FUNC_NESTING - 1)
emsg(_(e_function_nesting_too_deep));
else
{
++nesting;
nesting_def[nesting] = TRUE;
nesting_inline[nesting] = TRUE;
indent += 2;
}
}
}
}
// Check for ":append", ":change", ":insert". Not for :def.
p = skip_range(p, FALSE, NULL);
if (!vim9_function
&& ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
|| (p[0] == 'c'
&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'
&& (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'
&& (STRNCMP(&p[3], "nge", 3) != 0
|| !ASCII_ISALPHA(p[6])))))))
|| (p[0] == 'i'
&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
&& (!ASCII_ISALPHA(p[2])
|| (p[2] == 's'
&& (!ASCII_ISALPHA(p[3])
|| p[3] == 'e'))))))))
skip_until = vim_strsave((char_u *)".");
// Check for ":python <<EOF", ":tcl <<EOF", etc.
arg = skipwhite(skiptowhite(p));
if (arg[0] == '<' && arg[1] =='<'
&& ((p[0] == 'p' && p[1] == 'y'
&& (!ASCII_ISALNUM(p[2]) || p[2] == 't'
|| ((p[2] == '3' || p[2] == 'x')
&& !ASCII_ISALPHA(p[3]))))
|| (p[0] == 'p' && p[1] == 'e'
&& (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
|| (p[0] == 't' && p[1] == 'c'
&& (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
|| (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
&& !ASCII_ISALPHA(p[3]))
|| (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
&& (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
|| (p[0] == 'm' && p[1] == 'z'
&& (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
))
{
// ":python <<" continues until a dot, like ":append"
p = skipwhite(arg + 2);
if (STRNCMP(p, "trim", 4) == 0)
{
// Ignore leading white space.
p = skipwhite(p + 4);
heredoc_trimmed = vim_strnsave(theline,
skipwhite(theline) - theline);
}
if (*p == NUL)
skip_until = vim_strsave((char_u *)".");
else
skip_until = vim_strnsave(p, skiptowhite(p) - p);
getline_options = GETLINE_NONE;
is_heredoc = TRUE;
if (eap->cmdidx == CMD_def)
heredoc_concat_len = newlines->ga_len + 1;
}
// Check for ":cmd v =<< [trim] EOF"
// and ":cmd [a, b] =<< [trim] EOF"
// and "lines =<< [trim] EOF" for Vim9
// Where "cmd" can be "let", "var", "final" or "const".
arg = skipwhite(skiptowhite(p));
if (*arg == '[')
arg = vim_strchr(arg, ']');
if (arg != NULL)
{
int found = (eap->cmdidx == CMD_def && arg[0] == '='
&& arg[1] == '<' && arg[2] =='<');
if (!found)
// skip over the argument after "cmd"
arg = skipwhite(skiptowhite(arg));
if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<'
&& (checkforcmd(&p, "let", 2)
|| checkforcmd(&p, "var", 3)
|| checkforcmd(&p, "final", 5)
|| checkforcmd(&p, "const", 5))))
{
p = skipwhite(arg + 3);
if (STRNCMP(p, "trim", 4) == 0)
{
// Ignore leading white space.
p = skipwhite(p + 4);
heredoc_trimmed = vim_strnsave(theline,
skipwhite(theline) - theline);
}
skip_until = vim_strnsave(p, skiptowhite(p) - p);
getline_options = GETLINE_NONE;
is_heredoc = TRUE;
}
}
}
// Add the line to the function.
if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL)
goto theend;
if (heredoc_concat_len > 0)
{
// For a :def function "python << EOF" concatenates all the lines,
// to be used for the instruction later.
ga_concat(&heredoc_ga, theline);
ga_concat(&heredoc_ga, (char_u *)"\n");
p = vim_strsave((char_u *)"");
}
else
{
// Copy the line to newly allocated memory. get_one_sourceline()
// allocates 250 bytes per line, this saves 80% on average. The
// cost is an extra alloc/free.
p = vim_strsave(theline);
}
if (p == NULL)
goto theend;
((char_u **)(newlines->ga_data))[newlines->ga_len++] = p;
// Add NULL lines for continuation lines, so that the line count is
// equal to the index in the growarray.
while (sourcing_lnum_off-- > 0)
((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL;
// Check for end of eap->arg.
if (line_arg != NULL && *line_arg == NUL)
line_arg = NULL;
}
// Return OK when no error was detected.
if (!did_emsg)
ret = OK;
theend:
vim_free(skip_until);
vim_free(heredoc_trimmed);
vim_free(heredoc_ga.ga_data);
need_wait_return |= saved_wait_return;
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,121 |
miniupnp | b238cade9a173c6f751a34acf8ccff838a62aa47 | void processRequest(struct reqelem * req)
{
ssize_t n;
unsigned int l, m;
unsigned char buf[2048];
const unsigned char * p;
enum request_type type;
struct device * d = devlist;
unsigned char rbuf[RESPONSE_BUFFER_SIZE];
unsigned char * rp;
unsigned char nrep = 0;
time_t t;
struct service * newserv = NULL;
struct service * serv;
n = read(req->socket, buf, sizeof(buf));
if(n<0) {
if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
return; /* try again later */
syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket);
goto error;
}
if(n==0) {
syslog(LOG_INFO, "(s=%d) request connection closed", req->socket);
goto error;
}
t = time(NULL);
type = buf[0];
p = buf + 1;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding l=%u n=%u)",
l, (unsigned)n);
goto error;
}
if(l == 0 && type != MINISSDPD_SEARCH_ALL
&& type != MINISSDPD_GET_VERSION && type != MINISSDPD_NOTIF) {
syslog(LOG_WARNING, "bad request (length=0, type=%d)", type);
goto error;
}
syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'",
req->socket, type, l, p);
switch(type) {
case MINISSDPD_GET_VERSION:
rp = rbuf;
CODELENGTH((sizeof(MINISSDPD_VERSION) - 1), rp);
memcpy(rp, MINISSDPD_VERSION, sizeof(MINISSDPD_VERSION) - 1);
rp += (sizeof(MINISSDPD_VERSION) - 1);
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
break;
case MINISSDPD_SEARCH_TYPE: /* request by type */
case MINISSDPD_SEARCH_USN: /* request by USN (unique id) */
case MINISSDPD_SEARCH_ALL: /* everything */
rp = rbuf+1;
while(d && (nrep < 255)) {
if(d->t < t) {
syslog(LOG_INFO, "outdated device");
} else {
/* test if we can put more responses in the buffer */
if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l
+ d->headers[HEADER_USN].l + 6
+ (rp - rbuf) >= (int)sizeof(rbuf))
break;
if( (type==MINISSDPD_SEARCH_TYPE && 0==memcmp(d->headers[HEADER_NT].p, p, l))
||(type==MINISSDPD_SEARCH_USN && 0==memcmp(d->headers[HEADER_USN].p, p, l))
||(type==MINISSDPD_SEARCH_ALL) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = d->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l);
rp += d->headers[HEADER_LOCATION].l;
m = d->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l);
rp += d->headers[HEADER_NT].l;
m = d->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l);
rp += d->headers[HEADER_USN].l;
nrep++;
}
}
d = d->next;
}
/* Also look in service list */
for(serv = servicelisthead.lh_first;
serv && (nrep < 255);
serv = serv->entries.le_next) {
/* test if we can put more responses in the buffer */
if(strlen(serv->location) + strlen(serv->st)
+ strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf))
break;
if( (type==MINISSDPD_SEARCH_TYPE && 0==strncmp(serv->st, (const char *)p, l))
||(type==MINISSDPD_SEARCH_USN && 0==strncmp(serv->usn, (const char *)p, l))
||(type==MINISSDPD_SEARCH_ALL) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;
m = strlen(serv->st);
CODELENGTH(m, rp);
memcpy(rp, serv->st, m);
rp += m;
m = strlen(serv->usn);
CODELENGTH(m, rp);
memcpy(rp, serv->usn, m);
rp += m;
nrep++;
}
}
rbuf[0] = nrep;
syslog(LOG_DEBUG, "(s=%d) response : %d device%s",
req->socket, nrep, (nrep > 1) ? "s" : "");
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
break;
case MINISSDPD_SUBMIT: /* submit service */
newserv = malloc(sizeof(struct service));
if(!newserv) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memset(newserv, 0, sizeof(struct service)); /* set pointers to NULL */
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (st contains forbidden chars)");
goto error;
}
newserv->st = malloc(l + 1);
if(!newserv->st) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->st, p, l);
newserv->st[l] = '\0';
p += l;
if(p >= buf + n) {
syslog(LOG_WARNING, "bad request (missing usn)");
goto error;
}
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (usn contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "usn='%.*s'", l, p);
newserv->usn = malloc(l + 1);
if(!newserv->usn) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->usn, p, l);
newserv->usn[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (server contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "server='%.*s'", l, p);
newserv->server = malloc(l + 1);
if(!newserv->server) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->server, p, l);
newserv->server[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (location contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "location='%.*s'", l, p);
newserv->location = malloc(l + 1);
if(!newserv->location) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->location, p, l);
newserv->location[l] = '\0';
/* look in service list for duplicate */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strcmp(newserv->usn, serv->usn)
&& 0 == strcmp(newserv->st, serv->st)) {
syslog(LOG_INFO, "Service already in the list. Updating...");
free(newserv->st);
free(newserv->usn);
free(serv->server);
serv->server = newserv->server;
free(serv->location);
serv->location = newserv->location;
free(newserv);
newserv = NULL;
return;
}
}
/* Inserting new service */
LIST_INSERT_HEAD(&servicelisthead, newserv, entries);
sendNotifications(NOTIF_NEW, NULL, newserv);
newserv = NULL;
break;
case MINISSDPD_NOTIF: /* switch socket to notify */
rbuf[0] = '\0';
if(write_or_buffer(req, rbuf, 1) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
req->is_notify = 1;
break;
default:
syslog(LOG_WARNING, "Unknown request type %d", type);
rbuf[0] = '\0';
if(write_or_buffer(req, rbuf, 1) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
}
return;
error:
if(newserv) {
free(newserv->st);
free(newserv->usn);
free(newserv->server);
free(newserv->location);
free(newserv);
newserv = NULL;
}
close(req->socket);
req->socket = -1;
return;
}
| 1 | CVE-2016-3178 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 1,388 |
uwsgi | cb4636f7c0af2e97a4eef7a3cdcbd85a71247bfe | int check_hex(char *str, int len) {
int i;
for (i = 0; i < len; i++) {
if ((str[i] < '0' && str[i] > '9') && (str[i] < 'a' && str[i] > 'f') && (str[i] < 'A' && str[i] > 'F')
) {
return 0;
}
}
return 1;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,939 |
tensorflow | f68fdab93fb7f4ddb4eb438c8fe052753c9413e8 | void Compute(tensorflow::OpKernelContext* context) override {
for (int ngram_width : ngram_widths_) {
OP_REQUIRES(
context, ngram_width > 0,
errors::InvalidArgument("ngram_widths must contain positive values"));
}
const tensorflow::Tensor* data;
OP_REQUIRES_OK(context, context->input("data", &data));
const auto& input_data = data->flat<tstring>().data();
const tensorflow::Tensor* splits;
OP_REQUIRES_OK(context, context->input("data_splits", &splits));
const auto& splits_vec = splits->flat<SPLITS_TYPE>();
// Validate that the splits are valid indices into data, only if there are
// splits specified.
const int input_data_size = data->flat<tstring>().size();
const int splits_vec_size = splits_vec.size();
if (splits_vec_size > 0) {
int prev_split = splits_vec(0);
OP_REQUIRES(context, prev_split == 0,
errors::InvalidArgument("First split value must be 0, got ",
prev_split));
for (int i = 1; i < splits_vec_size; ++i) {
bool valid_splits = splits_vec(i) >= prev_split;
valid_splits = valid_splits && (splits_vec(i) <= input_data_size);
OP_REQUIRES(context, valid_splits,
errors::InvalidArgument(
"Invalid split value ", splits_vec(i), ", must be in [",
prev_split, ", ", input_data_size, "]"));
prev_split = splits_vec(i);
}
OP_REQUIRES(context, prev_split == input_data_size,
errors::InvalidArgument(
"Last split value must be data size. Expected ",
input_data_size, ", got ", prev_split));
}
int num_batch_items = splits_vec.size() - 1;
tensorflow::Tensor* ngrams_splits;
OP_REQUIRES_OK(
context, context->allocate_output(1, splits->shape(), &ngrams_splits));
auto ngrams_splits_data = ngrams_splits->flat<SPLITS_TYPE>().data();
// If there is no data or size, return an empty RT.
if (data->flat<tstring>().size() == 0 || splits_vec.size() == 0) {
tensorflow::Tensor* empty;
OP_REQUIRES_OK(context,
context->allocate_output(0, data->shape(), &empty));
for (int i = 0; i <= num_batch_items; ++i) {
ngrams_splits_data[i] = 0;
}
return;
}
ngrams_splits_data[0] = 0;
for (int i = 1; i <= num_batch_items; ++i) {
int length = splits_vec(i) - splits_vec(i - 1);
int num_ngrams = 0;
for (int ngram_width : ngram_widths_)
num_ngrams += get_num_ngrams(length, ngram_width);
if (preserve_short_ && length > 0 && num_ngrams == 0) {
num_ngrams = 1;
}
ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams;
}
tensorflow::Tensor* ngrams;
OP_REQUIRES_OK(
context,
context->allocate_output(
0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams));
auto ngrams_data = ngrams->flat<tstring>().data();
for (int i = 0; i < num_batch_items; ++i) {
auto data_start = &input_data[splits_vec(i)];
int output_start_idx = ngrams_splits_data[i];
for (int ngram_width : ngram_widths_) {
auto output_start = &ngrams_data[output_start_idx];
int length = splits_vec(i + 1) - splits_vec(i);
int num_ngrams = get_num_ngrams(length, ngram_width);
CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
output_start_idx += num_ngrams;
}
// If we're preserving short sequences, check to see if no sequence was
// generated by comparing the current output start idx to the original
// one (ngram_splits_data). If no ngrams were generated, then they will
// be equal (since we increment output_start_idx by num_ngrams every
// time we create a set of ngrams.)
if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) {
int data_length = splits_vec(i + 1) - splits_vec(i);
// One legitimate reason to not have any ngrams when preserve_short_
// is true is if the sequence itself is empty. In that case, move on.
if (data_length == 0) {
continue;
}
// We don't have to worry about dynamic padding sizes here: if padding
// was dynamic, every sequence would have had sufficient padding to
// generate at least one ngram.
int ngram_width = data_length + 2 * pad_width_;
auto output_start = &ngrams_data[output_start_idx];
int num_ngrams = 1;
CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
}
}
} | 1 | CVE-2022-21733 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 4,106 |
evolution-data-server | 6672b8236139bd6ef41ecb915f4c72e2a052dba5 | e_named_parameters_clear (ENamedParameters *parameters)
{
GPtrArray *array;
g_return_if_fail (parameters != NULL);
array = (GPtrArray *) parameters;
if (array->len)
g_ptr_array_remove_range (array, 0, array->len);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,104 |
nasm | e996d28c70d45008085322b442b44a9224308548 | static bool skip_this_pass(int severity)
{
/*
* See if it's a pass-specific error or warning which should be skipped.
* We cannot skip errors stronger than ERR_NONFATAL as by definition
* they cannot be resumed from.
*/
if ((severity & ERR_MASK) > ERR_NONFATAL)
return false;
/*
* passn is 1 on the very first pass only.
* pass0 is 2 on the code-generation (final) pass only.
* These are the passes we care about in this case.
*/
return (((severity & ERR_PASS1) && passn != 1) ||
((severity & ERR_PASS2) && pass0 != 2));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,464 |
qpdf | ad527a64f93dca12f6aabab2ca99ae5eb352ab4b | QPDFObjectHandle::QPDFObjectHandle(QPDFObject* data) :
initialized(true),
qpdf(0),
objid(0),
generation(0),
obj(data),
reserved(false)
{
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,059 |
tensorflow | 098e7762d909bac47ce1dbabe6dfd06294cb9d58 | void Compute(OpKernelContext* ctx) override {
const Tensor& gradient = ctx->input(0);
const Tensor& input = ctx->input(1);
Tensor* input_backprop = nullptr;
OP_REQUIRES_OK(ctx,
ctx->allocate_output(0, input.shape(), &input_backprop));
OP_REQUIRES(
ctx, axis_ >= -1,
errors::InvalidArgument("Axis must be at least -1. Found ", axis_));
OP_REQUIRES(ctx, (axis_ == -1 || axis_ < input.shape().dims()),
errors::InvalidArgument(
"Axis should be -1 or 0 or a positive value less than ",
input.shape().dims(), "but given axis value was ", axis_));
OP_REQUIRES(
ctx, input.IsSameSize(gradient),
errors::InvalidArgument("gradient and input must be the same size"));
const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);
const Tensor& input_min_tensor = ctx->input(2);
OP_REQUIRES(ctx,
input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1,
errors::InvalidArgument(
"Input min tensor must have dimension 0 or 1. Received ",
input_min_tensor.dims(), "."));
const Tensor& input_max_tensor = ctx->input(3);
OP_REQUIRES(ctx,
input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1,
errors::InvalidArgument(
"Input max tensor must have dimension 0 or 1. Received ",
input_max_tensor.dims(), "."));
if (axis_ != -1) {
OP_REQUIRES(
ctx, input_min_tensor.dim_size(0) == depth,
errors::InvalidArgument("min has incorrect size, expected ", depth,
" was ", input_min_tensor.dim_size(0)));
OP_REQUIRES(
ctx, input_max_tensor.dim_size(0) == depth,
errors::InvalidArgument("max has incorrect size, expected ", depth,
" was ", input_max_tensor.dim_size(0)));
}
TensorShape min_max_shape(input_min_tensor.shape());
Tensor* input_min_backprop;
OP_REQUIRES_OK(ctx,
ctx->allocate_output(1, min_max_shape, &input_min_backprop));
Tensor* input_max_backprop;
OP_REQUIRES_OK(ctx,
ctx->allocate_output(2, min_max_shape, &input_max_backprop));
if (axis_ == -1) {
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(input_min_tensor.shape()),
errors::InvalidArgument(
"input_min must be a scalar if axis is unspecified"));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(input_max_tensor.shape()),
errors::InvalidArgument(
"input_max must be a scalar if axis is unspecified"));
functor::QuantizeAndDequantizeOneScaleGradientFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), gradient.template flat<T>(),
input.template flat<T>(), input_min_tensor.scalar<T>(),
input_max_tensor.scalar<T>(), input_backprop->template flat<T>(),
input_min_backprop->template scalar<T>(),
input_max_backprop->template scalar<T>());
} else {
functor::QuantizeAndDequantizePerChannelGradientFunctor<Device, T> f;
f(ctx->eigen_device<Device>(),
gradient.template flat_inner_outer_dims<T, 3>(axis_ - 1),
input.template flat_inner_outer_dims<T, 3>(axis_ - 1),
&input_min_tensor, &input_max_tensor,
input_backprop->template flat_inner_outer_dims<T, 3>(axis_ - 1),
input_min_backprop->template flat<T>(),
input_max_backprop->template flat<T>());
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,488 |
php | 81406c0c1d45f75fcc7972ed974d2597abb0b9e9 | php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper,
char *path,
char *mode,
int options,
char **opened_path,
php_stream_context *context STREAMS_DC TSRMLS_DC)
{
int path_len;
char *file_basename;
size_t file_basename_len;
char file_dirname[MAXPATHLEN];
struct zip *za;
struct zip_file *zf = NULL;
char *fragment;
int fragment_len;
int err;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
fragment = strchr(path, '#');
if (!fragment) {
return NULL;
}
if (strncasecmp("zip://", path, 6) == 0) {
path += 6;
}
fragment_len = strlen(fragment);
if (fragment_len < 1) {
return NULL;
}
path_len = strlen(path);
if (path_len >= MAXPATHLEN || mode[0] != 'r') {
return NULL;
}
memcpy(file_dirname, path, path_len - fragment_len);
file_dirname[path_len - fragment_len] = '\0';
php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC);
fragment++;
if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) {
efree(file_basename);
return NULL;
}
za = zip_open(file_dirname, ZIP_CREATE, &err);
if (za) {
zf = zip_fopen(za, fragment, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
if (opened_path) {
*opened_path = estrdup(path);
}
} else {
zip_close(za);
}
}
efree(file_basename);
if (!stream) {
return NULL;
} else {
return stream;
}
}
| 1 | CVE-2016-6297 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 5,665 |
savannah | 4f747edc625815f449048579f6e65869914dd715 | num_fifos ()
{
return nfifo;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,460 |
tcpdump | d7505276842e85bfd067fa21cdb32b8a2dc3c5e4 | icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
| 1 | CVE-2018-14882 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 5,521 |
libxml2 | 9cd1c3cfbd32655d60572c0a413e017260c854df | xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* Note: external parsed entities will not be loaded, it is
* not required for a non-validating parser, unless the
* option of validating, or substituting entities were
* given. Doing so is far more secure as the parser will
* only process data coming from the document entity by
* default.
*/
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
(ctxt->validate == 0))
return;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if (ctxt->instate == XML_PARSER_EOF)
return;
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,701 |
qemu | 66fed30c9cd11854fc878a4eceb507e915d7c9cd | static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
MirrorBlockJob *s,
uint64_t offset,
uint64_t bytes)
{
uint64_t self_start_chunk = offset / s->granularity;
uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
self_start_chunk) < self_end_chunk &&
s->ret >= 0)
{
MirrorOp *op;
QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
uint64_t op_start_chunk = op->offset / s->granularity;
uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
s->granularity) -
op_start_chunk;
if (op == self) {
continue;
}
if (ranges_overlap(self_start_chunk, self_nb_chunks,
op_start_chunk, op_nb_chunks))
{
/*
* If the operation is already (indirectly) waiting for us, or
* will wait for us as soon as it wakes up, then just go on
* (instead of producing a deadlock in the former case).
*/
if (op->waiting_for_op) {
continue;
}
self->waiting_for_op = op;
qemu_co_queue_wait(&op->waiting_requests, NULL);
self->waiting_for_op = NULL;
break;
}
}
}
} | 1 | CVE-2021-4145 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 4,584 |
uzbl | 1958b52d41cba96956dc1995660de49525ed1047 | talk_to_socket(WebKitWebView *web_view, GArray *argv, GString *result) {
(void)web_view; (void)result;
int fd, len;
struct sockaddr_un sa;
char* sockpath;
ssize_t ret;
struct pollfd pfd;
struct iovec* iov;
guint i;
if(uzbl.comm.sync_stdout) uzbl.comm.sync_stdout = strfree(uzbl.comm.sync_stdout);
/* This function could be optimised by storing a hash table of socket paths
and associated connected file descriptors rather than closing and
re-opening for every call. Also we could launch a script if socket connect
fails. */
/* First element argv[0] is path to socket. Following elements are tokens to
write to the socket. We write them as a single packet with each token
separated by an ASCII nul (\0). */
if(argv->len < 2) {
g_printerr("talk_to_socket called with only %d args (need at least two).\n",
(int)argv->len);
return;
}
/* copy socket path, null terminate result */
sockpath = g_array_index(argv, char*, 0);
g_strlcpy(sa.sun_path, sockpath, sizeof(sa.sun_path));
sa.sun_family = AF_UNIX;
/* create socket file descriptor and connect it to path */
fd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
if(fd == -1) {
g_printerr("talk_to_socket: creating socket failed (%s)\n", strerror(errno));
return;
}
if(connect(fd, (struct sockaddr*)&sa, sizeof(sa))) {
g_printerr("talk_to_socket: connect failed (%s)\n", strerror(errno));
close(fd);
return;
}
/* build request vector */
iov = g_malloc(sizeof(struct iovec) * (argv->len - 1));
if(!iov) {
g_printerr("talk_to_socket: unable to allocated memory for token vector\n");
close(fd);
return;
}
for(i = 1; i < argv->len; ++i) {
iov[i - 1].iov_base = g_array_index(argv, char*, i);
iov[i - 1].iov_len = strlen(iov[i - 1].iov_base) + 1; /* string plus \0 */
}
/* write request */
ret = writev(fd, iov, argv->len - 1);
g_free(iov);
if(ret == -1) {
g_printerr("talk_to_socket: write failed (%s)\n", strerror(errno));
close(fd);
return;
}
/* wait for a response, with a 500ms timeout */
pfd.fd = fd;
pfd.events = POLLIN;
while(1) {
ret = poll(&pfd, 1, 500);
if(ret == 1) break;
if(ret == 0) errno = ETIMEDOUT;
if(errno == EINTR) continue;
g_printerr("talk_to_socket: poll failed while waiting for input (%s)\n",
strerror(errno));
close(fd);
return;
}
/* get length of response */
if(ioctl(fd, FIONREAD, &len) == -1) {
g_printerr("talk_to_socket: cannot find daemon response length, "
"ioctl failed (%s)\n", strerror(errno));
close(fd);
return;
}
/* if there is a response, read it */
if(len) {
uzbl.comm.sync_stdout = g_malloc(len + 1);
if(!uzbl.comm.sync_stdout) {
g_printerr("talk_to_socket: failed to allocate %d bytes\n", len);
close(fd);
return;
}
uzbl.comm.sync_stdout[len] = 0; /* ensure result is null terminated */
ret = read(fd, uzbl.comm.sync_stdout, len);
if(ret == -1) {
g_printerr("talk_to_socket: failed to read from socket (%s)\n",
strerror(errno));
close(fd);
return;
}
}
/* clean up */
close(fd);
return;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,368 |
xserver | d2f813f7db157fc83abc4b3726821c36ee7e40b1 | SafeAlphaCompositeSolidMask_nx8x8888(
CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca;
CARD32 *dstLine, *dst, d, dstMask;
CARD8 *maskLine, *mask, m;
FbStride dstStride, maskStride;
CARD16 w;
fbComposeGetSolid(pSrc, src, pDst->format);
dstMask = FbFullMask (pDst->pDrawable->depth);
srca = src >> 24;
if (src == 0)
return;
fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1);
if (dstMask == FB_ALLONES && pDst->pDrawable->bitsPerPixel == 32 &&
width * height > rootless_CompositePixels_threshold &&
SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels)
{
void *srcp[2], *destp[2];
unsigned int dest_rowbytes[2];
unsigned int fn;
srcp[0] = &src; srcp[1] = &src;
/* null rowbytes pointer means use first value as a constant */
destp[0] = dstLine; destp[1] = dstLine;
dest_rowbytes[0] = dstStride * 4; dest_rowbytes[1] = dest_rowbytes[0];
fn = RL_COMPOSITE_FUNCTION(RL_COMPOSITE_OVER, RL_DEPTH_ARGB8888,
RL_DEPTH_A8, RL_DEPTH_ARGB8888);
if (SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels(
width, height, fn, srcp, NULL,
maskLine, maskStride,
destp, dest_rowbytes) == Success)
{
return;
}
}
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
}
void
SafeAlphaComposite (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
RegionRec region;
int n;
BoxPtr pbox;
CompositeFunc func = 0;
Bool srcRepeat = pSrc->repeat;
Bool maskRepeat = FALSE;
Bool srcAlphaMap = pSrc->alphaMap != 0;
Bool maskAlphaMap = FALSE;
Bool dstAlphaMap = pDst->alphaMap != 0;
int x_msk, y_msk, x_src, y_src, x_dst, y_dst;
int w, h, w_this, h_this;
int dstDepth = pDst->pDrawable->depth;
int oldFormat = pDst->format;
xDst += pDst->pDrawable->x;
yDst += pDst->pDrawable->y;
xSrc += pSrc->pDrawable->x;
ySrc += pSrc->pDrawable->y;
if (pMask)
{
xMask += pMask->pDrawable->x;
yMask += pMask->pDrawable->y;
maskRepeat = pMask->repeat;
maskAlphaMap = pMask->alphaMap != 0;
}
/*
* We can use the more optimized fbpict code, but it sets bits above
* the depth to zero. Temporarily adjust destination depth if needed.
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
{
pDst->pDrawable->depth = 32;
}
/* For rootless preserve the alpha in x8r8g8b8 which really is
* a8r8g8b8
*/
int n;
{
pDst->format = PICT_a8r8g8b8;
}
if (!pSrc->transform && !(pMask && pMask->transform))
if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap)
switch (op) {
case PictOpSrc:
#ifdef USE_MMX
if (!pMask && pSrc->format == pDst->format &&
pSrc->pDrawable != pDst->pDrawable)
{
func = fbCompositeCopyAreammx;
}
#endif
break;
case PictOpOver:
if (pMask)
{
if (srcRepeat &&
pSrc->pDrawable->width == 1 &&
pSrc->pDrawable->height == 1)
{
srcRepeat = FALSE;
if (PICT_FORMAT_COLOR(pSrc->format)) {
switch (pMask->format) {
case PICT_a8:
switch (pDst->format) {
case PICT_r5g6b5:
case PICT_b5g6r5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8x0565mmx;
else
#endif
func = fbCompositeSolidMask_nx8x0565;
break;
case PICT_r8g8b8:
case PICT_b8g8r8:
func = fbCompositeSolidMask_nx8x0888;
break;
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
func = SafeAlphaCompositeSolidMask_nx8x8888;
break;
}
break;
case PICT_a8r8g8b8:
if (pMask->componentAlpha) {
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x8888Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x8888C;
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x0565Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x0565C;
break;
}
}
break;
case PICT_a8b8g8r8:
if (pMask->componentAlpha) {
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x8888Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x8888C;
break;
case PICT_b5g6r5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x0565Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x0565C;
break;
}
}
break;
case PICT_a1:
switch (pDst->format) {
case PICT_r5g6b5:
case PICT_b5g6r5:
case PICT_r8g8b8:
case PICT_b8g8r8:
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
func = fbCompositeSolidMask_nx1xn;
break;
}
break;
}
}
}
else /* has mask and non-repeating source */
{
if (pSrc->pDrawable == pMask->pDrawable &&
xSrc == xMask && ySrc == yMask &&
!pMask->componentAlpha)
{
/* source == mask: non-premultiplied data */
switch (pSrc->format) {
case PICT_x8b8g8r8:
switch (pMask->format) {
case PICT_a8r8g8b8:
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx8888mmx;
#endif
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx0565mmx;
#endif
break;
}
break;
}
break;
case PICT_x8r8g8b8:
switch (pMask->format) {
case PICT_a8r8g8b8:
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx8888mmx;
#endif
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx0565mmx;
#endif
break;
}
break;
}
break;
}
break;
}
else
{
/* non-repeating source, repeating mask => translucent window */
if (maskRepeat &&
pMask->pDrawable->width == 1 &&
pMask->pDrawable->height == 1)
{
if (pSrc->format == PICT_x8r8g8b8 &&
pDst->format == PICT_x8r8g8b8 &&
pMask->format == PICT_a8)
{
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888x8x8888mmx;
#endif
}
}
}
}
}
else /* no mask */
{
if (srcRepeat &&
pSrc->pDrawable->width == 1 &&
pSrc->pDrawable->height == 1)
{
/* no mask and repeating source */
switch (pSrc->format) {
case PICT_a8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
{
srcRepeat = FALSE;
func = fbCompositeSolid_nx8888mmx;
}
#endif
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
{
srcRepeat = FALSE;
func = fbCompositeSolid_nx0565mmx;
}
#endif
break;
}
break;
}
}
else
{
switch (pSrc->format) {
case PICT_a8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888x8888mmx;
else
#endif
func = fbCompositeSrc_8888x8888;
break;
case PICT_r8g8b8:
func = fbCompositeSrc_8888x0888;
break;
case PICT_r5g6b5:
func = fbCompositeSrc_8888x0565;
break;
}
break;
case PICT_x8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeCopyAreammx;
#endif
break;
}
case PICT_x8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeCopyAreammx;
#endif
break;
}
break;
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888x8888mmx;
else
#endif
func = fbCompositeSrc_8888x8888;
break;
case PICT_b8g8r8:
func = fbCompositeSrc_8888x0888;
break;
case PICT_b5g6r5:
func = fbCompositeSrc_8888x0565;
break;
}
break;
case PICT_r5g6b5:
switch (pDst->format) {
case PICT_r5g6b5:
func = fbCompositeSrc_0565x0565;
break;
}
break;
case PICT_b5g6r5:
switch (pDst->format) {
case PICT_b5g6r5:
func = fbCompositeSrc_0565x0565;
break;
}
break;
}
}
}
break;
case PictOpAdd:
if (pMask == 0)
{
switch (pSrc->format) {
case PICT_a8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrcAdd_8888x8888mmx;
else
#endif
func = fbCompositeSrcAdd_8888x8888;
break;
}
break;
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrcAdd_8888x8888mmx;
else
#endif
func = fbCompositeSrcAdd_8888x8888;
break;
}
break;
case PICT_a8:
switch (pDst->format) {
case PICT_a8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrcAdd_8000x8000mmx;
else
#endif
func = fbCompositeSrcAdd_8000x8000;
break;
}
break;
case PICT_a1:
switch (pDst->format) {
case PICT_a1:
func = fbCompositeSrcAdd_1000x1000;
break;
}
break;
}
}
break;
}
if (!func) {
/* no fast path, use the general code */
fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height);
pDst->pDrawable->depth = dstDepth;
pDst->format = oldFormat;
return;
}
if (!miComputeCompositeRegion (®ion,
pSrc,
pMask,
pDst,
xSrc,
ySrc,
xMask,
yMask,
xDst,
yDst,
width,
height))
return;
n = REGION_NUM_RECTS (®ion);
pbox = REGION_RECTS (®ion);
while (n--)
{
h = pbox->y2 - pbox->y1;
y_src = pbox->y1 - yDst + ySrc;
y_msk = pbox->y1 - yDst + yMask;
y_dst = pbox->y1;
while (h)
{
h_this = h;
w = pbox->x2 - pbox->x1;
x_src = pbox->x1 - xDst + xSrc;
x_msk = pbox->x1 - xDst + xMask;
x_dst = pbox->x1;
if (maskRepeat)
{
y_msk = mod (y_msk, pMask->pDrawable->height);
if (h_this > pMask->pDrawable->height - y_msk)
h_this = pMask->pDrawable->height - y_msk;
}
if (srcRepeat)
{
y_src = mod (y_src, pSrc->pDrawable->height);
if (h_this > pSrc->pDrawable->height - y_src)
h_this = pSrc->pDrawable->height - y_src;
}
while (w)
{
w_this = w;
if (maskRepeat)
{
x_msk = mod (x_msk, pMask->pDrawable->width);
if (w_this > pMask->pDrawable->width - x_msk)
w_this = pMask->pDrawable->width - x_msk;
}
if (srcRepeat)
{
x_src = mod (x_src, pSrc->pDrawable->width);
if (w_this > pSrc->pDrawable->width - x_src)
w_this = pSrc->pDrawable->width - x_src;
}
(*func) (op, pSrc, pMask, pDst,
x_src, y_src, x_msk, y_msk, x_dst, y_dst,
w_this, h_this);
w -= w_this;
x_src += w_this;
x_msk += w_this;
x_dst += w_this;
}
h -= h_this;
y_src += h_this;
y_msk += h_this;
y_dst += h_this;
}
pbox++;
}
REGION_UNINIT (pDst->pDrawable->pScreen, ®ion);
pDst->pDrawable->depth = dstDepth;
pDst->format = oldFormat;
}
}
/* For rootless preserve the alpha in x8r8g8b8 which really is
* a8r8g8b8
*/
if (oldFormat == PICT_x8r8g8b8)
{
pDst->format = PICT_a8r8g8b8;
}
if (!pSrc->transform && !(pMask && pMask->transform))
if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap)
switch (op) {
case PictOpSrc:
#ifdef USE_MMX
if (!pMask && pSrc->format == pDst->format &&
pSrc->pDrawable != pDst->pDrawable)
{
func = fbCompositeCopyAreammx;
}
#endif
break;
case PictOpOver:
if (pMask)
{
if (srcRepeat &&
pSrc->pDrawable->width == 1 &&
pSrc->pDrawable->height == 1)
{
srcRepeat = FALSE;
if (PICT_FORMAT_COLOR(pSrc->format)) {
switch (pMask->format) {
case PICT_a8:
switch (pDst->format) {
case PICT_r5g6b5:
case PICT_b5g6r5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8x0565mmx;
else
#endif
func = fbCompositeSolidMask_nx8x0565;
break;
case PICT_r8g8b8:
case PICT_b8g8r8:
func = fbCompositeSolidMask_nx8x0888;
break;
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
func = SafeAlphaCompositeSolidMask_nx8x8888;
break;
}
break;
case PICT_a8r8g8b8:
if (pMask->componentAlpha) {
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x8888Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x8888C;
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x0565Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x0565C;
break;
}
}
break;
case PICT_a8b8g8r8:
if (pMask->componentAlpha) {
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x8888Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x8888C;
break;
case PICT_b5g6r5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x0565Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x0565C;
break;
}
}
break;
case PICT_a1:
switch (pDst->format) {
case PICT_r5g6b5:
case PICT_b5g6r5:
case PICT_r8g8b8:
case PICT_b8g8r8:
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
func = fbCompositeSolidMask_nx1xn;
break;
}
break;
}
}
}
else /* has mask and non-repeating source */
{
if (pSrc->pDrawable == pMask->pDrawable &&
xSrc == xMask && ySrc == yMask &&
!pMask->componentAlpha)
{
/* source == mask: non-premultiplied data */
switch (pSrc->format) {
case PICT_x8b8g8r8:
switch (pMask->format) {
case PICT_a8r8g8b8:
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx8888mmx;
#endif
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx0565mmx;
#endif
break;
}
break;
}
break;
case PICT_x8r8g8b8:
switch (pMask->format) {
case PICT_a8r8g8b8:
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx8888mmx;
#endif
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888RevNPx0565mmx;
#endif
break;
}
break;
}
break;
}
break;
}
else
{
/* non-repeating source, repeating mask => translucent window */
if (maskRepeat &&
pMask->pDrawable->width == 1 &&
pMask->pDrawable->height == 1)
{
if (pSrc->format == PICT_x8r8g8b8 &&
pDst->format == PICT_x8r8g8b8 &&
pMask->format == PICT_a8)
{
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888x8x8888mmx;
#endif
}
}
}
}
}
else /* no mask */
{
if (srcRepeat &&
pSrc->pDrawable->width == 1 &&
pSrc->pDrawable->height == 1)
{
/* no mask and repeating source */
switch (pSrc->format) {
case PICT_a8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
{
srcRepeat = FALSE;
func = fbCompositeSolid_nx8888mmx;
}
#endif
break;
case PICT_r5g6b5:
#ifdef USE_MMX
if (fbHaveMMX())
{
srcRepeat = FALSE;
func = fbCompositeSolid_nx0565mmx;
}
#endif
break;
}
break;
}
}
else
{
switch (pSrc->format) {
case PICT_a8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888x8888mmx;
else
#endif
func = fbCompositeSrc_8888x8888;
break;
case PICT_r8g8b8:
func = fbCompositeSrc_8888x0888;
break;
case PICT_r5g6b5:
func = fbCompositeSrc_8888x0565;
break;
}
break;
case PICT_x8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeCopyAreammx;
#endif
break;
}
case PICT_x8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeCopyAreammx;
#endif
break;
}
break;
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrc_8888x8888mmx;
else
#endif
func = fbCompositeSrc_8888x8888;
break;
case PICT_b8g8r8:
func = fbCompositeSrc_8888x0888;
break;
case PICT_b5g6r5:
func = fbCompositeSrc_8888x0565;
break;
}
break;
case PICT_r5g6b5:
switch (pDst->format) {
case PICT_r5g6b5:
func = fbCompositeSrc_0565x0565;
break;
}
break;
case PICT_b5g6r5:
switch (pDst->format) {
case PICT_b5g6r5:
func = fbCompositeSrc_0565x0565;
break;
}
break;
}
}
}
break;
case PictOpAdd:
if (pMask == 0)
{
switch (pSrc->format) {
case PICT_a8r8g8b8:
switch (pDst->format) {
case PICT_a8r8g8b8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrcAdd_8888x8888mmx;
else
#endif
func = fbCompositeSrcAdd_8888x8888;
break;
}
break;
case PICT_a8b8g8r8:
switch (pDst->format) {
case PICT_a8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrcAdd_8888x8888mmx;
else
#endif
func = fbCompositeSrcAdd_8888x8888;
break;
}
break;
case PICT_a8:
switch (pDst->format) {
case PICT_a8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSrcAdd_8000x8000mmx;
else
#endif
func = fbCompositeSrcAdd_8000x8000;
break;
}
break;
case PICT_a1:
switch (pDst->format) {
case PICT_a1:
func = fbCompositeSrcAdd_1000x1000;
break;
}
break;
}
}
break;
}
if (!func) {
/* no fast path, use the general code */
fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height);
pDst->pDrawable->depth = dstDepth;
pDst->format = oldFormat;
return;
}
if (!miComputeCompositeRegion (®ion,
pSrc,
pMask,
pDst,
xSrc,
ySrc,
xMask,
yMask,
xDst,
yDst,
width,
height))
return;
n = REGION_NUM_RECTS (®ion);
pbox = REGION_RECTS (®ion);
while (n--)
{
h = pbox->y2 - pbox->y1;
y_src = pbox->y1 - yDst + ySrc;
y_msk = pbox->y1 - yDst + yMask;
y_dst = pbox->y1;
while (h)
{
h_this = h;
w = pbox->x2 - pbox->x1;
x_src = pbox->x1 - xDst + xSrc;
x_msk = pbox->x1 - xDst + xMask;
x_dst = pbox->x1;
if (maskRepeat)
{
y_msk = mod (y_msk, pMask->pDrawable->height);
if (h_this > pMask->pDrawable->height - y_msk)
h_this = pMask->pDrawable->height - y_msk;
}
if (srcRepeat)
{
y_src = mod (y_src, pSrc->pDrawable->height);
if (h_this > pSrc->pDrawable->height - y_src)
h_this = pSrc->pDrawable->height - y_src;
}
while (w)
{
w_this = w;
if (maskRepeat)
{
x_msk = mod (x_msk, pMask->pDrawable->width);
if (w_this > pMask->pDrawable->width - x_msk)
w_this = pMask->pDrawable->width - x_msk;
}
if (srcRepeat)
{
x_src = mod (x_src, pSrc->pDrawable->width);
if (w_this > pSrc->pDrawable->width - x_src)
w_this = pSrc->pDrawable->width - x_src;
}
(*func) (op, pSrc, pMask, pDst,
x_src, y_src, x_msk, y_msk, x_dst, y_dst,
w_this, h_this);
w -= w_this;
x_src += w_this;
x_msk += w_this;
x_dst += w_this;
}
h -= h_this;
y_src += h_this;
y_msk += h_this;
y_dst += h_this;
}
pbox++;
}
REGION_UNINIT (pDst->pDrawable->pScreen, ®ion);
pDst->pDrawable->depth = dstDepth;
pDst->format = oldFormat;
}
| 1 | CVE-2010-1166 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 1,794 |
Chrome | 84fbaf8414b4911ef122557d1518b50f79c2eaef | void OomInterventionTabHelper::WebContentsDestroyed() {
StopMonitoring();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,880 |
CWE Enriched and Balanced BigVul+PrimeVul
This dataset is a processed and enriched version of the BigVul and PrimeVul datasets, enhanced using CWE mappings from MITRE's CWE Database. The purpose of this dataset is to provide a cleaner, more balanced, and more informative version of the original datasets for vulnerability prediction and CWE classification tasks.
π Dataset Description
This dataset contains vulnerability information from BigVul and PrimeVul datasets, with additional columns added from CWE ID mappings fetched from MITREβs CWE database. The dataset was cleaned, balanced, and split into training, validation, and test sets while maintaining:
- The distribution ratio of vulnerable and non-vulnerable functions.
- The distribution ratio of each CWE ID across all splits.
π‘ Key Features:
- Project & Commit Information: Metadata related to the project and its commits.
- Function Code (
func
): The code snippet associated with each entry. - Vulnerability Label (
vul
): Whether the function is vulnerable (1
) or not (0
). - CVE ID & CWE ID Mapping: Relevant IDs for categorizing vulnerabilities.
- CWE Information: Additional information fetched from MITRE's CWE database including:
CWE Name
CWE Description
Potential Mitigation
π Dataset Structure
The dataset consists of the following columns:
Column Name | Description |
---|---|
project | The name of the project where the code is taken from. |
commit_id | The unique commit identifier. |
func | The function code snippet. |
vul | Label indicating if the function is vulnerable (1 ) or not (0 ). |
CVE ID | The CVE identifier (if applicable). |
CWE ID | The CWE identifier corresponding to the vulnerability. |
CWE Name | The name of the CWE ID. |
CWE Description | Description of the CWE category. |
Potential Mitigation | Recommended mitigations for addressing the vulnerability. |
π CWE IDs Contained In This Dataset
The dataset contains the following 13 unique CWE IDs (Including Not Applicable):
CWE ID | CWE Name |
---|---|
CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer |
CWE-20 | Improper Input Validation |
CWE-125 | Out-of-bounds Read |
CWE-399 | Resource Management Errors |
CWE-200 | Information Exposure |
CWE-787 | Out-of-bounds Write |
CWE-264 | Permissions, Privileges, and Access Control |
CWE-416 | Use After Free |
CWE-476 | NULL Pointer Dereference |
CWE-190 | Integer Overflow or Wraparound |
CWE-189 | Numeric Errors |
CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization (Race Condition) |
NOT_APPLICABLE | Not applicable / No CWE ID assigned |
π Data Splitting & Balancing
The dataset has been split into training, validation, and test sets using stratified sampling to ensure the distribution of:
- Vulnerable (
vul = 1
) and Non-Vulnerable (vul = 0
) functions. - Each CWE ID remains consistent across splits.
π₯ Usage
To load this dataset from the Hugging Face Hub:
from datasets import load_dataset
dataset = load_dataset('mahdin70/cwe_enriched_balanced_bigvul_primevul')
π Citation
If you use this dataset, please cite the original sources of BigVul and PrimeVul datasets.
- Downloads last month
- 39
Models trained or fine-tuned on mahdin70/cwe_enriched_balanced_bigvul_primevul
