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(&current->sighand->siglock); set_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL); spin_unlock_irq(&current->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 = &current->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 (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; } } /* For rootless preserve the alpha in x8r8g8b8 which really is * a8r8g8b8 */ if (oldFormat == PICT_x8r8g8b8) { pDst->format = PICT_a8r8g8b8; } if (!pSrc->transform && !(pMask && pMask->transform)) if (!maskAlphaMap && !srcAlphaMap && !dstAlphaMap) switch (op) { case PictOpSrc: #ifdef USE_MMX if (!pMask && pSrc->format == pDst->format && pSrc->pDrawable != pDst->pDrawable) { func = fbCompositeCopyAreammx; } #endif break; case PictOpOver: if (pMask) { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { srcRepeat = FALSE; if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = SafeAlphaCompositeSolidMask_nx8x8888; break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: func = fbCompositeSolidMask_nx1xn; break; } break; } } } else /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; } break; } break; } break; } else { /* non-repeating source, repeating mask => translucent window */ if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { if (pSrc->format == PICT_x8r8g8b8 && pDst->format == PICT_x8r8g8b8 && pMask->format == PICT_a8) { #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; #endif } } } } } else /* no mask */ { if (srcRepeat && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; } break; } } else { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: func = fbCompositeSrc_8888x0565; break; } break; case PICT_r5g6b5: switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSrc_0565x0565; break; } break; case PICT_b5g6r5: switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSrc_0565x0565; break; } break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; } break; } } break; } if (!func) { /* no fast path, use the general code */ fbCompositeGeneral(op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; return; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; } if (srcRepeat) { y_src = mod (y_src, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; } if (srcRepeat) { x_src = mod (x_src, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); pDst->pDrawable->depth = dstDepth; pDst->format = oldFormat; }
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
FFmpeg
f52fbf4f3ed02a7d872d8a102006f29b4421f360
static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int i, v, offset, count, segments; segments = bytestream2_get_le16(gb); while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 2; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count*2 + width) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) { frame[0] = frame[1] = frame[width] = frame[width + 1] = frame[-offset]; frame += 2; } } else if (bitbuf & (mask << 1)) { v = bytestream2_get_le16(gb)*2; if (frame - frame_end < v) return AVERROR_INVALIDDATA; frame += v; } else { if (frame_end - frame < width + 3) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; } mask <<= 2; } return 0; }
1
CVE-2017-9992
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).
6,594
vim
de05bb25733c3319e18dca44e9b59c6ee389eb26
redraw_after_callback(int call_update_screen, int do_message) { ++redrawing_for_callback; if (State == HITRETURN || State == ASKMORE || State == SETWSIZE || State == EXTERNCMD || State == CONFIRM || exmode_active) { if (do_message) repeat_message(); } else if (State & CMDLINE) { // Don't redraw when in prompt_for_number(). if (cmdline_row > 0) { // Redrawing only works when the screen didn't scroll. Don't clear // wildmenu entries. if (msg_scrolled == 0 #ifdef FEAT_WILDMENU && wild_menu_showing == 0 #endif && call_update_screen) update_screen(0); // Redraw in the same position, so that the user can continue // editing the command. redrawcmdline_ex(FALSE); } } else if (State & (NORMAL | INSERT | TERMINAL)) { // keep the command line if possible update_screen(VALID_NO_UPDATE); setcursor(); if (msg_scrolled == 0) { // don't want a hit-enter prompt when something else is displayed msg_didany = FALSE; need_wait_return = FALSE; } } cursor_on(); #ifdef FEAT_GUI if (gui.in_use && !gui_mch_is_blink_off()) // Don't update the cursor when it is blinking and off to avoid // flicker. out_flush_cursor(FALSE, FALSE); else #endif out_flush(); --redrawing_for_callback; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,672
ImageMagick6
1aea203eb36409ce6903b9e41fe7cb70030e8750
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff, TIFFInfo *tiff_info) { #define TIFFStripSizeDefault 1048576 const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) memset(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { size_t extent; uint32 rows = 0, rows_per_strip = 0; extent=TIFFScanlineSize(tiff); rows_per_strip=TIFFStripSizeDefault/(extent == 0 ? 1 : (uint32) extent); rows_per_strip=16*(((rows_per_strip < 16 ? 16 : rows_per_strip)+1)/16); (void) TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows); if (rows_per_strip > rows) rows_per_strip=rows; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(uint32) strtoul(option,(char **) NULL,10); rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,780
mongo
64095239f41e9f3841d8be9088347db56d35c891
TEST(LteOp, MatchesDotNotationNull) { BSONObj operand = BSON("$lte" << BSONNULL); LTEMatchExpression lte("a.b", operand["$lte"]); ASSERT(lte.matchesBSON(BSONObj(), NULL)); ASSERT(lte.matchesBSON(BSON("a" << BSONNULL), NULL)); ASSERT(lte.matchesBSON(BSON("a" << 4), NULL)); ASSERT(lte.matchesBSON(BSON("a" << BSONObj()), NULL)); ASSERT(lte.matchesBSON(BSON("a" << BSON_ARRAY(BSON("b" << BSONNULL))), NULL)); ASSERT(lte.matchesBSON(BSON("a" << BSON_ARRAY(BSON("a" << 4) << BSON("b" << 4))), NULL)); ASSERT(!lte.matchesBSON(BSON("a" << BSON_ARRAY(4)), NULL)); ASSERT(!lte.matchesBSON(BSON("a" << BSON_ARRAY(BSON("b" << 4))), NULL)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,721
linux
485e71e8fb6356c08c7fc6bcce4bf02c9a9a663f
posix_acl_clone(const struct posix_acl *acl, gfp_t flags) { struct posix_acl *clone = NULL; if (acl) { int size = sizeof(struct posix_acl) + acl->a_count * sizeof(struct posix_acl_entry); clone = kmemdup(acl, size, flags); if (clone) atomic_set(&clone->a_refcount, 1); } return clone; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,779
qemu
bfc56535f793c557aa754c50213fc5f882e6482d
static void vga_get_resolution(VGACommonState *s, int *pwidth, int *pheight) { int width, height; if (vbe_enabled(s)) { width = s->vbe_regs[VBE_DISPI_INDEX_XRES]; height = s->vbe_regs[VBE_DISPI_INDEX_YRES]; } else { width = (s->cr[VGA_CRTC_H_DISP] + 1) * 8; height = s->cr[VGA_CRTC_V_DISP_END] | ((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) | ((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3); height = (height + 1); } *pwidth = width; *pheight = height; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,201
openssl
a6c62f0c25a756c263a80ce52afbae888028e986
int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl) { EVP_MD_CTX_clear_flags(ctx,EVP_MD_CTX_FLAG_CLEANED); #ifndef OPENSSL_NO_ENGINE /* Whether it's nice or not, "Inits" can be used on "Final"'d contexts * so this context may already have an ENGINE! Try to avoid releasing * the previous handle, re-querying for an ENGINE, and having a * reinitialisation, when it may all be unecessary. */ if (ctx->engine && ctx->digest && (!type || (type && (type->type == ctx->digest->type)))) goto skip_to_init; if (type) { /* Ensure an ENGINE left lying around from last time is cleared * (the previous check attempted to avoid this if the same * ENGINE and EVP_MD could be used). */ if(ctx->engine) ENGINE_finish(ctx->engine); if(impl) { if (!ENGINE_init(impl)) { EVPerr(EVP_F_EVP_DIGESTINIT_EX,EVP_R_INITIALIZATION_ERROR); return 0; } } else /* Ask if an ENGINE is reserved for this job */ impl = ENGINE_get_digest_engine(type->type); if(impl) { /* There's an ENGINE for this job ... (apparently) */ const EVP_MD *d = ENGINE_get_digest(impl, type->type); if(!d) { /* Same comment from evp_enc.c */ EVPerr(EVP_F_EVP_DIGESTINIT_EX,EVP_R_INITIALIZATION_ERROR); ENGINE_finish(impl); return 0; } /* We'll use the ENGINE's private digest definition */ type = d; /* Store the ENGINE functional reference so we know * 'type' came from an ENGINE and we need to release * it when done. */ ctx->engine = impl; } else ctx->engine = NULL; } else if(!ctx->digest) { EVPerr(EVP_F_EVP_DIGESTINIT_EX,EVP_R_NO_DIGEST_SET); return 0; } #endif if (ctx->digest != type) { if (ctx->digest && ctx->digest->ctx_size) OPENSSL_free(ctx->md_data); ctx->digest=type; if (!(ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) && type->ctx_size) { ctx->update = type->update; ctx->md_data=OPENSSL_malloc(type->ctx_size); if (ctx->md_data == NULL) { EVPerr(EVP_F_EVP_DIGESTINIT_EX, ERR_R_MALLOC_FAILURE); return 0; } } } #ifndef OPENSSL_NO_ENGINE skip_to_init: #endif if (ctx->pctx) { int r; r = EVP_PKEY_CTX_ctrl(ctx->pctx, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_DIGESTINIT, 0, ctx); if (r <= 0 && (r != -2)) return 0; } if (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) return 1; #ifdef OPENSSL_FIPS if (FIPS_mode()) { if (FIPS_digestinit(ctx, type)) return 1; OPENSSL_free(ctx->md_data); ctx->md_data = NULL; return 0; } #endif return ctx->digest->init(ctx); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,177
linux
0774a964ef561b7170d8d1b1bfe6f88002b6d219
static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val) { int i; struct kvm_vcpu *vcpu; *val = 0; kvm_for_each_vcpu(i, vcpu, kvm) *val += *(u64 *)((void *)vcpu + offset); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,878
exfat
2e86ae5f81da11f11673d0546efb525af02b7786
static void parse_options(struct exfat* ef, const char* options) { int opt_umask; opt_umask = get_int_option(options, "umask", 8, 0); ef->dmask = get_int_option(options, "dmask", 8, opt_umask); ef->fmask = get_int_option(options, "fmask", 8, opt_umask); ef->uid = get_int_option(options, "uid", 10, geteuid()); ef->gid = get_int_option(options, "gid", 10, getegid()); ef->noatime = match_option(options, "noatime"); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,243
php-src
6045de69c7dedcba3eadf7c4bba424b19c81d00d
static PHP_METHOD(PDOStatement, nextRowset) { PHP_STMT_GET_OBJ; if (!stmt->methods->next_rowset) { pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "driver does not support multiple rowsets" TSRMLS_CC); RETURN_FALSE; } PDO_STMT_CLEAR_ERR(); if (!pdo_stmt_do_next_rowset(stmt TSRMLS_CC)) { PDO_HANDLE_STMT_ERR(); RETURN_FALSE; } RETURN_TRUE; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,399
ImageMagick
a2e1064f288a353bc5fef7f79ccb7683759e775c
static MagickBooleanType load_level(Image *image,XCFDocInfo *inDocInfo, XCFLayerInfo *inLayerInfo,ExceptionInfo *exception) { int destLeft = 0, destTop = 0; Image* tile_image; MagickBooleanType status; MagickOffsetType saved_pos, offset, offset2; register ssize_t i; size_t width, height, ntiles, ntile_rows, ntile_cols, tile_image_width, tile_image_height; /* start reading the data */ width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); /* read in the first tile offset. * if it is '0', then this tile level is empty * and we can simply return. */ offset=(MagickOffsetType) ReadBlobMSBLong(image); if (offset == 0) return(MagickTrue); /* Initialise the reference for the in-memory tile-compression */ ntile_rows=(height+TILE_HEIGHT-1)/TILE_HEIGHT; ntile_cols=(width+TILE_WIDTH-1)/TILE_WIDTH; ntiles=ntile_rows*ntile_cols; for (i = 0; i < (ssize_t) ntiles; i++) { status=MagickFalse; if (offset == 0) ThrowBinaryException(CorruptImageError,"NotEnoughTiles",image->filename); /* save the current position as it is where the * next tile offset is stored. */ saved_pos=TellBlob(image); /* read in the offset of the next tile so we can calculate the amount of data needed for this tile*/ offset2=(MagickOffsetType)ReadBlobMSBLong(image); /* if the offset is 0 then we need to read in the maximum possible allowing for negative compression */ if (offset2 == 0) offset2=(MagickOffsetType) (offset + TILE_WIDTH * TILE_WIDTH * 4* 1.5); /* seek to the tile offset */ offset=SeekBlob(image, offset, SEEK_SET); /* Allocate the image for the tile. NOTE: the last tile in a row or column may not be a full tile! */ tile_image_width=(size_t) (destLeft == (int) ntile_cols-1 ? (int) width % TILE_WIDTH : TILE_WIDTH); if (tile_image_width == 0) tile_image_width=TILE_WIDTH; tile_image_height = (size_t) (destTop == (int) ntile_rows-1 ? (int) height % TILE_HEIGHT : TILE_HEIGHT); if (tile_image_height == 0) tile_image_height=TILE_HEIGHT; tile_image=CloneImage(inLayerInfo->image,tile_image_width, tile_image_height,MagickTrue,exception); /* read in the tile */ switch (inDocInfo->compression) { case COMPRESS_NONE: if (load_tile(image,tile_image,inDocInfo,inLayerInfo,(size_t) (offset2-offset),exception) == 0) status=MagickTrue; break; case COMPRESS_RLE: if (load_tile_rle (image,tile_image,inDocInfo,inLayerInfo, (int) (offset2-offset),exception) == 0) status=MagickTrue; break; case COMPRESS_ZLIB: ThrowBinaryException(CoderError,"ZipCompressNotSupported", image->filename) case COMPRESS_FRACTAL: ThrowBinaryException(CoderError,"FractalCompressNotSupported", image->filename) } /* composite the tile onto the layer's image, and then destroy it */ (void) CompositeImage(inLayerInfo->image,tile_image,CopyCompositeOp, MagickTrue,destLeft * TILE_WIDTH,destTop*TILE_HEIGHT,exception); tile_image=DestroyImage(tile_image); /* adjust tile position */ destLeft++; if (destLeft >= (int) ntile_cols) { destLeft = 0; destTop++; } if (status != MagickFalse) return(MagickFalse); /* restore the saved position so we'll be ready to * read the next offset. */ offset=SeekBlob(image, saved_pos, SEEK_SET); /* read in the offset of the next tile */ offset=(MagickOffsetType) ReadBlobMSBLong(image); } if (offset != 0) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename) return(MagickTrue); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,460
wesnoth
af61f9fdd15cd439da9e2fe5fa39d174c923eaae
std::string get_exe_dir() { #ifndef _WIN32 char buf[1024]; size_t path_size = readlink("/proc/self/exe", buf, 1024); if(path_size == static_cast<size_t>(-1)) return std::string(); buf[path_size] = 0; return std::string(dirname(buf)); #else return get_cwd(); #endif }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,457
linux
ac1e516d5a4c56bf0cb4a3dfc0672f689131cfd4
static ssize_t ttm_pool_store(struct kobject *kobj, struct attribute *attr, const char *buffer, size_t size) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); int chars; unsigned val; chars = sscanf(buffer, "%u", &val); if (chars == 0) return size; /* Convert kb to number of pages */ val = val / (PAGE_SIZE >> 10); if (attr == &ttm_page_pool_max) m->options.max_size = val; else if (attr == &ttm_page_pool_small) m->options.small = val; else if (attr == &ttm_page_pool_alloc_size) { if (val > NUM_PAGES_TO_ALLOC*8) { pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n", NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7), NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10)); return size; } else if (val > NUM_PAGES_TO_ALLOC) { pr_warn("Setting allocation size to larger than %lu is not recommended\n", NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10)); } m->options.alloc_size = val; } return size; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,610
ImageMagick
2130bf6f89ded32ef0c88a11694f107c52566c53
static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); }
1
CVE-2017-16546
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).
8,888
krb5
08c642c09c38a9c6454ab43a9b53b2a89b9eef99
krb5_decode_histkey(krb5_context context, struct berval **bvalues, osa_princ_ent_rec *princ_ent) { krb5_error_code err = 0; krb5_int16 i, n_keysets = 0; ldap_seqof_key_data *keysets = NULL; err = decode_keys(bvalues, &keysets, &n_keysets, NULL); if (err != 0) { k5_prependmsg(context, err, _("unable to decode stored principal pw history")); goto cleanup; } princ_ent->old_keys = k5calloc(n_keysets, sizeof(osa_pw_hist_ent), &err); if (princ_ent->old_keys == NULL) goto cleanup; princ_ent->old_key_len = n_keysets; if (n_keysets > 0) princ_ent->admin_history_kvno = keysets[0].mkvno; /* Transfer key data pointers from keysets to princ_ent. */ for (i = 0; i < n_keysets; i++) { princ_ent->old_keys[i].n_key_data = keysets[i].n_key_data; princ_ent->old_keys[i].key_data = keysets[i].key_data; keysets[i].n_key_data = 0; keysets[i].key_data = NULL; } /* Sort the principal entries by kvno in ascending order. */ qsort(princ_ent->old_keys, princ_ent->old_key_len, sizeof(osa_pw_hist_ent), &compare_osa_pw_hist_ent); princ_ent->aux_attributes |= KADM5_KEY_HIST; /* Set the next key to the end of the list. The queue will be lengthened * if it isn't full yet; the first entry will be replaced if it is full. */ princ_ent->old_key_next = princ_ent->old_key_len; cleanup: free_ldap_seqof_key_data(keysets, n_keysets); return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,058
gnome-session
b0dc999e0b45355314616321dbb6cb71e729fc9d
prop_to_command (SmProp *prop) { GString *str; int i, j; gboolean need_quotes; str = g_string_new (NULL); for (i = 0; i < prop->num_vals; i++) { char *val = prop->vals[i].value; need_quotes = FALSE; for (j = 0; j < prop->vals[i].length; j++) { if (!g_ascii_isalnum (val[j]) && !strchr ("-_=:./", val[j])) { need_quotes = TRUE; break; } } if (i > 0) { g_string_append_c (str, ' '); } if (!need_quotes) { g_string_append_printf (str, "%.*s", prop->vals[i].length, (char *)prop->vals[i].value); } else { g_string_append_c (str, '\''); while (val < (char *)prop->vals[i].value + prop->vals[i].length) { if (*val == '\'') { g_string_append (str, "'\''"); } else { g_string_append_c (str, *val); } val++; } g_string_append_c (str, '\''); } } return g_string_free (str, FALSE); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,626
FFmpeg
e43a0a232dbf6d3c161823c2e07c52e76227a1bc
static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,318
Android
295c883fe3105b19bcd0f9e07d54c6b589fc5bff
OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)param); case OMX_IndexParamVideoVp8: return internalSetVp8Params( (const OMX_VIDEO_PARAM_VP8TYPE *)param); case OMX_IndexParamVideoAndroidVp8Encoder: return internalSetAndroidVp8Params( (const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param); default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, param); } }
1
CVE-2016-2476
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).
9,020
ImageMagick
78d4c5db50fbab0b4beb69c46c6167f2c6513dec
static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,212
linux
3e21f4af170bebf47c187c1ff8bf155583c9f3b1
static ssize_t lp_read(struct file * file, char __user * buf, size_t count, loff_t *ppos) { DEFINE_WAIT(wait); unsigned int minor=iminor(file_inode(file)); struct parport *port = lp_table[minor].dev->port; ssize_t retval = 0; char *kbuf = lp_table[minor].lp_buffer; int nonblock = ((file->f_flags & O_NONBLOCK) || (LP_F(minor) & LP_ABORT)); if (count > LP_BUFFER_SIZE) count = LP_BUFFER_SIZE; if (mutex_lock_interruptible(&lp_table[minor].port_mutex)) return -EINTR; lp_claim_parport_or_block (&lp_table[minor]); parport_set_timeout (lp_table[minor].dev, (nonblock ? PARPORT_INACTIVITY_O_NONBLOCK : lp_table[minor].timeout)); parport_negotiate (lp_table[minor].dev->port, IEEE1284_MODE_COMPAT); if (parport_negotiate (lp_table[minor].dev->port, IEEE1284_MODE_NIBBLE)) { retval = -EIO; goto out; } while (retval == 0) { retval = parport_read (port, kbuf, count); if (retval > 0) break; if (nonblock) { retval = -EAGAIN; break; } /* Wait for data. */ if (lp_table[minor].dev->port->irq == PARPORT_IRQ_NONE) { parport_negotiate (lp_table[minor].dev->port, IEEE1284_MODE_COMPAT); lp_error (minor); if (parport_negotiate (lp_table[minor].dev->port, IEEE1284_MODE_NIBBLE)) { retval = -EIO; goto out; } } else { prepare_to_wait(&lp_table[minor].waitq, &wait, TASK_INTERRUPTIBLE); schedule_timeout(LP_TIMEOUT_POLLED); finish_wait(&lp_table[minor].waitq, &wait); } if (signal_pending (current)) { retval = -ERESTARTSYS; break; } cond_resched (); } parport_negotiate (lp_table[minor].dev->port, IEEE1284_MODE_COMPAT); out: lp_release_parport (&lp_table[minor]); if (retval > 0 && copy_to_user (buf, kbuf, retval)) retval = -EFAULT; mutex_unlock(&lp_table[minor].port_mutex); return retval; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,718
php-src
620ccc9b1a0a593786a364af15d45fd797a6cf1f
static void autoload_func_info_dtor(autoload_func_info *alfi) { if (alfi->obj) { zval_ptr_dtor(&alfi->obj); } if (alfi->closure) { zval_ptr_dtor(&alfi->closure); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,505
Chrome
7fa8bd35982700cb2cb6ce22d05128c019a2b587
void HTMLSelectElement::defaultEventHandler(Event* event) { if (!renderer()) return; if (isDisabledFormControl()) { HTMLFormControlElementWithState::defaultEventHandler(event); return; } if (usesMenuList()) menuListDefaultEventHandler(event); else listBoxDefaultEventHandler(event); if (event->defaultHandled()) return; if (event->type() == eventNames().keypressEvent && event->isKeyboardEvent()) { KeyboardEvent* keyboardEvent = toKeyboardEvent(event); if (!keyboardEvent->ctrlKey() && !keyboardEvent->altKey() && !keyboardEvent->metaKey() && isPrintableChar(keyboardEvent->charCode())) { typeAheadFind(keyboardEvent); event->setDefaultHandled(); return; } } HTMLFormControlElementWithState::defaultEventHandler(event); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,655
postgres
1dc75515868454c645ded22d38054ec693e23ec6
mbuf_create_from_data(uint8 *data, int len) { MBuf *mbuf; mbuf = px_alloc(sizeof *mbuf); mbuf->data = (uint8 *) data; mbuf->buf_end = mbuf->data + len; mbuf->data_end = mbuf->data + len; mbuf->read_pos = mbuf->data; mbuf->no_write = true; mbuf->own_data = false; return mbuf; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,589
Chrome
3c8e4852477d5b1e2da877808c998dc57db9460f
void NetworkHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; host_ = frame_host; }
1
CVE-2018-6111
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.
4,771
LibRaw
20ad21c0d87ca80217aee47533d91e633ce1864d
void LibRaw::get_mem_image_format(int *width, int *height, int *colors, int *bps) const { *width = S.width; *height = S.height; if (imgdata.progress_flags < LIBRAW_PROGRESS_FUJI_ROTATE) { if (O.use_fuji_rotate) { if (IO.fuji_width) { int fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; *width = (ushort)(fuji_width / sqrt(0.5)); *height = (ushort)((*height - fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 0.995) *height = (ushort)(*height / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1.005) *width = (ushort)(*width * S.pixel_aspect + 0.5); } } } if (S.flip & 4) { std::swap(*width, *height); } *colors = P1.colors; *bps = O.output_bps; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,297
icoutils
4fbe9222fd79ee31b7ec031b0be070a9a400d1d3
check_offset(char *memory, int total_size, char *name, void *offset, int size) { char* memory_end = memory + total_size; char* block = (char*)offset; char* block_end = offset + size; /*debug("check_offset: size=%x vs %x offset=%x size=%x\n", need_size, total_size, (char *) offset - memory, size);*/ if (((memory <= memory_end) && (block <= block_end)) && ((block < memory) || (block >= memory_end) || (block_end > memory_end))) { warn(_("%s: premature end"), name); return false; } return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,612
libreport
257578a23d1537a2d235aaa2b1488ee4f818e360
static void tv_details_row_activated( GtkTreeView *tree_view, GtkTreePath *tree_path_UNUSED, GtkTreeViewColumn *column, gpointer user_data) { gchar *item_name; struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name); if (!item || !(item->flags & CD_FLAG_TXT)) goto ret; if (!strchr(item->content, '\n')) /* one line? */ goto ret; /* yes */ gint exitcode; gchar *arg[3]; arg[0] = (char *) "xdg-open"; arg[1] = concat_path_file(g_dump_dir_name, item_name); arg[2] = NULL; const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL, NULL, NULL, NULL, NULL, &exitcode, NULL); if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS) { GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"), GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, NULL, NULL); GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL); GtkWidget *textview = gtk_text_view_new(); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL); gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0); gtk_widget_set_size_request(scrolled, 640, 480); gtk_widget_show(scrolled); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8)) /* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */ /* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */ gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview); #else /* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */ gtk_container_add(GTK_CONTAINER(scrolled), textview); #endif gtk_widget_show(textview); load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name); gtk_widget_destroy(textview); gtk_widget_destroy(scrolled); gtk_widget_destroy(dialog); } free(arg[1]); ret: g_free(item_name); }
1
CVE-2015-5302
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.
591
Chrome
c391f54a210dd792f140650b886e92480d8eaf9e
float AudioParam::finalValue() { float value; calculateFinalValues(&value, 1, false); return value; }
1
CVE-2014-3174
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).
7,856
libxml2
932cc9896ab41475d4aa429c27d9afd175959d74
xmlDumpElementContent(xmlBufferPtr buf, xmlElementContentPtr content, int glob) { if (content == NULL) return; if (glob) xmlBufferWriteChar(buf, "("); switch (content->type) { case XML_ELEMENT_CONTENT_PCDATA: xmlBufferWriteChar(buf, "#PCDATA"); break; case XML_ELEMENT_CONTENT_ELEMENT: if (content->prefix != NULL) { xmlBufferWriteCHAR(buf, content->prefix); xmlBufferWriteChar(buf, ":"); } xmlBufferWriteCHAR(buf, content->name); break; case XML_ELEMENT_CONTENT_SEQ: if ((content->c1->type == XML_ELEMENT_CONTENT_OR) || (content->c1->type == XML_ELEMENT_CONTENT_SEQ)) xmlDumpElementContent(buf, content->c1, 1); else xmlDumpElementContent(buf, content->c1, 0); xmlBufferWriteChar(buf, " , "); if ((content->c2->type == XML_ELEMENT_CONTENT_OR) || ((content->c2->type == XML_ELEMENT_CONTENT_SEQ) && (content->c2->ocur != XML_ELEMENT_CONTENT_ONCE))) xmlDumpElementContent(buf, content->c2, 1); else xmlDumpElementContent(buf, content->c2, 0); break; case XML_ELEMENT_CONTENT_OR: if ((content->c1->type == XML_ELEMENT_CONTENT_OR) || (content->c1->type == XML_ELEMENT_CONTENT_SEQ)) xmlDumpElementContent(buf, content->c1, 1); else xmlDumpElementContent(buf, content->c1, 0); xmlBufferWriteChar(buf, " | "); if ((content->c2->type == XML_ELEMENT_CONTENT_SEQ) || ((content->c2->type == XML_ELEMENT_CONTENT_OR) && (content->c2->ocur != XML_ELEMENT_CONTENT_ONCE))) xmlDumpElementContent(buf, content->c2, 1); else xmlDumpElementContent(buf, content->c2, 0); break; default: xmlErrValid(NULL, XML_ERR_INTERNAL_ERROR, "Internal: ELEMENT content corrupted invalid type\n", NULL); } if (glob) xmlBufferWriteChar(buf, ")"); switch (content->ocur) { case XML_ELEMENT_CONTENT_ONCE: break; case XML_ELEMENT_CONTENT_OPT: xmlBufferWriteChar(buf, "?"); break; case XML_ELEMENT_CONTENT_MULT: xmlBufferWriteChar(buf, "*"); break; case XML_ELEMENT_CONTENT_PLUS: xmlBufferWriteChar(buf, "+"); break; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,314
curl
75ca568fa1c19de4c5358fed246686de8467c238
void curl_free(void *p) { if(p) free(p); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,702
Android
eeb4e45d5683f88488c083ecf142dc89bc3f0b47
int res_unpack(vorbis_info_residue *info, vorbis_info *vi,oggpack_buffer *opb){ int j,k; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; memset(info,0,sizeof(*info)); info->type=oggpack_read(opb,16); if(info->type>2 || info->type<0)goto errout; info->begin=oggpack_read(opb,24); info->end=oggpack_read(opb,24); info->grouping=oggpack_read(opb,24)+1; info->partitions=(char)(oggpack_read(opb,6)+1); info->groupbook=(unsigned char)oggpack_read(opb,8); if(info->groupbook>=ci->books)goto errout; info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks)); info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks)); for(j=0;j<info->partitions;j++){ int cascade=oggpack_read(opb,3); if(oggpack_read(opb,1)) cascade|=(oggpack_read(opb,5)<<3); info->stagemasks[j]=cascade; } for(j=0;j<info->partitions;j++){ for(k=0;k<8;k++){ if((info->stagemasks[j]>>k)&1){ unsigned char book=(unsigned char)oggpack_read(opb,8); if(book>=ci->books)goto errout; info->stagebooks[j*8+k]=book; if(k+1>info->stages)info->stages=k+1; }else info->stagebooks[j*8+k]=0xff; } } if(oggpack_eop(opb))goto errout; return 0; errout: res_clear_info(info); return 1; }
1
CVE-2017-0814
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.
3,950
Chrome
2aec794f26098c7a361c27d7c8f57119631cca8a
void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->AddHandler(std::make_unique<protocol::InspectorHandler>()); session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId())); session->AddHandler(std::make_unique<protocol::SchemaHandler>()); session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr); if (state_ == WORKER_READY) session->AttachToAgent(EnsureAgent()); }
1
CVE-2018-6140
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.
8,001
linux
820f9f147dcce2602eefd9b575bbbd9ea14f0953
void pin_kill(struct fs_pin *p) { wait_queue_t wait; if (!p) { rcu_read_unlock(); return; } init_wait(&wait); spin_lock_irq(&p->wait.lock); if (likely(!p->done)) { p->done = -1; spin_unlock_irq(&p->wait.lock); rcu_read_unlock(); p->kill(p); return; } if (p->done > 0) { spin_unlock_irq(&p->wait.lock); rcu_read_unlock(); return; } __add_wait_queue(&p->wait, &wait); while (1) { set_current_state(TASK_UNINTERRUPTIBLE); spin_unlock_irq(&p->wait.lock); rcu_read_unlock(); schedule(); rcu_read_lock(); if (likely(list_empty(&wait.task_list))) break; /* OK, we know p couldn't have been freed yet */ spin_lock_irq(&p->wait.lock); if (p->done > 0) { spin_unlock_irq(&p->wait.lock); break; } } rcu_read_unlock(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,055
linux
c8c499175f7d295ef867335bceb9a76a2c3cdc38
static int sco_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,878
selinux
c49a8ea09501ad66e799ea41b8154b6770fec2c8
static inline void cil_reset_levelrange(struct cil_levelrange *levelrange) { if (levelrange->low_str == NULL) { cil_reset_level(levelrange->low); } if (levelrange->high_str == NULL) { cil_reset_level(levelrange->high); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,738
gpac
90dc7f853d31b0a4e9441cba97feccf36d8b69a4
void AVC_RewriteESDescriptor(GF_MPEGVisualSampleEntryBox *avc) { AVC_RewriteESDescriptorEx(avc, NULL); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,451
Chrome
77e995d28edc6fb303ceb1d596fdf17b046c3ef6
void AddAllUsers() { for (size_t i = 0; i < arraysize(kTestAccounts); ++i) AddUser(kTestAccounts[i], i >= SECONDARY_ACCOUNT_INDEX_START); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,504
linux
70945643722ffeac779d2529a348f99567fa5c33
tlink_rb_search(struct rb_root *root, uid_t uid) { struct rb_node *node = root->rb_node; struct tcon_link *tlink; while (node) { tlink = rb_entry(node, struct tcon_link, tl_rbnode); if (tlink->tl_uid > uid) node = node->rb_left; else if (tlink->tl_uid < uid) node = node->rb_right; else return tlink; } return NULL; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,242
radare2
2ca9ab45891b6ae8e32b6c28c81eebca059cbe5d
static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf, RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da, size_t offset, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7); ut64 abbr_code; size_t i; if (cu->hdr.length > debug_str_len) { return NULL; } while (buf && buf < buf_end && buf >= obuf) { if (cu->length && cu->capacity == cu->length) { r_bin_dwarf_expand_cu (cu); } buf = r_uleb128 (buf, buf_end - buf, &abbr_code); if (abbr_code > da->length || !buf) { return NULL; } r_bin_dwarf_init_die (&cu->dies[cu->length]); if (!abbr_code) { cu->dies[cu->length].abbrev_code = 0; cu->length++; buf++; continue; } cu->dies[cu->length].abbrev_code = abbr_code; cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag; abbr_code += offset; if (da->capacity < abbr_code) { return NULL; } for (i = 0; i < da->decls[abbr_code - 1].length; i++) { if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) { r_bin_dwarf_expand_die (&cu->dies[cu->length]); } if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) { eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n"); break; } memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i])); buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf, &da->decls[abbr_code - 1].specs[i], &cu->dies[cu->length].attr_values[i], &cu->hdr, debug_str, debug_str_len); if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) { const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string; sdb_set (s, "DW_AT_comp_dir", name, 0); } cu->dies[cu->length].length++; } cu->length++; } return buf; }
1
CVE-2017-16805
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.
9,969
Android
04839626ed859623901ebd3a5fd483982186b59d
Track::Info::~Info() { Clear(); }
1
CVE-2016-1621
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,280
ImageMagick6
91e58d967a92250439ede038ccfb0913a81e59fe
static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); }
1
CVE-2019-13307
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).
6,233
node
fcb9145e291e8cb82164bc1fe3db1c1dae219b55
Address address(int n) const { return Address(this) + n; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,736
qemu
79fa99831debc9782087e834382c577215f2f511
static void intel_hda_response(HDACodecDevice *dev, bool solicited, uint32_t response) { const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED; HDACodecBus *bus = HDA_BUS(dev->qdev.parent_bus); IntelHDAState *d = container_of(bus, IntelHDAState, codecs); hwaddr addr; uint32_t wp, ex; MemTxResult res = MEMTX_OK; if (d->ics & ICH6_IRS_BUSY) { dprint(d, 2, "%s: [irr] response 0x%x, cad 0x%x\n", __func__, response, dev->cad); d->irr = response; d->ics &= ~(ICH6_IRS_BUSY | 0xf0); d->ics |= (ICH6_IRS_VALID | (dev->cad << 4)); return; } if (!(d->rirb_ctl & ICH6_RBCTL_DMA_EN)) { dprint(d, 1, "%s: rirb dma disabled, drop codec response\n", __func__); return; } ex = (solicited ? 0 : (1 << 4)) | dev->cad; wp = (d->rirb_wp + 1) & 0xff; addr = intel_hda_addr(d->rirb_lbase, d->rirb_ubase); res |= stl_le_pci_dma(&d->pci, addr + 8 * wp, response, attrs); res |= stl_le_pci_dma(&d->pci, addr + 8 * wp + 4, ex, attrs); if (res != MEMTX_OK && (d->rirb_ctl & ICH6_RBCTL_OVERRUN_EN)) { d->rirb_sts |= ICH6_RBSTS_OVERRUN; intel_hda_update_irq(d); } d->rirb_wp = wp; dprint(d, 2, "%s: [wp 0x%x] response 0x%x, extra 0x%x\n", __func__, wp, response, ex); d->rirb_count++; if (d->rirb_count == d->rirb_cnt) { dprint(d, 2, "%s: rirb count reached (%d)\n", __func__, d->rirb_count); if (d->rirb_ctl & ICH6_RBCTL_IRQ_EN) { d->rirb_sts |= ICH6_RBSTS_IRQ; intel_hda_update_irq(d); } } else if ((d->corb_rp & 0xff) == d->corb_wp) { dprint(d, 2, "%s: corb ring empty (%d/%d)\n", __func__, d->rirb_count, d->rirb_cnt); if (d->rirb_ctl & ICH6_RBCTL_IRQ_EN) { d->rirb_sts |= ICH6_RBSTS_IRQ; intel_hda_update_irq(d); } } }
1
CVE-2021-3611
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
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).
395
radare2
bbb4af56003c1afdad67af0c4339267ca38b1017
static void _6502_anal_esil_pop(RAnalOp *op, ut8 data0) { char *reg = (data0==0x28) ? "flags" : "a"; r_strbuf_setf (&op->esil, "sp,++=,sp,0x100,+,[1],%s,=", reg); if (data0==0x68) _6502_anal_update_flags (op, _6502_FLAGS_NZ); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,675
iperf
91f2fa59e8ed80dfbf400add0164ee0e508e412a
static char *print_array( cJSON *item, int depth, int fmt ) { char **entries; char *out = 0, *ptr, *ret; int len = 5; cJSON *child = item->child; int numentries = 0, i = 0, fail = 0; /* How many entries in the array? */ while ( child ) { ++numentries; child = child->next; } /* Allocate an array to hold the values for each. */ if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) return 0; memset( entries, 0, numentries * sizeof(char*) ); /* Retrieve all the results. */ child = item->child; while ( child && ! fail ) { ret = print_value( child, depth + 1, fmt ); entries[i++] = ret; if ( ret ) len += strlen( ret ) + 2 + ( fmt ? 1 : 0 ); else fail = 1; child = child -> next; } /* If we didn't fail, try to malloc the output string. */ if ( ! fail ) { out = (char*) cJSON_malloc( len ); if ( ! out ) fail = 1; } /* Handle failure. */ if ( fail ) { for ( i = 0; i < numentries; ++i ) if ( entries[i] ) cJSON_free( entries[i] ); cJSON_free( entries ); return 0; } /* Compose the output array. */ *out = '['; ptr = out + 1; *ptr = 0; for ( i = 0; i < numentries; ++i ) { strcpy( ptr, entries[i] ); ptr += strlen( entries[i] ); if ( i != numentries - 1 ) { *ptr++ = ','; if ( fmt ) *ptr++ = ' '; *ptr = 0; } cJSON_free( entries[i] ); } cJSON_free( entries ); *ptr++ = ']'; *ptr++ = 0; return out; }
1
CVE-2016-4303
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).
1,763
php-src
70523ce41ff400ea00343a03f297332cb1f1b77b
static php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode) { php_iconv_err_t err = PHP_ICONV_ERR_SUCCESS; iconv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1); const char *p1; size_t str_left; unsigned int scan_stat = 0; const char *csname = NULL; size_t csname_len; const char *encoded_text = NULL; size_t encoded_text_len = 0; const char *encoded_word = NULL; const char *spaces = NULL; php_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64; if (next_pos != NULL) { *next_pos = NULL; } cd_pl = iconv_open(enc, ICONV_ASCII_ENCODING); if (cd_pl == (iconv_t)(-1)) { #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { err = PHP_ICONV_ERR_WRONG_CHARSET; } else { err = PHP_ICONV_ERR_CONVERTER; } #else err = PHP_ICONV_ERR_UNKNOWN; #endif goto out; } p1 = str; for (str_left = str_nbytes; str_left > 0; str_left--, p1++) { int eos = 0; switch (scan_stat) { case 0: /* expecting any character */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ encoded_word = p1; scan_stat = 1; break; case ' ': case '\t': /* a chunk of whitespaces */ spaces = p1; scan_stat = 11; break; default: /* first letter of a non-encoded word */ err = _php_iconv_appendc(pretval, *p1, cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { if (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) { err = PHP_ICONV_ERR_SUCCESS; } else { goto out; } } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } break; } break; case 1: /* expecting a delimiter */ if (*p1 != '?') { if (*p1 == '\r' || *p1 == '\n') { --p1; } err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } csname = p1 + 1; scan_stat = 2; break; case 2: /* expecting a charset name */ switch (*p1) { case '?': /* normal delimiter: encoding scheme follows */ scan_stat = 3; break; case '*': /* new style delimiter: locale id follows */ scan_stat = 10; break; case '\r': case '\n': /* not an encoded-word */ --p1; _php_iconv_appendc(pretval, '=', cd_pl); _php_iconv_appendc(pretval, '?', cd_pl); err = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } csname = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } continue; } if (scan_stat != 2) { char tmpbuf[80]; if (csname == NULL) { err = PHP_ICONV_ERR_MALFORMED; goto out; } csname_len = (size_t)(p1 - csname); if (csname_len > sizeof(tmpbuf) - 1) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } memcpy(tmpbuf, csname, csname_len); tmpbuf[csname_len] = '\0'; if (cd != (iconv_t)(-1)) { iconv_close(cd); } cd = iconv_open(enc, tmpbuf); if (cd == (iconv_t)(-1)) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* Bad character set, but the user wants us to * press on. In this case, we'll just insert the * undecoded encoded word, since there isn't really * a more sensible behaviour available; the only * other options are to swallow the encoded word * entirely or decode it with an arbitrarily chosen * single byte encoding, both of which seem to have * a higher WTF factor than leaving it undecoded. * * Given this approach, we need to skip ahead to * the end of the encoded word. */ int qmarks = 2; while (qmarks > 0 && str_left > 1) { if (*(++p1) == '?') { --qmarks; } --str_left; } /* Look ahead to check for the terminating = that * should be there as well; if it's there, we'll * also include that. If it's not, there isn't much * we can do at this point. */ if (*(p1 + 1) == '=') { ++p1; --str_left; } err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } /* Let's go back and see if there are further * encoded words or bare content, and hope they * might actually have a valid character set. */ scan_stat = 12; break; } else { #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { err = PHP_ICONV_ERR_WRONG_CHARSET; } else { err = PHP_ICONV_ERR_CONVERTER; } #else err = PHP_ICONV_ERR_UNKNOWN; #endif goto out; } } } break; case 3: /* expecting a encoding scheme specifier */ switch (*p1) { case 'b': case 'B': enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64; scan_stat = 4; break; case 'q': case 'Q': enc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT; scan_stat = 4; break; default: if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } break; case 4: /* expecting a delimiter */ if (*p1 != '?') { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } encoded_text = p1 + 1; scan_stat = 5; break; case 5: /* expecting an encoded portion */ if (*p1 == '?') { encoded_text_len = (size_t)(p1 - encoded_text); scan_stat = 6; } break; case 7: /* expecting a "\n" character */ if (*p1 == '\n') { scan_stat = 8; } else { /* bare CR */ _php_iconv_appendc(pretval, '\r', cd_pl); _php_iconv_appendc(pretval, *p1, cd_pl); scan_stat = 0; } break; case 8: /* checking whether the following line is part of a folded header */ if (*p1 != ' ' && *p1 != '\t') { --p1; str_left = 1; /* quit_loop */ break; } if (encoded_word == NULL) { _php_iconv_appendc(pretval, ' ', cd_pl); } spaces = NULL; scan_stat = 11; break; case 6: /* expecting a End-Of-Chunk character "=" */ if (*p1 != '=') { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } scan_stat = 9; if (str_left == 1) { eos = 1; } else { break; } case 9: /* choice point, seeing what to do next.*/ switch (*p1) { default: /* Handle non-RFC-compliant formats * * RFC2047 requires the character that comes right * after an encoded word (chunk) to be a whitespace, * while there are lots of broken implementations that * generate such malformed headers that don't fulfill * that requirement. */ if (!eos) { if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } scan_stat = 12; break; } } /* break is omitted intentionally */ case '\r': case '\n': case ' ': case '\t': { zend_string *decoded_text; switch (enc_scheme) { case PHP_ICONV_ENC_SCHEME_BASE64: decoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len); break; case PHP_ICONV_ENC_SCHEME_QPRINT: decoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1); break; default: decoded_text = NULL; break; } if (decoded_text == NULL) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_UNKNOWN; goto out; } } err = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd); zend_string_release_ex(decoded_text, 0); if (err != PHP_ICONV_ERR_SUCCESS) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl); encoded_word = NULL; if (err != PHP_ICONV_ERR_SUCCESS) { break; } } else { goto out; } } if (eos) { /* reached end-of-string. done. */ scan_stat = 0; break; } switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ scan_stat = 1; break; case ' ': case '\t': /* medial whitespaces */ spaces = p1; scan_stat = 11; break; default: /* first letter of a non-encoded word */ _php_iconv_appendc(pretval, *p1, cd_pl); scan_stat = 12; break; } } break; } break; case 10: /* expects a language specifier. dismiss it for now */ if (*p1 == '?') { scan_stat = 3; } break; case 11: /* expecting a chunk of whitespaces */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ if (spaces != NULL && encoded_word == NULL) { _php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl); spaces = NULL; } encoded_word = p1; scan_stat = 1; break; case ' ': case '\t': break; default: /* first letter of a non-encoded word */ if (spaces != NULL) { _php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl); spaces = NULL; } _php_iconv_appendc(pretval, *p1, cd_pl); encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } break; case 12: /* expecting a non-encoded word */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case ' ': case '\t': spaces = p1; scan_stat = 11; break; case '=': /* first letter of an encoded chunk */ if (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) { encoded_word = p1; scan_stat = 1; break; } /* break is omitted intentionally */ default: _php_iconv_appendc(pretval, *p1, cd_pl); break; } break; } } switch (scan_stat) { case 0: case 8: case 11: case 12: break; default: if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { if (scan_stat == 1) { _php_iconv_appendc(pretval, '=', cd_pl); } err = PHP_ICONV_ERR_SUCCESS; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } if (next_pos != NULL) { *next_pos = p1; } smart_str_0(pretval); out: if (cd != (iconv_t)(-1)) { iconv_close(cd); } if (cd_pl != (iconv_t)(-1)) { iconv_close(cd_pl); } return err; }
1
CVE-2019-11039
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.
3,805
capstone
6fe86eef621b9849f51a5e1e5d73258a93440403
void * CAPSTONE_API cs_winkernel_malloc(size_t size) { // Disallow zero length allocation because they waste pool header space and, // in many cases, indicate a potential validation issue in the calling code. NT_ASSERT(size); // FP; a use of NonPagedPool is required for Windows 7 support #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; }
1
CVE-2017-6952
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,084
FFmpeg
e43a0a232dbf6d3c161823c2e07c52e76227a1bc
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; in->data[plane] && plane < 4; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; in->data[plane] && plane < 4; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); }
1
CVE-2013-4263
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).
7,418
php-src
b4e4788c4461449b4587e19ef1f474ce938e4980
static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; info_data->name = estrdup(name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen(value, length); info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { if (tag == TAG_MAKER_NOTE) { length = (int) php_strnlen(value, length); } /* do not recompute length here */ info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = safe_emalloc(length, sizeof(image_info_value), 0); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type single"); #endif info_value->f = *(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type double"); #endif info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,922
tcpdump
8dca25d26c7ca2caf6138267f6f17111212c156e
ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,237
jdk11u-dev
9a62b8af48af6c506d2fc4a3482116de26357f16
LIR_Address* LIRGenerator::emit_array_address(LIR_Opr array_opr, LIR_Opr index_opr, BasicType type) { int offset_in_bytes = arrayOopDesc::base_offset_in_bytes(type); LIR_Address* addr; if (index_opr->is_constant()) { int elem_size = type2aelembytes(type); #ifdef _LP64 jint index = index_opr->as_jint(); jlong disp = offset_in_bytes + (jlong)(index) * elem_size; if (disp > max_jint) { // Displacement overflow. Cannot directly use instruction with 32-bit displacement for 64-bit addresses. // Convert array index to long to do array offset computation with 64-bit values. index_opr = new_register(T_LONG); __ move(LIR_OprFact::longConst(index), index_opr); addr = new LIR_Address(array_opr, index_opr, LIR_Address::scale(type), offset_in_bytes, type); } else { addr = new LIR_Address(array_opr, (intx)disp, type); } #else // A displacement overflow can also occur for x86 but that is not a problem due to the 32-bit address range! // Let's assume an array 'a' and an access with displacement 'disp'. When disp overflows, then "a + disp" will // always be negative (i.e. underflows the 32-bit address range): // Let N = 2^32: a + signed_overflow(disp) = a + disp - N. // "a + disp" is always smaller than N. If an index was chosen which would point to an address beyond N, then // range checks would catch that and throw an exception. Thus, a + disp < 0 holds which means that it always // underflows the 32-bit address range: // unsigned_underflow(a + signed_overflow(disp)) = unsigned_underflow(a + disp - N) // = (a + disp - N) + N = a + disp // This shows that we still end up at the correct address with a displacement overflow due to the 32-bit address // range limitation. This overflow only needs to be handled if addresses can be larger as on 64-bit platforms. addr = new LIR_Address(array_opr, offset_in_bytes + (intx)(index_opr->as_jint()) * elem_size, type); #endif // _LP64 } else { #ifdef _LP64 if (index_opr->type() == T_INT) { LIR_Opr tmp = new_register(T_LONG); __ convert(Bytecodes::_i2l, index_opr, tmp); index_opr = tmp; } #endif // _LP64 addr = new LIR_Address(array_opr, index_opr, LIR_Address::scale(type), offset_in_bytes, type); } return addr; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,926
isolated-vm
27151bfecc260e96714443613880e3b2e6596704
CreateRunner(RemoteHandle<Context> context, shared_ptr<NativeModule> module) : context(std::move(context)), module(std::move(module)) {}
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,558
Android
2b9fb0c2074d370a254b35e2489de2d94943578d
WORD32 ihevcd_parse_transform_tree(codec_t *ps_codec, WORD32 x0, WORD32 y0, WORD32 cu_x_base, WORD32 cu_y_base, WORD32 log2_trafo_size, WORD32 trafo_depth, WORD32 blk_idx, WORD32 intra_pred_mode) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; sps_t *ps_sps; pps_t *ps_pps; WORD32 value; WORD32 x1, y1; WORD32 max_trafo_depth; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; WORD32 intra_split_flag; WORD32 split_transform_flag; WORD32 ctxt_idx; cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac; max_trafo_depth = ps_codec->s_parse.s_cu.i4_max_trafo_depth; ps_sps = ps_codec->s_parse.ps_sps; ps_pps = ps_codec->s_parse.ps_pps; intra_split_flag = ps_codec->s_parse.s_cu.i4_intra_split_flag; { split_transform_flag = 0; if((log2_trafo_size <= ps_sps->i1_log2_max_transform_block_size) && (log2_trafo_size > ps_sps->i1_log2_min_transform_block_size) && (trafo_depth < max_trafo_depth) && !(intra_split_flag && (trafo_depth == 0))) { /* encode the split transform flag, context derived as per Table9-37 */ ctxt_idx = IHEVC_CAB_SPLIT_TFM + (5 - log2_trafo_size); TRACE_CABAC_CTXT("split_transform_flag", ps_cabac->u4_range, ctxt_idx); split_transform_flag = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("split_transform_flag", split_transform_flag, ps_cabac->u4_range); } else { WORD32 inter_split_flag = 0; if((0 == ps_sps->i1_max_transform_hierarchy_depth_inter) && (PRED_MODE_INTER == ps_codec->s_parse.s_cu.i4_pred_mode) && (PART_2Nx2N != ps_codec->s_parse.s_cu.i4_part_mode) && (0 == trafo_depth)) { inter_split_flag = 1; } if((log2_trafo_size > ps_sps->i1_log2_max_transform_block_size) || ((1 == intra_split_flag) && (0 == trafo_depth)) || (1 == inter_split_flag)) { split_transform_flag = 1; } } if(0 == trafo_depth) { ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = 0; ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = 0; } else { ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1]; ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1]; } if(trafo_depth == 0 || log2_trafo_size > 2) { ctxt_idx = IHEVC_CAB_CBCR_IDX + trafo_depth; /* CBF for Cb/Cr is sent only if the parent CBF for Cb/Cr is non-zero */ if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1]) { TRACE_CABAC_CTXT("cbf_cb", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_cb", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = value; } if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1]) { TRACE_CABAC_CTXT("cbf_cr", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_cr", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = value; } } if(split_transform_flag) { WORD32 intra_pred_mode_tmp; x1 = x0 + ((1 << log2_trafo_size) >> 1); y1 = y0 + ((1 << log2_trafo_size) >> 1); /* For transform depth of zero, intra pred mode as decoded at CU */ /* level is sent to the transform tree nodes */ /* When depth is non-zero intra pred mode of parent node is sent */ /* This takes care of passing correct mode to all the child nodes */ intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; ret = ihevcd_parse_transform_tree(ps_codec, x0, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 0, intra_pred_mode_tmp); RETURN_IF((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret, ret); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[1]; ret = ihevcd_parse_transform_tree(ps_codec, x1, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 1, intra_pred_mode_tmp); RETURN_IF((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret, ret); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[2]; ret = ihevcd_parse_transform_tree(ps_codec, x0, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 2, intra_pred_mode_tmp); RETURN_IF((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret, ret); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[3]; ret = ihevcd_parse_transform_tree(ps_codec, x1, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 3, intra_pred_mode_tmp); RETURN_IF((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret, ret); } else { WORD32 ctb_x_base; WORD32 ctb_y_base; WORD32 cu_qp_delta_abs; tu_t *ps_tu = ps_codec->s_parse.ps_tu; cu_qp_delta_abs = 0; ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; if((ps_codec->s_parse.s_cu.i4_pred_mode == PRED_MODE_INTRA) || (trafo_depth != 0) || (ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) || (ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth])) { ctxt_idx = IHEVC_CAB_CBF_LUMA_IDX; ctxt_idx += (trafo_depth == 0) ? 1 : 0; TRACE_CABAC_CTXT("cbf_luma", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_luma", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.i1_cbf_luma = value; } else { ps_codec->s_parse.s_cu.i1_cbf_luma = 1; } /* Initialize ps_tu to default values */ /* If required change this to WORD32 packed write */ ps_tu->b1_cb_cbf = 0; ps_tu->b1_cr_cbf = 0; ps_tu->b1_y_cbf = 0; ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); ps_tu->b1_transquant_bypass = ps_codec->s_parse.s_cu.i4_cu_transquant_bypass; ps_tu->b3_size = (log2_trafo_size - 2); ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ps_tu->b6_luma_intra_mode = intra_pred_mode; ps_tu->b3_chroma_intra_mode_idx = ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx; /* Section:7.3.12 Transform unit syntax inlined here */ if(ps_codec->s_parse.s_cu.i1_cbf_luma || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { WORD32 intra_pred_mode_chroma; if(ps_pps->i1_cu_qp_delta_enabled_flag && !ps_codec->s_parse.i4_is_cu_qp_delta_coded) { WORD32 c_max = TU_MAX_QP_DELTA_ABS; WORD32 ctxt_inc = IHEVC_CAB_QP_DELTA_ABS; WORD32 ctxt_inc_max = CTXT_MAX_QP_DELTA_ABS; TRACE_CABAC_CTXT("cu_qp_delta_abs", ps_cabac->u4_range, ctxt_inc); /* qp_delta_abs is coded as combination of tunary and eg0 code */ /* See Table 9-32 and Table 9-37 for details on cu_qp_delta_abs */ cu_qp_delta_abs = ihevcd_cabac_decode_bins_tunary(ps_cabac, ps_bitstrm, c_max, ctxt_inc, 0, ctxt_inc_max); if(cu_qp_delta_abs >= c_max) { value = ihevcd_cabac_decode_bypass_bins_egk(ps_cabac, ps_bitstrm, 0); cu_qp_delta_abs += value; } AEV_TRACE("cu_qp_delta_abs", cu_qp_delta_abs, ps_cabac->u4_range); ps_codec->s_parse.i4_is_cu_qp_delta_coded = 1; if(cu_qp_delta_abs) { value = ihevcd_cabac_decode_bypass_bin(ps_cabac, ps_bitstrm); AEV_TRACE("cu_qp_delta_sign", value, ps_cabac->u4_range); if(value) cu_qp_delta_abs = -cu_qp_delta_abs; } if (cu_qp_delta_abs < MIN_CU_QP_DELTA_ABS(ps_sps->i1_bit_depth_luma_minus8) || cu_qp_delta_abs > MAX_CU_QP_DELTA_ABS(ps_sps->i1_bit_depth_luma_minus8)) { return IHEVCD_INVALID_PARAMETER; } ps_codec->s_parse.s_cu.i4_cu_qp_delta = cu_qp_delta_abs; } if(ps_codec->s_parse.s_cu.i1_cbf_luma) { ps_tu->b1_y_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size, 0, intra_pred_mode); } if(4 == ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx) intra_pred_mode_chroma = ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; else { intra_pred_mode_chroma = gau1_intra_pred_chroma_modes[ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx]; if(intra_pred_mode_chroma == ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]) { intra_pred_mode_chroma = INTRA_ANGULAR(34); } } if(log2_trafo_size > 2) { if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) { ps_tu->b1_cb_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 1, intra_pred_mode_chroma); } if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { ps_tu->b1_cr_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 2, intra_pred_mode_chroma); } } else if(blk_idx == 3) { if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) { ps_tu->b1_cb_cbf = 1; ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 1, intra_pred_mode_chroma); } if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { ps_tu->b1_cr_cbf = 1; ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 2, intra_pred_mode_chroma); } } else { ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; } } else { if((3 != blk_idx) && (2 == log2_trafo_size)) { ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; } } /* Set the first TU in CU flag */ { if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) { ps_tu->b1_first_tu_in_cu = 1; } else { ps_tu->b1_first_tu_in_cu = 0; } } ps_codec->s_parse.ps_tu++; ps_codec->s_parse.s_cu.i4_tu_cnt++; ps_codec->s_parse.i4_pic_tu_idx++; } } return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,983
NetHack
612755bfb5c412079795c68ba392df5d93874ed8
change_inv_order(op) char *op; { int oc_sym, num; char *sp, buf[BUFSZ]; num = 0; #ifndef GOLDOBJ if (!index(op, GOLD_SYM)) buf[num++] = COIN_CLASS; #else /* !!!! probably unnecessary with gold as normal inventory */ #endif for (sp = op; *sp; sp++) { oc_sym = def_char_to_objclass(*sp); /* reject bad or duplicate entries */ if (oc_sym == MAXOCLASSES || oc_sym == RANDOM_CLASS || oc_sym == ILLOBJ_CLASS || !index(flags.inv_order, oc_sym) || index(sp+1, *sp)) return 0; /* retain good ones */ buf[num++] = (char) oc_sym; } buf[num] = '\0'; /* fill in any omitted classes, using previous ordering */ for (sp = flags.inv_order; *sp; sp++) if (!index(buf, *sp)) { buf[num++] = *sp; buf[num] = '\0'; /* explicitly terminate for next index() */ } Strcpy(flags.inv_order, buf); return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,075
ghostscript
6d444c273da5499a4cd72f21cb6d4c9a5256807d
void errflush(const gs_memory_t *mem) { if (!mem->gs_lib_ctx->stderr_fn) fflush(mem->gs_lib_ctx->fstderr); /* else nothing to flush */ }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,088
linux
34fad54c2537f7c99d07375e50cb30aa3c23bd83
static inline size_t flow_keys_hash_length(const struct flow_keys *flow) { size_t diff = FLOW_KEYS_HASH_OFFSET + sizeof(flow->addrs); BUILD_BUG_ON((sizeof(*flow) - FLOW_KEYS_HASH_OFFSET) % sizeof(u32)); BUILD_BUG_ON(offsetof(typeof(*flow), addrs) != sizeof(*flow) - sizeof(flow->addrs)); switch (flow->control.addr_type) { case FLOW_DISSECTOR_KEY_IPV4_ADDRS: diff -= sizeof(flow->addrs.v4addrs); break; case FLOW_DISSECTOR_KEY_IPV6_ADDRS: diff -= sizeof(flow->addrs.v6addrs); break; case FLOW_DISSECTOR_KEY_TIPC_ADDRS: diff -= sizeof(flow->addrs.tipcaddrs); break; } return (sizeof(*flow) - diff) / sizeof(u32); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,574
FFmpeg
77bb0004bbe18f1498cfecdc68db5f10808b6599
static void rpza_decode_stream(RpzaContext *s) { int width = s->avctx->width; int stride = s->frame->linesize[0] / 2; int row_inc = stride - 4; int chunk_size; uint16_t colorA = 0, colorB; uint16_t color4[4]; uint16_t ta, tb; uint16_t *pixels = (uint16_t *)s->frame->data[0]; int row_ptr = 0; int pixel_ptr = 0; int block_ptr; int pixel_x, pixel_y; int total_blocks; /* First byte is always 0xe1. Warn if it's different */ if (bytestream2_peek_byte(&s->gb) != 0xe1) av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n", bytestream2_peek_byte(&s->gb)); /* Get chunk size, ingnoring first byte */ chunk_size = bytestream2_get_be32(&s->gb) & 0x00FFFFFF; /* If length mismatch use size from MOV file and try to decode anyway */ if (chunk_size != bytestream2_get_bytes_left(&s->gb) - 4) av_log(s->avctx, AV_LOG_WARNING, "MOV chunk size != encoded chunk size\n"); /* Number of 4x4 blocks in frame. */ total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4); /* Process chunk data */ while (bytestream2_get_bytes_left(&s->gb)) { uint8_t opcode = bytestream2_get_byte(&s->gb); /* Get opcode */ int n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */ /* If opcode MSbit is 0, we need more data to decide what to do */ if ((opcode & 0x80) == 0) { colorA = (opcode << 8) | bytestream2_get_byte(&s->gb); opcode = 0; if ((bytestream2_peek_byte(&s->gb) & 0x80) != 0) { /* Must behave as opcode 110xxxxx, using colorA computed * above. Use fake opcode 0x20 to enter switch block at * the right place */ opcode = 0x20; n_blocks = 1; } } n_blocks = FFMIN(n_blocks, total_blocks); switch (opcode & 0xe0) { /* Skip blocks */ case 0x80: while (n_blocks--) { ADVANCE_BLOCK(); } break; /* Fill blocks with one color */ case 0xa0: colorA = bytestream2_get_be16(&s->gb); while (n_blocks--) { block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); } break; /* Fill blocks with 4 colors */ case 0xc0: colorA = bytestream2_get_be16(&s->gb); case 0x20: colorB = bytestream2_get_be16(&s->gb); /* sort out the colors */ color4[0] = colorB; color4[1] = 0; color4[2] = 0; color4[3] = colorA; /* red components */ ta = (colorA >> 10) & 0x1F; tb = (colorB >> 10) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10; /* green components */ ta = (colorA >> 5) & 0x1F; tb = (colorB >> 5) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5; /* blue components */ ta = colorA & 0x1F; tb = colorB & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5); color4[2] |= ((21 * ta + 11 * tb) >> 5); if (bytestream2_get_bytes_left(&s->gb) < n_blocks * 4) return; while (n_blocks--) { block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { uint8_t index = bytestream2_get_byteu(&s->gb); for (pixel_x = 0; pixel_x < 4; pixel_x++){ uint8_t idx = (index >> (2 * (3 - pixel_x))) & 0x03; pixels[block_ptr] = color4[idx]; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); } break; /* Fill block with 16 colors */ case 0x00: if (bytestream2_get_bytes_left(&s->gb) < 30) return; block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ /* We already have color of upper left pixel */ if ((pixel_y != 0) || (pixel_x != 0)) colorA = bytestream2_get_be16u(&s->gb); pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); break; /* Unknown opcode */ default: av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk." " Skip remaining %d bytes of chunk data.\n", opcode, bytestream2_get_bytes_left(&s->gb)); return; } /* Opcode switch */ } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,389