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
mbed-coap
4647a68e364401e81dbd370728127d844f221d93
static uint32_t sn_coap_parser_options_parse_uint(uint8_t **packet_data_pptr, uint8_t option_len) { uint32_t value = 0; while (option_len--) { value <<= 8; value |= *(*packet_data_pptr)++; } return value; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,182
oniguruma
850bd9b0d8186eb1637722b46b12656814ab4ad2
callout_name_table_hash(st_callout_name_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } /* use intptr_t for escape warning in Windows */ return val + (val >> 5) + ((intptr_t )x->enc & 0xffff) + x->type; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,520
Chrome
d304b5ec1b16766ea2cb552a27dc14df848d6a0e
FFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() { if (codec_context_) { av_free(codec_context_->extradata); avcodec_close(codec_context_); av_free(codec_context_); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,143
linux
606142af57dad981b78707234cfbd15f9f7b7125
static int su3000_power_ctrl(struct dvb_usb_device *d, int i) { struct dw2102_state *state = (struct dw2102_state *)d->priv; u8 obuf[] = {0xde, 0}; info("%s: %d, initialized %d", __func__, i, state->initialized); if (i && !state->initialized) { state->initialized = 1; /* reset board */ return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0); } return 0; }
1
CVE-2017-8062
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,932
Chrome
deaa07bec5d105ffc546d37eba3da4cba341fc03
void LogoService::GetLogo(LogoCallbacks callbacks) { if (!template_url_service_) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); if (!template_url) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); GURL logo_url; if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) { logo_url = GURL( command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL)); } else { #if defined(OS_ANDROID) logo_url = template_url->logo_url(); #endif } GURL base_url; GURL doodle_url; const bool is_google = template_url->url_ref().HasGoogleBaseURLs( template_url_service_->search_terms_data()); if (is_google) { base_url = GURL(template_url_service_->search_terms_data().GoogleBaseURLValue()); doodle_url = search_provider_logos::GetGoogleDoodleURL(base_url); } else if (base::FeatureList::IsEnabled(features::kThirdPartyDoodles)) { if (command_line->HasSwitch(switches::kThirdPartyDoodleURL)) { doodle_url = GURL( command_line->GetSwitchValueASCII(switches::kThirdPartyDoodleURL)); } else { std::string override_url = base::GetFieldTrialParamValueByFeature( features::kThirdPartyDoodles, features::kThirdPartyDoodlesOverrideUrlParam); if (!override_url.empty()) { doodle_url = GURL(override_url); } else { doodle_url = template_url->doodle_url(); } } base_url = doodle_url.GetOrigin(); } if (!logo_url.is_valid() && !doodle_url.is_valid()) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const bool use_fixed_logo = !doodle_url.is_valid(); if (!logo_tracker_) { std::unique_ptr<LogoCache> logo_cache = std::move(logo_cache_for_test_); if (!logo_cache) { logo_cache = std::make_unique<LogoCache>(cache_directory_); } std::unique_ptr<base::Clock> clock = std::move(clock_for_test_); if (!clock) { clock = std::make_unique<base::DefaultClock>(); } logo_tracker_ = std::make_unique<LogoTracker>( request_context_getter_, std::make_unique<LogoDelegateImpl>(std::move(image_decoder_)), std::move(logo_cache), std::move(clock)); } if (use_fixed_logo) { logo_tracker_->SetServerAPI( logo_url, base::Bind(&search_provider_logos::ParseFixedLogoResponse), base::Bind(&search_provider_logos::UseFixedLogoUrl)); } else if (is_google) { logo_tracker_->SetServerAPI( doodle_url, search_provider_logos::GetGoogleParseLogoResponseCallback(base_url), search_provider_logos::GetGoogleAppendQueryparamsCallback( use_gray_background_)); } else { logo_tracker_->SetServerAPI( doodle_url, base::Bind(&search_provider_logos::GoogleNewParseLogoResponse, base_url), base::Bind(&search_provider_logos::GoogleNewAppendQueryparamsToLogoURL, use_gray_background_)); } logo_tracker_->GetLogo(std::move(callbacks)); }
1
CVE-2015-1290
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,325
linux
3a9b153c5591548612c3955c9600a98150c81875
int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, "info: WMM: WMM_GET_STATUS cmdresp received: %d\n", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "QSTATUS TLV: %d, %d, %d\n", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "WMM Parameter Set Count: %d\n", wmm_param_ie->qos_info_bitmap & mask); memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; }
1
CVE-2020-12654
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).
1,300
Android
92a7bf8c44a236607c146240f3c0adc1ae01fedf
void rfc_send_sabme(tRFC_MCB* p_mcb, uint8_t dlci) { uint8_t* p_data; uint8_t cr = RFCOMM_CR(p_mcb->is_initiator, true); BT_HDR* p_buf = (BT_HDR*)osi_malloc(RFCOMM_CMD_BUF_SIZE); p_buf->offset = L2CAP_MIN_OFFSET; p_data = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; /* SABME frame, command, PF = 1, dlci */ *p_data++ = RFCOMM_EA | cr | (dlci << RFCOMM_SHIFT_DLCI); *p_data++ = RFCOMM_SABME | RFCOMM_PF; *p_data++ = RFCOMM_EA | 0; *p_data = RFCOMM_SABME_FCS((uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET, cr, dlci); p_buf->len = 4; rfc_check_send_cmd(p_mcb, p_buf); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,371
Chrome
eea3300239f0b53e172a320eb8de59d0bea65f27
void DevToolsUIBindings::CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); web_contents_->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript)); }
1
CVE-2017-5011
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.
1,346
Chrome
b8573aa643b03a59f4e2c99c72d3511a11cfb0b6
void GestureSequence::AppendScrollGestureUpdate(const GesturePoint& point, const gfx::Point& location, Gestures* gestures) { int dx = point.x_delta(); int dy = point.y_delta(); if (scroll_type_ == ST_HORIZONTAL) dy = 0; else if (scroll_type_ == ST_VERTICAL) dx = 0; gestures->push_back(linked_ptr<GestureEvent>(new GestureEvent( ui::ET_GESTURE_SCROLL_UPDATE, location.x(), location.y(), flags_, base::Time::FromDoubleT(point.last_touch_time()), dx, dy))); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,213
linux
ced39002f5ea736b716ae233fb68b26d59783912
__kprobes void *perf_trace_buf_prepare(int size, unsigned short type, struct pt_regs *regs, int *rctxp) { struct trace_entry *entry; unsigned long flags; char *raw_data; int pc; BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(unsigned long)); pc = preempt_count(); *rctxp = perf_swevent_get_recursion_context(); if (*rctxp < 0) return NULL; raw_data = this_cpu_ptr(perf_trace_buf[*rctxp]); /* zero the dead bytes from align to not leak stack to user */ memset(&raw_data[size - sizeof(u64)], 0, sizeof(u64)); entry = (struct trace_entry *)raw_data; local_save_flags(flags); tracing_generic_entry_update(entry, flags, pc); entry->type = type; return raw_data; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,584
contiki-ng
12c824386ab60de757de5001974d73b32e19ad71
snmp_api_add_resource(snmp_mib_resource_t *new_resource) { return snmp_mib_add(new_resource); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,563
git
1a7fd1fb2998002da6e9ff2ee46e1bdd25ee8404
static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); if (!strcmp(key, "path") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_PATH, "disallowed submodule path: %s", value); free(name); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,489
libmysofa
d39a171e9c6a1c44dbdf43f9db6c3fbd887e38c1
int btreeRead(struct READER *reader, struct BTREE *btree) { char buf[4]; /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "BTHD", 4)) { log("cannot read signature of BTHD\n"); return MYSOFA_INVALID_FORMAT; } log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); if (fgetc(reader->fhd) != 0) { log("object BTHD must have version 0\n"); return MYSOFA_INVALID_FORMAT; } btree->type = (uint8_t)fgetc(reader->fhd); btree->node_size = (uint32_t)readValue(reader, 4); btree->record_size = (uint16_t)readValue(reader, 2); btree->depth = (uint16_t)readValue(reader, 2); btree->split_percent = (uint8_t)fgetc(reader->fhd); btree->merge_percent = (uint8_t)fgetc(reader->fhd); btree->root_node_address = (uint64_t)readValue(reader, reader->superblock.size_of_offsets); btree->number_of_records = (uint16_t)readValue(reader, 2); if(btree->number_of_records>0x1000) return MYSOFA_UNSUPPORTED_FORMAT; btree->total_number = (uint64_t)readValue(reader, reader->superblock.size_of_lengths); /* fseek(reader->fhd, 4, SEEK_CUR); skip checksum */ if(btree->total_number > 0x10000000) return MYSOFA_NO_MEMORY; btree->records = malloc(sizeof(btree->records[0]) * btree->total_number); if (!btree->records) return MYSOFA_NO_MEMORY; memset(btree->records, 0, sizeof(btree->records[0]) * btree->total_number); /* read records */ if(fseek(reader->fhd, btree->root_node_address, SEEK_SET)<0) return errno; return readBTLF(reader, btree, btree->number_of_records, btree->records); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,567
ImageMagick
d63a3c5729df59f183e9e110d5d8385d17caaad0
MagickExport MagickBooleanType IsOpaqueImage(const Image *image, ExceptionInfo *exception) { CacheView *image_view; register const PixelPacket *p; register ssize_t x; ssize_t y; /* Determine if image is opaque. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->matte == MagickFalse) return(MagickTrue); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) break; p++; } if (x < (ssize_t) image->columns) break; } image_view=DestroyCacheView(image_view); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,342
Chrome
5405341d5cc268a0b2ff0678bd78ddda0892e7ea
RenderFrameImpl::RenderFrameImpl(CreateParams params) : frame_(nullptr), is_main_frame_(true), unique_name_frame_adapter_(this), unique_name_helper_(&unique_name_frame_adapter_), in_frame_tree_(false), render_view_(params.render_view), routing_id_(params.routing_id), proxy_routing_id_(MSG_ROUTING_NONE), #if BUILDFLAG(ENABLE_PLUGINS) plugin_power_saver_helper_(nullptr), #endif cookie_jar_(this), selection_text_offset_(0), selection_range_(gfx::Range::InvalidRange()), handling_select_range_(false), web_user_media_client_(nullptr), push_messaging_client_(nullptr), render_accessibility_(nullptr), previews_state_(PREVIEWS_UNSPECIFIED), effective_connection_type_( blink::WebEffectiveConnectionType::kTypeUnknown), is_pasting_(false), suppress_further_dialogs_(false), blame_context_(nullptr), #if BUILDFLAG(ENABLE_PLUGINS) focused_pepper_plugin_(nullptr), pepper_last_mouse_event_target_(nullptr), #endif autoplay_configuration_binding_(this), frame_binding_(this), host_zoom_binding_(this), frame_bindings_control_binding_(this), frame_navigation_control_binding_(this), fullscreen_binding_(this), navigation_client_impl_(nullptr), has_accessed_initial_document_(false), media_factory_(this, base::Bind(&RenderFrameImpl::RequestOverlayRoutingToken, base::Unretained(this))), input_target_client_impl_(this), devtools_frame_token_(params.devtools_frame_token), weak_factory_(this) { CHECK(params.interface_provider.is_bound()); remote_interfaces_.Bind(std::move(params.interface_provider)); blink_interface_registry_.reset(new BlinkInterfaceRegistryImpl( registry_.GetWeakPtr(), associated_interfaces_.GetWeakPtr())); media_factory_.SetupMojo(); std::pair<RoutingIDFrameMap::iterator, bool> result = g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this)); CHECK(result.second) << "Inserting a duplicate item."; #if defined(OS_ANDROID) new GinJavaBridgeDispatcher(this); #endif #if BUILDFLAG(ENABLE_PLUGINS) plugin_power_saver_helper_ = new PluginPowerSaverHelper(this); #endif manifest_manager_ = std::make_unique<ManifestManager>(this); if (IsMainFrame()) { new ManifestChangeNotifier(this); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,707
tensorflow
a5b89cd68c02329d793356bda85d079e9e69b4e7
Status StoreResourceDtypesAndShapes(const eager::Operation& remote_op, const DataTypeVector& output_dtypes, TensorHandle** retvals) { if (remote_op.name() == "VarHandleOp") { if (output_dtypes.size() != 1) { return errors::Internal("VarHandleOp should only have one output."); } if (output_dtypes[0] != DT_RESOURCE) { return errors::Internal( "The output of VarHandleOp should be a DT_RESOURCE."); } AttrSlice attr_slice = AttrSlice(&remote_op.attrs()); const AttrValue* dtype; TF_RETURN_IF_ERROR(attr_slice.Find("dtype", &dtype)); const AttrValue* shape; TF_RETURN_IF_ERROR(attr_slice.Find("shape", &shape)); retvals[0]->SetResourceHandleDtypeAndShape( {DtypeAndPartialTensorShape{dtype->type(), shape->shape()}}); } return Status::OK(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,051
acpica
987a3b5cf7175916e2a4b6ea5b8e70f830dfe732
AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ AcpiDsObjStackPopAndDelete (ArgCount, WalkState); ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); }
1
CVE-2017-13693
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.
4,038
linux
ea25f914dc164c8d56b36147ecc86bc65f83c469
static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; }
1
CVE-2017-17857
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,579
openssl
259b664f950c2ba66fbf4b0fe5281327904ead21
static void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); }
1
CVE-2016-0798
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
6,696
util-linux
89e90ae7b2826110ea28c1c0eb8e7c56c3907bdc
static int parse_dev(blkid_cache cache, blkid_dev *dev, char **cp) { char *start, *tmp, *end, *name; int ret; if ((ret = parse_start(cp)) <= 0) return ret; start = tmp = strchr(*cp, '>'); if (!start) { DBG(READ, ul_debug("blkid: short line parsing dev: %s", *cp)); return -BLKID_ERR_CACHE; } start = skip_over_blank(start + 1); end = skip_over_word(start); DBG(READ, ul_debug("device should be %*s", (int)(end - start), start)); if (**cp == '>') *cp = end; else (*cp)++; *tmp = '\0'; if (!(tmp = strrchr(end, '<')) || parse_end(&tmp) < 0) { DBG(READ, ul_debug("blkid: missing </device> ending: %s", end)); } else if (tmp) *tmp = '\0'; if (end - start <= 1) { DBG(READ, ul_debug("blkid: empty device name: %s", *cp)); return -BLKID_ERR_CACHE; } name = strndup(start, end - start); if (name == NULL) return -BLKID_ERR_MEM; DBG(READ, ul_debug("found dev %s", name)); if (!(*dev = blkid_get_dev(cache, name, BLKID_DEV_CREATE))) { free(name); return -BLKID_ERR_MEM; } free(name); return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,171
linux
beb39db59d14990e401e235faf66a6b9b31240b0
void udp_set_csum(bool nocheck, struct sk_buff *skb, __be32 saddr, __be32 daddr, int len) { struct udphdr *uh = udp_hdr(skb); if (nocheck) uh->check = 0; else if (skb_is_gso(skb)) uh->check = ~udp_v4_check(len, saddr, daddr, 0); else if (skb_dst(skb) && skb_dst(skb)->dev && (skb_dst(skb)->dev->features & NETIF_F_V4_CSUM)) { BUG_ON(skb->ip_summed == CHECKSUM_PARTIAL); skb->ip_summed = CHECKSUM_PARTIAL; skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); uh->check = ~udp_v4_check(len, saddr, daddr, 0); } else { __wsum csum; BUG_ON(skb->ip_summed == CHECKSUM_PARTIAL); uh->check = 0; csum = skb_checksum(skb, 0, len, 0); uh->check = udp_v4_check(len, saddr, daddr, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; skb->ip_summed = CHECKSUM_UNNECESSARY; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,485
pgbouncer
7ca3e5279d05fceb1e8a043c6f5b6f58dea3ed38
static bool handle_client_startup(PgSocket *client, PktHdr *pkt) { const char *passwd; const uint8_t *key; bool ok; SBuf *sbuf = &client->sbuf; /* don't tolerate partial packets */ if (incomplete_pkt(pkt)) { disconnect_client(client, true, "client sent partial pkt in startup phase"); return false; } if (client->wait_for_welcome) { if (finish_client_login(client)) { /* the packet was already parsed */ sbuf_prepare_skip(sbuf, pkt->len); return true; } else { return false; } } switch (pkt->type) { case PKT_SSLREQ: slog_noise(client, "C: req SSL"); if (client->sbuf.tls) { disconnect_client(client, false, "SSL req inside SSL"); return false; } if (cf_client_tls_sslmode != SSLMODE_DISABLED) { slog_noise(client, "P: SSL ack"); if (!sbuf_answer(&client->sbuf, "S", 1)) { disconnect_client(client, false, "failed to ack SSL"); return false; } if (!sbuf_tls_accept(&client->sbuf)) { disconnect_client(client, false, "failed to accept SSL"); return false; } break; } /* reject SSL attempt */ slog_noise(client, "P: nak"); if (!sbuf_answer(&client->sbuf, "N", 1)) { disconnect_client(client, false, "failed to nak SSL"); return false; } break; case PKT_STARTUP_V2: disconnect_client(client, true, "Old V2 protocol not supported"); return false; case PKT_STARTUP: /* require SSL except on unix socket */ if (cf_client_tls_sslmode >= SSLMODE_REQUIRE && !client->sbuf.tls && !pga_is_unix(&client->remote_addr)) { disconnect_client(client, true, "SSL required"); return false; } if (client->pool && !client->wait_for_user_conn && !client->wait_for_user) { disconnect_client(client, true, "client re-sent startup pkt"); return false; } if (client->wait_for_user) { client->wait_for_user = false; if (!finish_set_pool(client, false)) return false; } else if (!decide_startup_pool(client, pkt)) { return false; } break; case 'p': /* PasswordMessage */ /* too early */ if (!client->auth_user) { disconnect_client(client, true, "client password pkt before startup packet"); return false; } ok = mbuf_get_string(&pkt->data, &passwd); if (ok && check_client_passwd(client, passwd)) { if (!finish_client_login(client)) return false; } else { disconnect_client(client, true, "Auth failed"); return false; } break; case PKT_CANCEL: if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN && mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key)) { memcpy(client->cancel_key, key, BACKENDKEY_LEN); accept_cancel_request(client); } else { disconnect_client(client, false, "bad cancel request"); } return false; default: disconnect_client(client, false, "bad packet"); return false; } sbuf_prepare_skip(sbuf, pkt->len); client->request_time = get_cached_time(); return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,263
linux
050fad7c4534c13c8eb1d9c2ba66012e014773cb
BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset, u64, from, u64, to, u64, flags) { __sum16 *ptr; if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK))) return -EINVAL; if (unlikely(offset > 0xffff || offset & 1)) return -EFAULT; if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr)))) return -EFAULT; ptr = (__sum16 *)(skb->data + offset); switch (flags & BPF_F_HDR_FIELD_MASK) { case 0: if (unlikely(from != 0)) return -EINVAL; csum_replace_by_diff(ptr, to); break; case 2: csum_replace2(ptr, from, to); break; case 4: csum_replace4(ptr, from, to); break; default: return -EINVAL; } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,695
sqlite
18f6ff9eb7db02356102283c28053b0a602f55d7
static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ Fts3Table *p = (Fts3Table *)pVTab; int i; /* Iterator variable */ int iCons = -1; /* Index of constraint to use */ int iLangidCons = -1; /* Index of langid=x constraint, if present */ int iDocidGe = -1; /* Index of docid>=x constraint, if present */ int iDocidLe = -1; /* Index of docid<=x constraint, if present */ int iIdx; /* By default use a full table scan. This is an expensive option, ** so search through the constraints to see if a more efficient ** strategy is possible. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 5000000; for(i=0; i<pInfo->nConstraint; i++){ int bDocid; /* True if this constraint is on docid */ struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; if( pCons->usable==0 ){ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ /* There exists an unusable MATCH constraint. This means that if ** the planner does elect to use the results of this call as part ** of the overall query plan the user will see an "unable to use ** function MATCH in the requested context" error. To discourage ** this, return a very high cost here. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 1e50; fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50); return SQLITE_OK; } continue; } bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ pInfo->idxNum = FTS3_DOCID_SEARCH; pInfo->estimatedCost = 1.0; iCons = i; } /* A MATCH constraint. Use a full-text search. ** ** If there is more than one MATCH constraint available, use the first ** one encountered. If there is both a MATCH constraint and a direct ** rowid/docid lookup, prefer the MATCH strategy. This is done even ** though the rowid/docid lookup is faster than a MATCH query, selecting ** it would lead to an "unable to use function MATCH in the requested ** context" error. */ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn ){ pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; pInfo->estimatedCost = 2.0; iCons = i; } /* Equality constraint on the langid column */ if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && pCons->iColumn==p->nColumn + 2 ){ iLangidCons = i; } if( bDocid ){ switch( pCons->op ){ case SQLITE_INDEX_CONSTRAINT_GE: case SQLITE_INDEX_CONSTRAINT_GT: iDocidGe = i; break; case SQLITE_INDEX_CONSTRAINT_LE: case SQLITE_INDEX_CONSTRAINT_LT: iDocidLe = i; break; } } } iIdx = 1; if( iCons>=0 ){ pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; pInfo->aConstraintUsage[iCons].omit = 1; } if( iLangidCons>=0 ){ pInfo->idxNum |= FTS3_HAVE_LANGID; pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; } if( iDocidGe>=0 ){ pInfo->idxNum |= FTS3_HAVE_DOCID_GE; pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; } if( iDocidLe>=0 ){ pInfo->idxNum |= FTS3_HAVE_DOCID_LE; pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; } /* Regardless of the strategy selected, FTS can deliver rows in rowid (or ** docid) order. Both ascending and descending are possible. */ if( pInfo->nOrderBy==1 ){ struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ if( pOrder->desc ){ pInfo->idxStr = "DESC"; }else{ pInfo->idxStr = "ASC"; } pInfo->orderByConsumed = 1; } } assert( p->pSegments==0 ); return SQLITE_OK; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,096
tcpdump
5d0d76e88ee2d3236d7e032589d6f1d4ec5f7b1e
isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); }
1
CVE-2017-13055
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.
6,090
php-src
5c0455bf2c8cd3c25401407f158e820aa3b239e1
static void timelib_skip_day_suffix(char **ptr) { if (isspace(**ptr)) { return; } if (!strncasecmp(*ptr, "nd", 2) || !strncasecmp(*ptr, "rd", 2) ||!strncasecmp(*ptr, "st", 2) || !strncasecmp(*ptr, "th", 2)) { *ptr += 2; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,952
samba
7f51ec8c4ed9ba1f53d722e44fb6fb3cde933b72
static int ldb_dn_escape_internal(char *dst, const char *src, int len) { const char *p, *s; char *d; size_t l; p = s = src; d = dst; while (p - src < len) { p += strcspn(p, ",=\n\r+<>#;\\\" "); if (p - src == len) /* found no escapable chars */ break; /* copy the part of the string before the stop */ memcpy(d, s, p - s); d += (p - s); /* move to current position */ switch (*p) { case ' ': if (p == src || (p-src)==(len-1)) { /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; case '?': /* these must be escaped using \c form */ *d++ = '\\'; *d++ = *p++; break; default: { /* any others get \XX form */ unsigned char v; const char *hexbytes = "0123456789ABCDEF"; v = *(const unsigned char *)p; *d++ = '\\'; *d++ = hexbytes[v>>4]; *d++ = hexbytes[v&0xF]; p++; break; } } s = p; /* move forward */ }
1
CVE-2015-5330
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,029
ImageMagick
53c1dcd34bed85181b901bfce1a2322f85a59472
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,060
tensorflow
bb6a0383ed553c286f87ca88c207f6774d5c4a8f
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* params; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kParams, &params)); const TfLiteTensor* indices; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kIndices, &indices)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); // Prevent division by 0 in the helper TF_LITE_ENSURE(context, NumElements(params) > 0); switch (indices->type) { case kTfLiteInt32: return EvalGatherNd<int32_t>(context, params, indices, output); case kTfLiteInt64: return EvalGatherNd<int64_t>(context, params, indices, output); default: context->ReportError( context, "Indices of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(indices->type)); return kTfLiteError; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,462
lua
6298903e35217ab69c279056f925fb72900ce0b7
void luaD_hookcall (lua_State *L, CallInfo *ci) { int hook = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL; Proto *p; if (!(L->hookmask & LUA_MASKCALL)) /* some other hook? */ return; /* don't call hook */ p = clLvalue(s2v(ci->func))->p; L->top = ci->top; /* prepare top */ ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ luaD_hook(L, hook, -1, 1, p->numparams); ci->u.l.savedpc--; /* correct 'pc' */ }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,856
php-src
7b1898183032eeabc64a086ff040af991cebcd93
static HashTable *date_object_get_properties_period(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_period_obj *period_obj; period_obj = zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!period_obj->start || GC_G(gc_active)) { return props; } MAKE_STD_ZVAL(zv); if (period_obj->start) { php_date_obj *date_obj; object_init_ex(zv, date_ce_date); date_obj = zend_object_store_get_object(zv TSRMLS_CC); date_obj->time = timelib_time_clone(period_obj->start); } else { ZVAL_NULL(zv); } zend_hash_update(props, "start", sizeof("start"), &zv, sizeof(zv), NULL); MAKE_STD_ZVAL(zv); if (period_obj->current) { php_date_obj *date_obj; object_init_ex(zv, date_ce_date); date_obj = zend_object_store_get_object(zv TSRMLS_CC); date_obj->time = timelib_time_clone(period_obj->current); } else { ZVAL_NULL(zv); } zend_hash_update(props, "current", sizeof("current"), &zv, sizeof(zv), NULL); MAKE_STD_ZVAL(zv); if (period_obj->end) { php_date_obj *date_obj; object_init_ex(zv, date_ce_date); date_obj = zend_object_store_get_object(zv TSRMLS_CC); date_obj->time = timelib_time_clone(period_obj->end); } else { ZVAL_NULL(zv); } zend_hash_update(props, "end", sizeof("end"), &zv, sizeof(zv), NULL); MAKE_STD_ZVAL(zv); if (period_obj->interval) { php_interval_obj *interval_obj; object_init_ex(zv, date_ce_interval); interval_obj = zend_object_store_get_object(zv TSRMLS_CC); interval_obj->diff = timelib_rel_time_clone(period_obj->interval); interval_obj->initialized = 1; } else { ZVAL_NULL(zv); } zend_hash_update(props, "interval", sizeof("interval"), &zv, sizeof(zv), NULL); /* converted to larger type (int->long); must check when unserializing */ MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, (long) period_obj->recurrences); zend_hash_update(props, "recurrences", sizeof("recurrences"), &zv, sizeof(zv), NULL); MAKE_STD_ZVAL(zv); ZVAL_BOOL(zv, period_obj->include_start_date); zend_hash_update(props, "include_start_date", sizeof("include_start_date"), &zv, sizeof(zv), NULL); return props;
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,953
mbedtls
97b5209bc01ab8b3b519fdb46cefc04739433124
int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start, const unsigned char *buf, size_t bits ) { int ret; size_t len = 0, size; size = ( bits / 8 ) + ( ( bits % 8 ) ? 1 : 0 ); // Calculate byte length // if( *p < start || (size_t)( *p - start ) < size + 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); len = size + 1; (*p) -= size; memcpy( *p, buf, size ); // Write unused bits // *--(*p) = (unsigned char) (size * 8 - bits); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) ); return( (int) len ); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,136
Android
04839626ed859623901ebd3a5fd483982186b59d
const BlockEntry* Cues::GetBlock( const CuePoint* pCP, const CuePoint::TrackPosition* pTP) const { if (pCP == NULL) return NULL; if (pTP == NULL) return NULL; return m_pSegment->GetBlock(*pCP, *pTP); }
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).
6,750
illumos-gate
d65686849024838243515b5c40ae2c479460b4b5
devzvol_validate(struct sdev_node *dv) { dmu_objset_type_t do_type; char *dsname; char *nm = dv->sdev_name; int rc; sdcmn_err13(("validating ('%s' '%s')", dv->sdev_path, nm)); /* * validate only READY nodes; if someone is sitting on the * directory of a dataset that just got destroyed we could * get a zombie node which we just skip. */ if (dv->sdev_state != SDEV_READY) { sdcmn_err13(("skipping '%s'", nm)); return (SDEV_VTOR_SKIP); } if ((strcmp(dv->sdev_path, ZVOL_DIR "/dsk") == 0) || (strcmp(dv->sdev_path, ZVOL_DIR "/rdsk") == 0)) return (SDEV_VTOR_VALID); dsname = devzvol_make_dsname(dv->sdev_path, NULL); if (dsname == NULL) return (SDEV_VTOR_INVALID); rc = devzvol_objset_check(dsname, &do_type); sdcmn_err13((" '%s' rc %d", dsname, rc)); if (rc != 0) { kmem_free(dsname, strlen(dsname) + 1); return (SDEV_VTOR_INVALID); } sdcmn_err13((" v_type %d do_type %d", SDEVTOV(dv)->v_type, do_type)); if ((SDEVTOV(dv)->v_type == VLNK && do_type != DMU_OST_ZVOL) || ((SDEVTOV(dv)->v_type == VBLK || SDEVTOV(dv)->v_type == VCHR) && do_type != DMU_OST_ZVOL) || (SDEVTOV(dv)->v_type == VDIR && do_type == DMU_OST_ZVOL)) { kmem_free(dsname, strlen(dsname) + 1); return (SDEV_VTOR_STALE); } if (SDEVTOV(dv)->v_type == VLNK) { char *ptr, *link; long val = 0; minor_t lminor, ominor; rc = sdev_getlink(SDEVTOV(dv), &link); ASSERT(rc == 0); ptr = strrchr(link, ':') + 1; rc = ddi_strtol(ptr, NULL, 10, &val); kmem_free(link, strlen(link) + 1); ASSERT(rc == 0 && val != 0); lminor = (minor_t)val; if (sdev_zvol_name2minor(dsname, &ominor) < 0 || ominor != lminor) { kmem_free(dsname, strlen(dsname) + 1); return (SDEV_VTOR_STALE); } } kmem_free(dsname, strlen(dsname) + 1); return (SDEV_VTOR_VALID); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,259
Little-CMS
049d634ea6bf2a9bafbf9ddef18464be9caa567f
cmsPipeline* _cmsCreateGamutCheckPipeline(cmsContext ContextID, cmsHPROFILE hProfiles[], cmsBool BPC[], cmsUInt32Number Intents[], cmsFloat64Number AdaptationStates[], cmsUInt32Number nGamutPCSposition, cmsHPROFILE hGamut) { cmsHPROFILE hLab; cmsPipeline* Gamut; cmsStage* CLUT; cmsUInt32Number dwFormat; GAMUTCHAIN Chain; int nChannels, nGridpoints; cmsColorSpaceSignature ColorSpace; cmsUInt32Number i; cmsHPROFILE ProfileList[256]; cmsBool BPCList[256]; cmsFloat64Number AdaptationList[256]; cmsUInt32Number IntentList[256]; memset(&Chain, 0, sizeof(GAMUTCHAIN)); if (nGamutPCSposition <= 0 || nGamutPCSposition > 255) { cmsSignalError(ContextID, cmsERROR_RANGE, "Wrong position of PCS. 1..255 expected, %d found.", nGamutPCSposition); return NULL; } hLab = cmsCreateLab4ProfileTHR(ContextID, NULL); if (hLab == NULL) return NULL; // The figure of merit. On matrix-shaper profiles, should be almost zero as // the conversion is pretty exact. On LUT based profiles, different resolutions // of input and output CLUT may result in differences. if (cmsIsMatrixShaper(hGamut)) { Chain.Thereshold = 1.0; } else { Chain.Thereshold = ERR_THERESHOLD; } // Create a copy of parameters for (i=0; i < nGamutPCSposition; i++) { ProfileList[i] = hProfiles[i]; BPCList[i] = BPC[i]; AdaptationList[i] = AdaptationStates[i]; IntentList[i] = Intents[i]; } // Fill Lab identity ProfileList[nGamutPCSposition] = hLab; BPCList[nGamutPCSposition] = 0; AdaptationList[nGamutPCSposition] = 1.0; IntentList[nGamutPCSposition] = INTENT_RELATIVE_COLORIMETRIC; ColorSpace = cmsGetColorSpace(hGamut); nChannels = cmsChannelsOf(ColorSpace); nGridpoints = _cmsReasonableGridpointsByColorspace(ColorSpace, cmsFLAGS_HIGHRESPRECALC); dwFormat = (CHANNELS_SH(nChannels)|BYTES_SH(2)); // 16 bits to Lab double Chain.hInput = cmsCreateExtendedTransform(ContextID, nGamutPCSposition + 1, ProfileList, BPCList, IntentList, AdaptationList, NULL, 0, dwFormat, TYPE_Lab_DBL, cmsFLAGS_NOCACHE); // Does create the forward step. Lab double to device dwFormat = (CHANNELS_SH(nChannels)|BYTES_SH(2)); Chain.hForward = cmsCreateTransformTHR(ContextID, hLab, TYPE_Lab_DBL, hGamut, dwFormat, INTENT_RELATIVE_COLORIMETRIC, cmsFLAGS_NOCACHE); // Does create the backwards step Chain.hReverse = cmsCreateTransformTHR(ContextID, hGamut, dwFormat, hLab, TYPE_Lab_DBL, INTENT_RELATIVE_COLORIMETRIC, cmsFLAGS_NOCACHE); // All ok? if (Chain.hInput && Chain.hForward && Chain.hReverse) { // Go on, try to compute gamut LUT from PCS. This consist on a single channel containing // dE when doing a transform back and forth on the colorimetric intent. Gamut = cmsPipelineAlloc(ContextID, 3, 1); if (Gamut != NULL) { CLUT = cmsStageAllocCLut16bit(ContextID, nGridpoints, nChannels, 1, NULL); if (!cmsPipelineInsertStage(Gamut, cmsAT_BEGIN, CLUT)) { cmsPipelineFree(Gamut); Gamut = NULL; } else cmsStageSampleCLut16bit(CLUT, GamutSampler, (void*) &Chain, 0); } } else Gamut = NULL; // Didn't work... // Free all needed stuff. if (Chain.hInput) cmsDeleteTransform(Chain.hInput); if (Chain.hForward) cmsDeleteTransform(Chain.hForward); if (Chain.hReverse) cmsDeleteTransform(Chain.hReverse); if (hLab) cmsCloseProfile(hLab); // And return computed hull return Gamut; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,293
linux
7b07f8eb75aa3097cdfd4f6eac3da49db787381d
static int ccid3_hc_rx_init(struct ccid *ccid, struct sock *sk) { struct ccid3_hc_rx_sock *hc = ccid_priv(ccid); hc->rx_state = TFRC_RSTATE_NO_DATA; tfrc_lh_init(&hc->rx_li_hist); return tfrc_rx_hist_alloc(&hc->rx_hist); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,805
openssl
97ab3c4b538840037812c8d9164d09a1f4bf11a1
static int set_altname_email(X509 *crt, const char *name) { return set_altname(crt, GEN_EMAIL, name, 0); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,494
qemu
204f01b30975923c64006f8067f0937b91eea68b
static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size) { VirtIOGPU *g = opaque; struct virtio_gpu_simple_resource *res; struct virtio_gpu_scanout *scanout; uint32_t resource_id, pformat; int i; resource_id = qemu_get_be32(f); while (resource_id != 0) { res = g_new0(struct virtio_gpu_simple_resource, 1); res->resource_id = resource_id; res->width = qemu_get_be32(f); res->height = qemu_get_be32(f); res->format = qemu_get_be32(f); res->iov_cnt = qemu_get_be32(f); /* allocate */ pformat = get_pixman_format(res->format); if (!pformat) { return -EINVAL; } res->image = pixman_image_create_bits(pformat, res->width, res->height, NULL, 0); if (!res->image) { return -EINVAL; } res->addrs = g_new(uint64_t, res->iov_cnt); res->iov = g_new(struct iovec, res->iov_cnt); /* read data */ for (i = 0; i < res->iov_cnt; i++) { res->addrs[i] = qemu_get_be64(f); res->iov[i].iov_len = qemu_get_be32(f); } qemu_get_buffer(f, (void *)pixman_image_get_data(res->image), pixman_image_get_stride(res->image) * res->height); /* restore mapping */ for (i = 0; i < res->iov_cnt; i++) { hwaddr len = res->iov[i].iov_len; res->iov[i].iov_base = cpu_physical_memory_map(res->addrs[i], &len, 1); if (!res->iov[i].iov_base || len != res->iov[i].iov_len) { return -EINVAL; } } QTAILQ_INSERT_HEAD(&g->reslist, res, next); resource_id = qemu_get_be32(f); } /* load & apply scanout state */ vmstate_load_state(f, &vmstate_virtio_gpu_scanouts, g, 1); for (i = 0; i < g->conf.max_outputs; i++) { scanout = &g->scanout[i]; if (!scanout->resource_id) { continue; } res = virtio_gpu_find_resource(g, scanout->resource_id); if (!res) { return -EINVAL; } scanout->ds = qemu_create_displaysurface_pixman(res->image); if (!scanout->ds) { return -EINVAL; } dpy_gfx_replace_surface(scanout->con, scanout->ds); dpy_gfx_update(scanout->con, 0, 0, scanout->width, scanout->height); update_cursor(g, &scanout->cursor); res->scanout_bitmask |= (1 << i); } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,974
linux
fc27fe7e8deef2f37cba3f2be2d52b6ca5eb9d57
static int snd_seq_device_dev_free(struct snd_device *device) { struct snd_seq_device *dev = device->device_data; put_device(&dev->dev); return 0; }
1
CVE-2017-16528
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
7,460
linux
f2e5ddcc0d12f9c4c7b254358ad245c9dddce13b
static inline int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr) { return -ENOSYS; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,897
hhvm
97ef580ec2cca9a54da6f9bd9fdd9a455f6d74ed
FastCGIServer::FastCGIServer(const std::string &address, int port, int workers, bool useFileSocket) : Server(address, port), m_worker(&m_eventBaseManager), m_dispatcher(workers, workers, RuntimeOption::ServerThreadDropCacheTimeoutSeconds, RuntimeOption::ServerThreadDropStack, this, RuntimeOption::ServerThreadJobLIFOSwitchThreshold, RuntimeOption::ServerThreadJobMaxQueuingMilliSeconds, RequestPriority::k_numPriorities) { folly::SocketAddress sock_addr; if (useFileSocket) { sock_addr.setFromPath(address); } else if (address.empty()) { sock_addr.setFromLocalPort(port); } else { sock_addr.setFromHostPort(address, port); } m_socketConfig.bindAddress = sock_addr; m_socketConfig.acceptBacklog = RuntimeOption::ServerBacklog; std::chrono::seconds timeout; if (RuntimeOption::ConnectionTimeoutSeconds >= 0) { timeout = std::chrono::seconds(RuntimeOption::ConnectionTimeoutSeconds); } else { // default to 2 minutes timeout = std::chrono::seconds(120); } m_socketConfig.connectionIdleTimeout = timeout; }
1
CVE-2019-3569
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.
5,108
Little-CMS
06d4557477e7ab3330a24d69af4c67adcac9acdf
int PCS2ITU(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo) { cmsCIELab Lab; cmsLabEncoded2Float(&Lab, In); cmsDesaturateLab(&Lab, 85, -85, 125, -75); // This function does the necessary gamut remapping Lab2ITU(&Lab, Out); return TRUE; UTILS_UNUSED_PARAMETER(Cargo); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,677
linux
f2fcfcd670257236ebf2088bbdf26f6a8ef459fe
static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data; u16 scid, flags, result; struct sock *sk; scid = __le16_to_cpu(rsp->scid); flags = __le16_to_cpu(rsp->flags); result = __le16_to_cpu(rsp->result); BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x", scid, flags, result); sk = l2cap_get_chan_by_scid(&conn->chan_list, scid); if (!sk) return 0; switch (result) { case L2CAP_CONF_SUCCESS: break; case L2CAP_CONF_UNACCEPT: if (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) { char req[128]; /* It does not make sense to adjust L2CAP parameters * that are currently defined in the spec. We simply * resend config request that we sent earlier. It is * stupid, but it helps qualification testing which * expects at least some response from us. */ l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, req), req); goto done; } default: sk->sk_state = BT_DISCONN; sk->sk_err = ECONNRESET; l2cap_sock_set_timer(sk, HZ * 5); { struct l2cap_disconn_req req; req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid); req.scid = cpu_to_le16(l2cap_pi(sk)->scid); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ, sizeof(req), &req); } goto done; } if (flags & 0x01) goto done; l2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); } done: bh_unlock_sock(sk); return 0; }
1
CVE-2017-1000251
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,717
sqlite
522ebfa7cee96fb325a22ea3a2464a63485886a8
static int lookupName( Parse *pParse, /* The parsing context */ const char *zDb, /* Name of the database containing table, or NULL */ const char *zTab, /* Name of table containing column, or NULL */ const char *zCol, /* Name of the column. */ NameContext *pNC, /* The name context used to resolve the name */ Expr *pExpr /* Make this EXPR node point to the selected column */ ){ int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ sqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); /* Initialize the node to no-match */ pExpr->iTable = -1; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding ** schema. If not found, pSchema will remain NULL and nothing will match ** resulting in an appropriate error message toward the end of this routine */ if( zDb ){ testcase( pNC->ncFlags & NC_PartIdx ); testcase( pNC->ncFlags & NC_IsCheck ); if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ /* Silently ignore database qualifiers inside CHECK constraints and ** partial indices. Do not raise errors because that might break ** legacy and because it does not hurt anything to just ignore the ** database name. */ zDb = 0; }else{ for(i=0; i<db->nDb; i++){ assert( db->aDb[i].zDbSName ); if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } } } } /* Start at the inner-most context and move outward until a match is found */ assert( pNC && cnt==0 ); do{ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; if( pSrcList ){ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; j<pEList->nExpr; j++){ if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; pExpr->iColumn = j; hit = 1; } } if( hit || zTab==0 ) continue; } if( zDb && pTab->pSchema!=pSchema ){ continue; } if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); if( sqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } if( IN_RENAME_OBJECT && pItem->zAlias ){ sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. */ if( cnt==1 ){ if( pItem->fg.jointype & JT_NATURAL ) continue; if( nameInUsingClause(pItem->pUsing, zCol) ) continue; } cnt++; pMatch = pItem; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; break; } } } if( pMatch ){ pExpr->iTable = pMatch->iCursor; pExpr->y.pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } pSchema = pExpr->y.pTab->pSchema; } } /* if( pSrcList ) */ #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference. Or ** maybe it is an excluded.* from an upsert. */ if( zDb==0 && zTab!=0 && cntTab==0 ){ pTab = 0; #ifndef SQLITE_OMIT_TRIGGER if( pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; pTab = pParse->pTriggerTab; }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ pExpr->iTable = 0; pTab = pParse->pTriggerTab; } } #endif /* SQLITE_OMIT_TRIGGER */ #ifndef SQLITE_OMIT_UPSERT if( (pNC->ncFlags & NC_UUpsert)!=0 ){ Upsert *pUpsert = pNC->uNC.pUpsert; if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ pTab = pUpsert->pUpsertSrc->a[0].pTab; pExpr->iTable = 2; } } #endif /* SQLITE_OMIT_UPSERT */ if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iCol<pTab->nCol ){ cnt++; #ifndef SQLITE_OMIT_UPSERT if( pExpr->iTable==2 ){ testcase( iCol==(-1) ); if( IN_RENAME_OBJECT ){ pExpr->iColumn = iCol; pExpr->y.pTab = pTab; eNewExprOp = TK_COLUMN; }else{ pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; eNewExprOp = TK_REGISTER; ExprSetProperty(pExpr, EP_Alias); } }else #endif /* SQLITE_OMIT_UPSERT */ { #ifndef SQLITE_OMIT_TRIGGER if( iCol<0 ){ pExpr->affExpr = SQLITE_AFF_INTEGER; }else if( pExpr->iTable==0 ){ testcase( iCol==31 ); testcase( iCol==32 ); pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); }else{ testcase( iCol==31 ); testcase( iCol==32 ); pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); } pExpr->y.pTab = pTab; pExpr->iColumn = (i16)iCol; eNewExprOp = TK_TRIGGER; #endif /* SQLITE_OMIT_TRIGGER */ } } } } #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ /* ** Perhaps the name is a reference to the ROWID */ if( cnt==0 && cntTab==1 && pMatch && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0 && sqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; pExpr->affExpr = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. ** ** The ability to use an output result-set column in the WHERE, GROUP BY, ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning ** on sqlite3_log() whenever the capability is used. */ if( (pNC->ncFlags & NC_UEList)!=0 && cnt==0 && zTab==0 ){ pEList = pNC->uNC.pEList; assert( pEList!=0 ); for(j=0; j<pEList->nExpr; j++){ char *zAs = pEList->a[j].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); return WRC_Abort; } if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){ sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); return WRC_Abort; } if( sqlite3ExprVectorSize(pOrig)!=1 ){ sqlite3ErrorMsg(pParse, "row value misused"); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); if( IN_RENAME_OBJECT ){ sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); } goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if( cnt ) break; pNC = pNC->pNext; nSubquery++; }while( pNC ); /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ if( cnt==0 && zTab==0 ){ assert( pExpr->op==TK_ID ); if( ExprHasProperty(pExpr,EP_DblQuoted) && areDoubleQuotedStringsEnabled(db, pTopNC) ){ /* If a double-quoted identifier does not match any known column name, ** then treat it as a string. ** ** This hack was added in the early days of SQLite in a misguided attempt ** to be compatible with MySQL 3.x, which used double-quotes for strings. ** I now sorely regret putting in this hack. The effect of this hack is ** that misspelled identifier names are silently converted into strings ** rather than causing an error, to the frustration of countless ** programmers. To all those frustrated programmers, my apologies. ** ** Someday, I hope to get rid of this hack. Unfortunately there is ** a huge amount of legacy SQL that uses it. So for now, we just ** issue a warning. */ sqlite3_log(SQLITE_WARNING, "double-quoted string literal: \"%w\"", zCol); #ifdef SQLITE_ENABLE_NORMALIZE sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); #endif pExpr->op = TK_STRING; pExpr->y.pTab = 0; return WRC_Prune; } if( sqlite3ExprIdToTrueFalse(pExpr) ){ return WRC_Prune; } } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. ** ** The colUsed mask is an optimization used to help determine if an ** index is a covering index. The correct answer is still obtained ** if the mask contains extra bits. But omitting bits from the mask ** might result in an incorrect answer. ** ** The high-order bit of the mask is a "we-use-them-all" bit. ** If the column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. Also set the high-order ** bit if the column is a generated column, as that adds dependencies ** that are difficult to track, so we assume that all columns are used. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; testcase( n==BMS-1 ); if( n>=BMS ){ n = BMS-1; } assert( pExpr->y.pTab!=0 ); assert( pMatch->iCursor==pExpr->iTable ); if( pExpr->y.pTab->tabFlags & TF_HasGenerated ){ Column *pCol = pExpr->y.pTab->aCol + pExpr->iColumn; if( pCol->colFlags & COLFLAG_GENERATED ) n = BMS-1; } pMatch->colUsed |= ((Bitmask)1)<<n; } /* Clean up and return */ sqlite3ExprDelete(db, pExpr->pLeft); pExpr->pLeft = 0; sqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; pExpr->op = eNewExprOp; ExprSetProperty(pExpr, EP_Leaf); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for(;;){ assert( pTopNC!=0 ); pTopNC->nRef++; if( pTopNC==pNC ) break; pTopNC = pTopNC->pNext; } return WRC_Prune; } else { return WRC_Abort; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,771
libvncserver
53073c8d7e232151ea2ecd8a1243124121e10e2d
rfbSetClientColourMap(rfbClientPtr cl, int firstColour, int nColours) { if (cl->screen->serverFormat.trueColour || !cl->readyForSetColourMapEntries) { return TRUE; } if (nColours == 0) { nColours = cl->screen->colourMap.count; } if (cl->format.trueColour) { LOCK(cl->updateMutex); (*rfbInitColourMapSingleTableFns [BPP2OFFSET(cl->format.bitsPerPixel)]) (&cl->translateLookupTable, &cl->screen->serverFormat, &cl->format,&cl->screen->colourMap); sraRgnDestroy(cl->modifiedRegion); cl->modifiedRegion = sraRgnCreateRect(0,0,cl->screen->width,cl->screen->height); UNLOCK(cl->updateMutex); return TRUE; } return rfbSendSetColourMapEntries(cl, firstColour, nColours); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,385
Chrome
a261ea1c56ef16fc0fc4af1e440feb302d577716
void FileReaderLoader::OnDataPipeReadable(MojoResult result) { if (result != MOJO_RESULT_OK) { if (!received_all_data_) Failed(FileError::kNotReadableErr); return; } while (true) { uint32_t num_bytes; const void* buffer; MojoResult result = consumer_handle_->BeginReadData( &buffer, &num_bytes, MOJO_READ_DATA_FLAG_NONE); if (result == MOJO_RESULT_SHOULD_WAIT) { if (!IsSyncLoad()) return; result = mojo::Wait(consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE); if (result == MOJO_RESULT_OK) continue; } if (result == MOJO_RESULT_FAILED_PRECONDITION) { if (!received_all_data_) Failed(FileError::kNotReadableErr); return; } if (result != MOJO_RESULT_OK) { Failed(FileError::kNotReadableErr); return; } OnReceivedData(static_cast<const char*>(buffer), num_bytes); consumer_handle_->EndReadData(num_bytes); if (BytesLoaded() >= total_bytes_) { received_all_data_ = true; if (received_on_complete_) OnFinishLoading(); return; } } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,800
qpdf
8249a26d69f72b9cda584c14cc3f12769985e481
QPDFWriter::enqueueObject(QPDFObjectHandle object) { if (object.isIndirect()) { if (object.getOwningQPDF() != &(this->pdf)) { QTC::TC("qpdf", "QPDFWriter foreign object"); throw std::logic_error( "QPDFObjectHandle from different QPDF found while writing." " Use QPDF::copyForeignObject to add objects from" " another file."); } QPDFObjGen og = object.getObjGen(); if (obj_renumber.count(og) == 0) { if (this->object_to_object_stream.count(og)) { // This is in an object stream. Don't process it // here. Instead, enqueue the object stream. Object // streams always have generation 0. int stream_id = this->object_to_object_stream[og]; enqueueObject(this->pdf.getObjectByID(stream_id, 0)); } else { object_queue.push_back(object); obj_renumber[og] = next_objid++; if ((og.getGen() == 0) && this->object_stream_to_objects.count(og.getObj())) { // For linearized files, uncompressed objects go // at end, and we take care of assigning numbers // to them elsewhere. if (! this->linearized) { assignCompressedObjectNumbers(og); } } else if ((! this->direct_stream_lengths) && object.isStream()) { // reserve next object ID for length ++next_objid; } } } } else if (object.isArray()) { int n = object.getArrayNItems(); for (int i = 0; i < n; ++i) { if (! this->linearized) { enqueueObject(object.getArrayItem(i)); } } } else if (object.isDictionary()) { std::set<std::string> keys = object.getKeys(); for (std::set<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { if (! this->linearized) { enqueueObject(object.getKey(*iter)); } } } else { // ignore } }
1
CVE-2017-18183
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
8,435
linux
0b79459b482e85cb7426aa7da683a9f2c97aeae1
static void update_eoi_exitmap(struct kvm_vcpu *vcpu) { u64 eoi_exit_bitmap[4]; memset(eoi_exit_bitmap, 0, 32); kvm_ioapic_calculate_eoi_exitmap(vcpu, eoi_exit_bitmap); kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,872
tensorflow
e6cf28c72ba2eb949ca950d834dd6d66bb01cfae
ALWAYS_INLINE void ScalarMulAdd3Way(const float a1, const float a2, const float a3, const float** inp1, const float** inp2, const float** inp3, float** out) { **out += a1 * **inp1 + a2 * **inp2 + a3 * **inp3; ++*out; ++*inp1; ++*inp2; ++*inp3; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,070
bsdiff4
49a4cee2feef7deaf9d89e5e793a8824930284d7
static void qsufsort(off_t *I, off_t *V, unsigned char *old, off_t oldsize) { off_t buckets[256], i, h, len; for (i = 0; i < 256; i++) buckets[i] = 0; for (i = 0; i < oldsize; i++) buckets[old[i]]++; for (i = 1; i < 256; i++) buckets[i] += buckets[i - 1]; for (i = 255; i > 0; i--) buckets[i] = buckets[i - 1]; buckets[0] = 0; for (i = 0; i < oldsize; i++) I[++buckets[old[i]]] = i; I[0] = oldsize; for (i = 0; i < oldsize; i++) V[i] = buckets[old[i]]; V[oldsize] = 0; for (i = 1; i < 256; i++) if (buckets[i] == buckets[i - 1] + 1) I[buckets[i]] = -1; I[0] = -1; for (h = 1; I[0] != -(oldsize + 1); h += h) { len = 0; for (i = 0; i < oldsize + 1;) { if (I[i] < 0) { len -= I[i]; i -= I[i]; } else { if (len) I[i - len] = -len; len = V[I[i]] + 1 - i; split(I, V, i, len, h); i += len; len=0; } } if (len) I[i - len] = -len; } for (i = 0; i < oldsize + 1; i++) I[V[i]] = i; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,887
claws
d390fa07f5548f3173dd9cc13b233db5ce934c82
static gint conv_euctojis(gchar *outbuf, gint outlen, const gchar *inbuf) { const guchar *in = inbuf; guchar *out = outbuf; JISState state = JIS_ASCII; while (*in != '\0') { if (IS_ASCII(*in)) { K_OUT(); *out++ = *in++; } else if (iseuckanji(*in)) { if (iseuckanji(*(in + 1))) { K_IN(); *out++ = *in++ & 0x7f; *out++ = *in++ & 0x7f; } else { K_OUT(); *out++ = SUBST_CHAR; in++; if (*in != '\0' && !IS_ASCII(*in)) { *out++ = SUBST_CHAR; in++; } } } else if (iseuchwkana1(*in)) { if (iseuchwkana2(*(in + 1))) { if (prefs_common.allow_jisx0201_kana) { HW_IN(); in++; *out++ = *in++ & 0x7f; } else { guchar jis_ch[2]; gint len; if (iseuchwkana1(*(in + 2)) && iseuchwkana2(*(in + 3))) len = conv_jis_hantozen (jis_ch, *(in + 1), *(in + 3)); else len = conv_jis_hantozen (jis_ch, *(in + 1), '\0'); if (len == 0) in += 2; else { K_IN(); in += len * 2; *out++ = jis_ch[0]; *out++ = jis_ch[1]; } } } else { K_OUT(); in++; if (*in != '\0' && !IS_ASCII(*in)) { *out++ = SUBST_CHAR; in++; } } } else if (iseucaux(*in)) { in++; if (iseuckanji(*in) && iseuckanji(*(in + 1))) { AUX_IN(); *out++ = *in++ & 0x7f; *out++ = *in++ & 0x7f; } else { K_OUT(); if (*in != '\0' && !IS_ASCII(*in)) { *out++ = SUBST_CHAR; in++; if (*in != '\0' && !IS_ASCII(*in)) { *out++ = SUBST_CHAR; in++; } } } } else { K_OUT(); *out++ = SUBST_CHAR; in++; } } K_OUT(); *out = '\0'; return 0; }
1
CVE-2015-8614
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).
3,579
openjpeg
8ee335227bbcaf1614124046aa25e53d67b11ec3
opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) { opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256]; OPJ_UINT8 const* pLUT[3]; opj_image_t * image = NULL; FILE *IN; OPJ_BITMAPFILEHEADER File_h; OPJ_BITMAPINFOHEADER Info_h; OPJ_UINT32 i, palette_len, numcmpts = 1U; OPJ_BOOL l_result = OPJ_FALSE; OPJ_UINT8* pData = NULL; OPJ_UINT32 stride; pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B; IN = fopen(filename, "rb"); if (!IN) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return NULL; } if (!bmp_read_file_header(IN, &File_h)) { fclose(IN); return NULL; } if (!bmp_read_info_header(IN, &Info_h)) { fclose(IN); return NULL; } /* Load palette */ if (Info_h.biBitCount <= 8U) { memset(&lut_R[0], 0, sizeof(lut_R)); memset(&lut_G[0], 0, sizeof(lut_G)); memset(&lut_B[0], 0, sizeof(lut_B)); palette_len = Info_h.biClrUsed; if ((palette_len == 0U) && (Info_h.biBitCount <= 8U)) { palette_len = (1U << Info_h.biBitCount); } if (palette_len > 256U) { palette_len = 256U; } if (palette_len > 0U) { OPJ_UINT8 has_color = 0U; for (i = 0U; i < palette_len; i++) { lut_B[i] = (OPJ_UINT8)getc(IN); lut_G[i] = (OPJ_UINT8)getc(IN); lut_R[i] = (OPJ_UINT8)getc(IN); (void)getc(IN); /* padding */ has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]); } if (has_color) { numcmpts = 3U; } } } else { numcmpts = 3U; if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) { numcmpts++; } } if (Info_h.biWidth == 0 || Info_h.biHeight == 0) { fclose(IN); return NULL; } if (Info_h.biBitCount > (((OPJ_UINT32) - 1) - 31) / Info_h.biWidth) { fclose(IN); return NULL; } stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */ if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */ if (8 > (((OPJ_UINT32) - 1) - 31) / Info_h.biWidth) { fclose(IN); return NULL; } stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U; } if (stride > ((OPJ_UINT32) - 1) / sizeof(OPJ_UINT8) / Info_h.biHeight) { fclose(IN); return NULL; } pData = (OPJ_UINT8 *) calloc(1, sizeof(OPJ_UINT8) * stride * Info_h.biHeight); if (pData == NULL) { fclose(IN); return NULL; } /* Place the cursor at the beginning of the image information */ fseek(IN, 0, SEEK_SET); fseek(IN, (long)File_h.bfOffBits, SEEK_SET); switch (Info_h.biCompression) { case 0: case 3: /* read raw data */ l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 1: /* read rle8 data */ l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 2: /* read rle4 data */ l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; default: fprintf(stderr, "Unsupported BMP compression\n"); l_result = OPJ_FALSE; break; } if (!l_result) { free(pData); fclose(IN); return NULL; } /* create the image */ memset(&cmptparm[0], 0, sizeof(cmptparm)); for (i = 0; i < 4U; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy; cmptparm[i].w = Info_h.biWidth; cmptparm[i].h = Info_h.biHeight; } image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB); if (!image) { fclose(IN); free(pData); return NULL; } if (numcmpts == 4U) { image->comps[3].alpha = 1; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32) parameters->subsampling_dx + 1U; image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32) parameters->subsampling_dy + 1U; /* Read the data */ if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */ bmp24toimage(pData, stride, image); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/ bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */ } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */ bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U); } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0x00FF0000U; Info_h.biGreenMask = 0x0000FF00U; Info_h.biBlueMask = 0x000000FFU; } bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */ bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0xF800U; Info_h.biGreenMask = 0x07E0U; Info_h.biBlueMask = 0x001FU; } bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else { opj_image_destroy(image); image = NULL; fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount); } free(pData); fclose(IN); return image; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,713
openjpeg
2cd30c2b06ce332dede81cccad8b334cde997281
static unsigned short get_ushort(const unsigned char *data) { unsigned short val = *(const unsigned short *)data; #ifdef OPJ_BIG_ENDIAN val = ((val & 0xffU) << 8) | (val >> 8); #endif return val; }
1
CVE-2017-14040
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).
8,849
FreeRDP
17c363a5162fd4dc77b1df54e48d7bd9bf6b3be7
static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) { UINT32 front; if (count <= 0) return; if (count > zgfx->HistoryBufferSize) { const size_t residue = count - zgfx->HistoryBufferSize; count = zgfx->HistoryBufferSize; src += residue; zgfx->HistoryIndex = (zgfx->HistoryIndex + residue) % zgfx->HistoryBufferSize; } if (zgfx->HistoryIndex + count <= zgfx->HistoryBufferSize) { CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, count); if ((zgfx->HistoryIndex += count) == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; } else { front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); zgfx->HistoryIndex = count - front; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,353
libming
da9d86eab55cbf608d5c916b8b690f5b76bca462
getString(struct SWF_ACTIONPUSHPARAM *act) { char *t; #ifdef DEBUG printf("*getString* type=%d\n",act->Type); #endif switch( act->Type ) { case PUSH_STRING: if (!act->p.String) /* Not a NULL string */ { SWF_warn("WARNING: Call to getString with NULL string.\n"); break; } t=malloc(strlen(act->p.String)+3); /* 2 "'"s and a NULL */ strcpy(t,"'"); strcat(t,act->p.String); strcat(t,"'"); return t; case PUSH_NULL: /* NULL */ return "null"; case PUSH_UNDEF: /* Undefined */ return "undefined"; case PUSH_REGISTER: /* REGISTER */ if( regs[act->p.RegisterNumber] && regs[act->p.RegisterNumber]->Type != 4 && regs[act->p.RegisterNumber]->Type != 7 ) { return getName(regs[act->p.RegisterNumber]); } else { t=malloc(5); /* Rddd */ sprintf(t,"R%d", act->p.RegisterNumber ); return t; } case PUSH_BOOLEAN: /* BOOLEAN */ if( act->p.Boolean ) return "true"; else return "false"; case PUSH_DOUBLE: /* DOUBLE */ { char length_finder[1]; int needed_length = snprintf(length_finder, 1, "%g", act->p.Double) + 1; if (needed_length <= 0) { SWF_warn("WARNING: could not evaluate size of buffer (memory issue ?).\n"); break; } t = malloc(needed_length); sprintf(t, "%g", act->p.Double ); return t; } case PUSH_INT: /* INTEGER */ t=malloc(10); /* 32-bit decimal */ sprintf(t,"%ld", act->p.Integer ); return t; case PUSH_CONSTANT: /* CONSTANT8 */ if (act->p.Constant8 > poolcounter) { SWF_warn("WARNING: retrieving constants not present in the pool.\n"); break; } t=malloc(strlenext(pool[act->p.Constant8])+3); /* 2 "'"s and a NULL */ strcpy(t,"'"); strcatext(t,pool[act->p.Constant8]); strcat(t,"'"); return t; case PUSH_CONSTANT16: /* CONSTANT16 */ if (act->p.Constant16 > poolcounter) { SWF_warn("WARNING: retrieving constants not present in the pool.\n"); break; } t=malloc(strlenext(pool[act->p.Constant16])+3); /* 2 '\"'s and a NULL */ strcpy(t,"'"); strcatext(t,pool[act->p.Constant16]); strcat(t,"'"); return t; case 12: case 11: /* INCREMENTED or DECREMENTED VARIABLE */ case PUSH_VARIABLE: /* VARIABLE */ return act->p.String; default: fprintf (stderr," Can't get string for type: %d\n", act->Type); break; } t = malloc(sizeof(char)); strcpyext(t,""); return t; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,074
Chrome
3bbc818ed1a7b63b8290bbde9ae975956748cb8a
void webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase* webkitWebViewBase, unsigned height) { if (!webkitWebViewBase->priv->inspectorView) return; if (webkitWebViewBase->priv->inspectorViewHeight == height) return; webkitWebViewBase->priv->inspectorViewHeight = height; gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase)); }
1
CVE-2011-3099
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
967
sound
19bce474c45be69a284ecee660aa12d8f1e88f18
static int __check_input_term(struct mixer_build *state, int id, struct usb_audio_term *term) { int protocol = state->mixer->protocol; int err; void *p1; unsigned char *hdr; memset(term, 0, sizeof(*term)); for (;;) { /* a loop in the terminal chain? */ if (test_and_set_bit(id, state->termbitmap)) return -EINVAL; p1 = find_audio_control_unit(state, id); if (!p1) break; hdr = p1; term->id = id; if (protocol == UAC_VERSION_1 || protocol == UAC_VERSION_2) { switch (hdr[2]) { case UAC_INPUT_TERMINAL: if (protocol == UAC_VERSION_1) { struct uac_input_terminal_descriptor *d = p1; term->type = le16_to_cpu(d->wTerminalType); term->channels = d->bNrChannels; term->chconfig = le16_to_cpu(d->wChannelConfig); term->name = d->iTerminal; } else { /* UAC_VERSION_2 */ struct uac2_input_terminal_descriptor *d = p1; /* call recursively to verify that the * referenced clock entity is valid */ err = __check_input_term(state, d->bCSourceID, term); if (err < 0) return err; /* save input term properties after recursion, * to ensure they are not overriden by the * recursion calls */ term->id = id; term->type = le16_to_cpu(d->wTerminalType); term->channels = d->bNrChannels; term->chconfig = le32_to_cpu(d->bmChannelConfig); term->name = d->iTerminal; } return 0; case UAC_FEATURE_UNIT: { /* the header is the same for v1 and v2 */ struct uac_feature_unit_descriptor *d = p1; id = d->bSourceID; break; /* continue to parse */ } case UAC_MIXER_UNIT: { struct uac_mixer_unit_descriptor *d = p1; term->type = UAC3_MIXER_UNIT << 16; /* virtual type */ term->channels = uac_mixer_unit_bNrChannels(d); term->chconfig = uac_mixer_unit_wChannelConfig(d, protocol); term->name = uac_mixer_unit_iMixer(d); return 0; } case UAC_SELECTOR_UNIT: case UAC2_CLOCK_SELECTOR: { struct uac_selector_unit_descriptor *d = p1; /* call recursively to retrieve the channel info */ err = __check_input_term(state, d->baSourceID[0], term); if (err < 0) return err; term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */ term->id = id; term->name = uac_selector_unit_iSelector(d); return 0; } case UAC1_PROCESSING_UNIT: /* UAC2_EFFECT_UNIT */ if (protocol == UAC_VERSION_1) term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */ else /* UAC_VERSION_2 */ term->type = UAC3_EFFECT_UNIT << 16; /* virtual type */ /* fall through */ case UAC1_EXTENSION_UNIT: /* UAC2_PROCESSING_UNIT_V2 */ if (protocol == UAC_VERSION_1 && !term->type) term->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */ else if (protocol == UAC_VERSION_2 && !term->type) term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */ /* fall through */ case UAC2_EXTENSION_UNIT_V2: { struct uac_processing_unit_descriptor *d = p1; if (protocol == UAC_VERSION_2 && hdr[2] == UAC2_EFFECT_UNIT) { /* UAC2/UAC1 unit IDs overlap here in an * uncompatible way. Ignore this unit for now. */ return 0; } if (d->bNrInPins) { id = d->baSourceID[0]; break; /* continue to parse */ } if (!term->type) term->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */ term->channels = uac_processing_unit_bNrChannels(d); term->chconfig = uac_processing_unit_wChannelConfig(d, protocol); term->name = uac_processing_unit_iProcessing(d, protocol); return 0; } case UAC2_CLOCK_SOURCE: { struct uac_clock_source_descriptor *d = p1; term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */ term->id = id; term->name = d->iClockSource; return 0; } default: return -ENODEV; } } else { /* UAC_VERSION_3 */ switch (hdr[2]) { case UAC_INPUT_TERMINAL: { struct uac3_input_terminal_descriptor *d = p1; /* call recursively to verify that the * referenced clock entity is valid */ err = __check_input_term(state, d->bCSourceID, term); if (err < 0) return err; /* save input term properties after recursion, * to ensure they are not overriden by the * recursion calls */ term->id = id; term->type = le16_to_cpu(d->wTerminalType); err = get_cluster_channels_v3(state, le16_to_cpu(d->wClusterDescrID)); if (err < 0) return err; term->channels = err; /* REVISIT: UAC3 IT doesn't have channels cfg */ term->chconfig = 0; term->name = le16_to_cpu(d->wTerminalDescrStr); return 0; } case UAC3_FEATURE_UNIT: { struct uac3_feature_unit_descriptor *d = p1; id = d->bSourceID; break; /* continue to parse */ } case UAC3_CLOCK_SOURCE: { struct uac3_clock_source_descriptor *d = p1; term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */ term->id = id; term->name = le16_to_cpu(d->wClockSourceStr); return 0; } case UAC3_MIXER_UNIT: { struct uac_mixer_unit_descriptor *d = p1; err = uac_mixer_unit_get_channels(state, d); if (err <= 0) return err; term->channels = err; term->type = UAC3_MIXER_UNIT << 16; /* virtual type */ return 0; } case UAC3_SELECTOR_UNIT: case UAC3_CLOCK_SELECTOR: { struct uac_selector_unit_descriptor *d = p1; /* call recursively to retrieve the channel info */ err = __check_input_term(state, d->baSourceID[0], term); if (err < 0) return err; term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */ term->id = id; term->name = 0; /* TODO: UAC3 Class-specific strings */ return 0; } case UAC3_PROCESSING_UNIT: { struct uac_processing_unit_descriptor *d = p1; if (!d->bNrInPins) return -EINVAL; /* call recursively to retrieve the channel info */ err = __check_input_term(state, d->baSourceID[0], term); if (err < 0) return err; term->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */ term->id = id; term->name = 0; /* TODO: UAC3 Class-specific strings */ return 0; } default: return -ENODEV; } } } return -ENODEV; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,912
ImageMagick
d5559407ce29f4371e5df9c1cbde65455fe5854c
static Image *ReadINLINEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register size_t i; size_t quantum; ssize_t count; unsigned char *inline_image; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (LocaleNCompare(image_info->filename,"data:",5) == 0) { char *filename; Image *data_image; filename=AcquireString("data:"); (void) ConcatenateMagickString(filename,image_info->filename, MagickPathExtent); data_image=ReadInlineImage(image_info,filename,exception); filename=DestroyString(filename); return(data_image); } image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } quantum=MagickMin((size_t) GetBlobSize(image),MagickMaxBufferExtent); if (quantum == 0) quantum=MagickMaxBufferExtent; inline_image=(unsigned char *) AcquireQuantumMemory(quantum, sizeof(*inline_image)); count=0; for (i=0; inline_image != (unsigned char *) NULL; i+=count) { count=(ssize_t) ReadBlob(image,quantum,inline_image+i); if (count <= 0) { count=0; if (errno != EINTR) break; } if (~((size_t) i) < (quantum+1)) { inline_image=(unsigned char *) RelinquishMagickMemory(inline_image); break; } inline_image=(unsigned char *) ResizeQuantumMemory(inline_image,i+count+ quantum+1,sizeof(*inline_image)); } if (inline_image == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return((Image *) NULL); } inline_image[i+count]='\0'; image=DestroyImageList(image); image=ReadInlineImage(image_info,(char *) inline_image,exception); inline_image=(unsigned char *) RelinquishMagickMemory(inline_image); return(image); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,929
Chrome
b944f670bb7a8a919daac497a4ea0536c954c201
static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->overloadedMethod(objArg); return JSValue::encode(jsUndefined()); } int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(objArg, intArg); return JSValue::encode(jsUndefined()); }
1
CVE-2011-2350
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,583
Chrome
94fef6e2a56ef5b3ed0dc0fd94e6ad52267067fb
void TaskService::PostBoundDelayedTask(RunnerId runner_id, base::OnceClosure task, base::TimeDelta delay) { InstanceId instance_id; { base::AutoLock lock(lock_); if (bound_instance_id_ == kInvalidInstanceId) return; instance_id = bound_instance_id_; } GetTaskRunner(runner_id)->PostDelayedTask( FROM_HERE, base::BindOnce(&TaskService::RunTask, base::Unretained(this), instance_id, runner_id, std::move(task)), delay); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,456
gnupg
07116a314f4dcd4d96990bbd74db95a03a9f650a
dump_decoder_state (DECODER_STATE ds) { int i; for (i=0; i < ds->idx; i++) { fprintf (stderr," ds stack[%d] (", i); if (ds->stack[i].node) _ksba_asn_node_dump (ds->stack[i].node, stderr); else fprintf (stderr, "Null"); fprintf (stderr,") %s%d (%d)%s\n", ds->stack[i].ndef_length? "ndef ":"", ds->stack[i].length, ds->stack[i].nread, ds->stack[i].in_seq_of? " in_seq_of":""); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,032
linux
363b02dab09b3226f3bd1420dad9c72b79a42a76
int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { smp_rmb(); return key->reject_error; } return key_validate(key); }
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.
8,199
gnutls
5140422e0d7319a8e2fe07f02cbcafc4d6538732
int cdk_pk_get_nbits(cdk_pubkey_t pk) { if (!pk || !pk->mpi[0]) return 0; return _gnutls_mpi_get_nbits(pk->mpi[0]); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,744
linux
f0ec1aaf54caddd21c259aea8b2ecfbde4ee4fb9
void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; if (p->mm) { /* adjust to KB unit */ stats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB; } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; }
1
CVE-2012-3510
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
7,067
libsndfile
708e996c87c5fae77b104ccfeb8f6db784c32074
header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; } ; } /* header_put_le_8byte */
1
CVE-2017-7586
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,031
linux
e7af6307a8a54f0b873960b32b6a644f2d0fbd97
void snd_timer_notify(struct snd_timer *timer, int event, struct timespec *tstamp) { unsigned long flags; unsigned long resolution = 0; struct snd_timer_instance *ti, *ts; if (timer->card && timer->card->shutdown) return; if (! (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)) return; if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_MSTART || event > SNDRV_TIMER_EVENT_MRESUME)) return; spin_lock_irqsave(&timer->lock, flags); if (event == SNDRV_TIMER_EVENT_MSTART || event == SNDRV_TIMER_EVENT_MCONTINUE || event == SNDRV_TIMER_EVENT_MRESUME) resolution = snd_timer_hw_resolution(timer); list_for_each_entry(ti, &timer->active_list_head, active_list) { if (ti->ccallback) ti->ccallback(ti, event, tstamp, resolution); list_for_each_entry(ts, &ti->slave_active_head, active_list) if (ts->ccallback) ts->ccallback(ts, event, tstamp, resolution); } spin_unlock_irqrestore(&timer->lock, flags); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,679
FFmpeg
2b46ebdbff1d8dec7a3d8ea280a612b91a582869
static int parse_video_info(AVIOContext *pb, AVStream *st) { uint16_t size_asf; // ASF-specific Format Data size uint32_t size_bmp; // BMP_HEADER-specific Format Data size unsigned int tag; st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); avio_skip(pb, 1); // skip reserved flags size_asf = avio_rl16(pb); tag = ff_get_bmp_header(pb, st, &size_bmp); st->codecpar->codec_tag = tag; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); size_bmp = FFMAX(size_asf, size_bmp); if (size_bmp > BMP_HEADER_SIZE) { int ret; st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE; if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE))) { st->codecpar->extradata_size = 0; return AVERROR(ENOMEM); } memset(st->codecpar->extradata + st->codecpar->extradata_size , 0, AV_INPUT_BUFFER_PADDING_SIZE); if ((ret = avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size)) < 0) return ret; } return 0; }
1
CVE-2018-1999011
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,632
openssh-portable
ec165c392ca54317dbe3064a8c200de6531e89ad
kex_input_kexinit(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; const u_char *ptr; u_int i; size_t dlen; int r; debug("SSH2_MSG_KEXINIT received"); if (kex == NULL) return SSH_ERR_INVALID_ARGUMENT; ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL); ptr = sshpkt_ptr(ssh, &dlen); if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0) return r; /* discard packet */ for (i = 0; i < KEX_COOKIE_LEN; i++) if ((r = sshpkt_get_u8(ssh, NULL)) != 0) return r; for (i = 0; i < PROPOSAL_MAX; i++) if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) return r; /* * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported * KEX method has the server move first, but a server might be using * a custom method or one that we otherwise don't support. We should * be prepared to remember first_kex_follows here so we can eat a * packet later. * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means * for cases where the server *doesn't* go first. I guess we should * ignore it when it is set for these cases, which is what we do now. */ if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */ (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */ (r = sshpkt_get_end(ssh)) != 0) return r; if (!(kex->flags & KEX_INIT_SENT)) if ((r = kex_send_kexinit(ssh)) != 0) return r; if ((r = kex_choose_conf(ssh)) != 0) return r; if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL) return (kex->kex[kex->kex_type])(ssh); return SSH_ERR_INTERNAL_ERROR; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,648
Chrome
2511466dd15750f2ab0e5cecc30010f0a3f7949c
void FocusFirstNameField() { LOG(WARNING) << "Clicking on the tab."; ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER)); ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER)); LOG(WARNING) << "Focusing the first name field."; bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( render_view_host(), L"", L"if (document.readyState === 'complete')" L" document.getElementById('firstname').focus();" L"else" L" domAutomationController.send(false);", &result)); ASSERT_TRUE(result); }
1
CVE-2012-2876
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,751
w3m
e2c7ecec6f9b730ad3c9bf8c8df9212970f183d7
formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (buf->currentLine == NULL || spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ { if (!form->value) break; p = form->value->ptr; } l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,105
linux
1957a85b0032a81e6482ca4aab883643b8dae06e
u64 __init efi_mem_desc_end(efi_memory_desc_t *md) { u64 size = md->num_pages << EFI_PAGE_SHIFT; u64 end = md->phys_addr + size; return end; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,309
tcpdump
211124b972e74f0da66bc8b16f181f78793e2f66
static int dccp_cksum(netdissect_options *ndo, const struct ip *ip, const struct dccp_hdr *dh, u_int len) { return nextproto4_cksum(ndo, ip, (const uint8_t *)(const void *)dh, len, dccp_csum_coverage(dh, len), IPPROTO_DCCP); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,800
linux
c903f0456bc69176912dee6dd25c6a66ee1aed00
static ssize_t msr_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { const u32 __user *tmp = (const u32 __user *)buf; u32 data[2]; u32 reg = *ppos; int cpu = iminor(file->f_path.dentry->d_inode); int err = 0; ssize_t bytes = 0; if (count % 8) return -EINVAL; /* Invalid chunk size */ for (; count; count -= 8) { if (copy_from_user(&data, tmp, 8)) { err = -EFAULT; break; } err = wrmsr_safe_on_cpu(cpu, reg, data[0], data[1]); if (err) break; tmp += 2; bytes += 8; } return bytes ? bytes : err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,104
DBD-mysql
7c164a0c86cec6ee95df1d141e67b0e85dfdefd2
MYSQL *mysql_dr_connect( SV* dbh, MYSQL* sock, char* mysql_socket, char* host, char* port, char* user, char* password, char* dbname, imp_dbh_t *imp_dbh) { int portNr; unsigned int client_flag; MYSQL* result; dTHX; D_imp_xxh(dbh); /* per Monty, already in client.c in API */ /* but still not exist in libmysqld.c */ #if defined(DBD_MYSQL_EMBEDDED) if (host && !*host) host = NULL; #endif portNr= (port && *port) ? atoi(port) : 0; /* already in client.c in API */ /* if (user && !*user) user = NULL; */ /* if (password && !*password) password = NULL; */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: host = |%s|, port = %d," \ " uid = %s, pwd = %s\n", host ? host : "NULL", portNr, user ? user : "NULL", password ? password : "NULL"); { #if defined(DBD_MYSQL_EMBEDDED) if (imp_dbh) { D_imp_drh_from_dbh; SV* sv = DBIc_IMP_DATA(imp_dbh); if (sv && SvROK(sv)) { SV** svp; STRLEN lna; char * options; int server_args_cnt= 0; int server_groups_cnt= 0; int rc= 0; char ** server_args = NULL; char ** server_groups = NULL; HV* hv = (HV*) SvRV(sv); if (SvTYPE(hv) != SVt_PVHV) return NULL; if (!imp_drh->embedded.state) { /* Init embedded server */ if ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) && *svp && SvTRUE(*svp)) { options = SvPV(*svp, lna); imp_drh->embedded.groups=newSVsv(*svp); if ((server_groups_cnt=count_embedded_options(options))) { /* number of server_groups always server_groups+1 */ server_groups=fill_out_embedded_options(options, 0, (int)lna, ++server_groups_cnt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Groups names passed to embedded server:\n"); print_embedded_options(DBIc_LOGPIO(imp_xxh), server_groups, server_groups_cnt); } } } if ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) && *svp && SvTRUE(*svp)) { options = SvPV(*svp, lna); imp_drh->embedded.args=newSVsv(*svp); if ((server_args_cnt=count_embedded_options(options))) { /* number of server_options always server_options+1 */ server_args=fill_out_embedded_options(options, 1, (int)lna, ++server_args_cnt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Server options passed to embedded server:\n"); print_embedded_options(DBIc_LOGPIO(imp_xxh), server_args, server_args_cnt); } } } if (mysql_server_init(server_args_cnt, server_args, server_groups)) { do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was not started. \ Could not initialize environment."); return NULL; } imp_drh->embedded.state=1; if (server_args_cnt) free_embedded_options(server_args, server_args_cnt); if (server_groups_cnt) free_embedded_options(server_groups, server_groups_cnt); } else { /* * Check if embedded parameters passed to connect() differ from * first ones */ if ( ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) && *svp && SvTRUE(*svp))) rc =+ abs(sv_cmp(*svp, imp_drh->embedded.groups)); if ( ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) && *svp && SvTRUE(*svp)) ) rc =+ abs(sv_cmp(*svp, imp_drh->embedded.args)); if (rc) { do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was already started. You cannot pass init\ parameters to embedded server once"); return NULL; } } } } #endif #ifdef MYSQL_NO_CLIENT_FOUND_ROWS client_flag = 0; #else client_flag = CLIENT_FOUND_ROWS; #endif mysql_init(sock); if (imp_dbh) { SV* sv = DBIc_IMP_DATA(imp_dbh); DBIc_set(imp_dbh, DBIcf_AutoCommit, TRUE); if (sv && SvROK(sv)) { HV* hv = (HV*) SvRV(sv); SV** svp; STRLEN lna; /* thanks to Peter John Edwards for mysql_init_command */ if ((svp = hv_fetch(hv, "mysql_init_command", 18, FALSE)) && *svp && SvTRUE(*svp)) { char* df = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " init command (%s).\n", df); mysql_options(sock, MYSQL_INIT_COMMAND, df); } if ((svp = hv_fetch(hv, "mysql_compression", 17, FALSE)) && *svp && SvTRUE(*svp)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Enabling" \ " compression.\n"); mysql_options(sock, MYSQL_OPT_COMPRESS, NULL); } if ((svp = hv_fetch(hv, "mysql_connect_timeout", 21, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " connect timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_write_timeout", 19, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " write timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_WRITE_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_read_timeout", 18, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " read timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_READ_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_skip_secure_auth", 22, FALSE)) && *svp && SvTRUE(*svp)) { my_bool secauth = 0; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Skipping" \ " secure auth\n"); mysql_options(sock, MYSQL_SECURE_AUTH, &secauth); } if ((svp = hv_fetch(hv, "mysql_read_default_file", 23, FALSE)) && *svp && SvTRUE(*svp)) { char* df = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Reading" \ " default file %s.\n", df); mysql_options(sock, MYSQL_READ_DEFAULT_FILE, df); } if ((svp = hv_fetch(hv, "mysql_read_default_group", 24, FALSE)) && *svp && SvTRUE(*svp)) { char* gr = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Using" \ " default group %s.\n", gr); mysql_options(sock, MYSQL_READ_DEFAULT_GROUP, gr); } #if (MYSQL_VERSION_ID >= 50606) if ((svp = hv_fetch(hv, "mysql_conn_attrs", 16, FALSE)) && *svp) { HV* attrs = (HV*) SvRV(*svp); HE* entry = NULL; I32 num_entries = hv_iterinit(attrs); while (num_entries && (entry = hv_iternext(attrs))) { I32 retlen = 0; char *attr_name = hv_iterkey(entry, &retlen); SV *sv_attr_val = hv_iterval(attrs, entry); char *attr_val = SvPV(sv_attr_val, lna); mysql_options4(sock, MYSQL_OPT_CONNECT_ATTR_ADD, attr_name, attr_val); } } #endif if ((svp = hv_fetch(hv, "mysql_client_found_rows", 23, FALSE)) && *svp) { if (SvTRUE(*svp)) client_flag |= CLIENT_FOUND_ROWS; else client_flag &= ~CLIENT_FOUND_ROWS; } if ((svp = hv_fetch(hv, "mysql_use_result", 16, FALSE)) && *svp) { imp_dbh->use_mysql_use_result = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_mysql_use_result: %d\n", imp_dbh->use_mysql_use_result); } if ((svp = hv_fetch(hv, "mysql_bind_type_guessing", 24, TRUE)) && *svp) { imp_dbh->bind_type_guessing= SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->bind_type_guessing: %d\n", imp_dbh->bind_type_guessing); } if ((svp = hv_fetch(hv, "mysql_bind_comment_placeholders", 31, FALSE)) && *svp) { imp_dbh->bind_comment_placeholders = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->bind_comment_placeholders: %d\n", imp_dbh->bind_comment_placeholders); } if ((svp = hv_fetch(hv, "mysql_no_autocommit_cmd", 23, FALSE)) && *svp) { imp_dbh->no_autocommit_cmd= SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->no_autocommit_cmd: %d\n", imp_dbh->no_autocommit_cmd); } #if FABRIC_SUPPORT if ((svp = hv_fetch(hv, "mysql_use_fabric", 16, FALSE)) && *svp && SvTRUE(*svp)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_fabric: Enabling use of" \ " MySQL Fabric.\n"); mysql_options(sock, MYSQL_OPT_USE_FABRIC, NULL); } #endif #if defined(CLIENT_MULTI_STATEMENTS) if ((svp = hv_fetch(hv, "mysql_multi_statements", 22, FALSE)) && *svp) { if (SvTRUE(*svp)) client_flag |= CLIENT_MULTI_STATEMENTS; else client_flag &= ~CLIENT_MULTI_STATEMENTS; } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* took out client_flag |= CLIENT_PROTOCOL_41; */ /* because libmysql.c already sets this no matter what */ if ((svp = hv_fetch(hv, "mysql_server_prepare", 20, FALSE)) && *svp) { if (SvTRUE(*svp)) { client_flag |= CLIENT_PROTOCOL_41; imp_dbh->use_server_side_prepare = TRUE; } else { client_flag &= ~CLIENT_PROTOCOL_41; imp_dbh->use_server_side_prepare = FALSE; } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_server_side_prepare: %d\n", imp_dbh->use_server_side_prepare); #endif /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if ((svp = hv_fetch(hv, "mysql_enable_utf8mb4", 20, FALSE)) && *svp && SvTRUE(*svp)) { mysql_options(sock, MYSQL_SET_CHARSET_NAME, "utf8mb4"); } else if ((svp = hv_fetch(hv, "mysql_enable_utf8", 17, FALSE)) && *svp) { /* Do not touch imp_dbh->enable_utf8 as we are called earlier * than it is set and mysql_options() must be before: * mysql_real_connect() */ mysql_options(sock, MYSQL_SET_CHARSET_NAME, (SvTRUE(*svp) ? "utf8" : "latin1")); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_options: MYSQL_SET_CHARSET_NAME=%s\n", (SvTRUE(*svp) ? "utf8" : "latin1")); } #endif #if defined(DBD_MYSQL_WITH_SSL) && !defined(DBD_MYSQL_EMBEDDED) && \ (defined(CLIENT_SSL) || (MYSQL_VERSION_ID >= 40000)) if ((svp = hv_fetch(hv, "mysql_ssl", 9, FALSE)) && *svp) { if (SvTRUE(*svp)) { char *client_key = NULL; char *client_cert = NULL; char *ca_file = NULL; char *ca_path = NULL; char *cipher = NULL; STRLEN lna; #if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION /* New code to utilise MySQLs new feature that verifies that the server's hostname that the client connects to matches that of the certificate */ my_bool ssl_verify_true = 0; if ((svp = hv_fetch(hv, "mysql_ssl_verify_server_cert", 28, FALSE)) && *svp) ssl_verify_true = SvTRUE(*svp); #endif if ((svp = hv_fetch(hv, "mysql_ssl_client_key", 20, FALSE)) && *svp) client_key = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_client_cert", 21, FALSE)) && *svp) client_cert = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_ca_file", 17, FALSE)) && *svp) ca_file = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_ca_path", 17, FALSE)) && *svp) ca_path = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_cipher", 16, FALSE)) && *svp) cipher = SvPV(*svp, lna); mysql_ssl_set(sock, client_key, client_cert, ca_file, ca_path, cipher); #if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION mysql_options(sock, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &ssl_verify_true); #endif client_flag |= CLIENT_SSL; } } #endif #if (MYSQL_VERSION_ID >= 32349) /* * MySQL 3.23.49 disables LOAD DATA LOCAL by default. Use * mysql_local_infile=1 in the DSN to enable it. */ if ((svp = hv_fetch( hv, "mysql_local_infile", 18, FALSE)) && *svp) { unsigned int flag = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Using" \ " local infile %u.\n", flag); mysql_options(sock, MYSQL_OPT_LOCAL_INFILE, (const char *) &flag); } #endif } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: client_flags = %d\n", client_flag); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION client_flag|= CLIENT_MULTI_RESULTS; #endif result = mysql_real_connect(sock, host, user, password, dbname, portNr, mysql_socket, client_flag); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: <-"); if (result) { #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* connection succeeded. */ /* imp_dbh == NULL when mysql_dr_connect() is called from mysql.xs functions (_admin_internal(),_ListDBs()). */ if (!(result->client_flag & CLIENT_PROTOCOL_41) && imp_dbh) imp_dbh->use_server_side_prepare = FALSE; #endif #if MYSQL_ASYNC if(imp_dbh) { imp_dbh->async_query_in_flight = NULL; } #endif /* we turn off Mysql's auto reconnect and handle re-connecting ourselves so that we can keep track of when this happens. */ result->reconnect=0; } else { /* sock was allocated with mysql_init() fixes: https://rt.cpan.org/Ticket/Display.html?id=86153 Safefree(sock); rurban: No, we still need this handle later in mysql_dr_error(). RT #97625. It will be freed as imp_dbh->pmysql in dbd_db_destroy(), which is called by the DESTROY handler. */ } return result; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,512
git
de1e67d0703894cb6ea782e36abb63976ab07e60
static struct commit *handle_commit(struct rev_info *revs, struct object_array_entry *entry) { struct object *object = entry->item; const char *name = entry->name; const char *path = entry->path; unsigned int mode = entry->mode; unsigned long flags = object->flags; /* * Tag object? Look what it points to.. */ while (object->type == OBJ_TAG) { struct tag *tag = (struct tag *) object; if (revs->tag_objects && !(flags & UNINTERESTING)) add_pending_object(revs, object, tag->tag); if (!tag->tagged) die("bad tag"); object = parse_object(tag->tagged->oid.hash); if (!object) { if (flags & UNINTERESTING) return NULL; die("bad object %s", oid_to_hex(&tag->tagged->oid)); } object->flags |= flags; /* * We'll handle the tagged object by looping or dropping * through to the non-tag handlers below. Do not * propagate path data from the tag's pending entry. */ path = NULL; mode = 0; } /* * Commit object? Just return it, we'll do all the complex * reachability crud. */ if (object->type == OBJ_COMMIT) { struct commit *commit = (struct commit *)object; if (parse_commit(commit) < 0) die("unable to parse commit %s", name); if (flags & UNINTERESTING) { mark_parents_uninteresting(commit); revs->limited = 1; } if (revs->show_source && !commit->util) commit->util = xstrdup(name); return commit; } /* * Tree object? Either mark it uninteresting, or add it * to the list of objects to look at later.. */ if (object->type == OBJ_TREE) { struct tree *tree = (struct tree *)object; if (!revs->tree_objects) return NULL; if (flags & UNINTERESTING) { mark_tree_contents_uninteresting(tree); return NULL; } add_pending_object_with_path(revs, object, name, mode, path); return NULL; } /* * Blob object? You know the drill by now.. */ if (object->type == OBJ_BLOB) { if (!revs->blob_objects) return NULL; if (flags & UNINTERESTING) return NULL; add_pending_object_with_path(revs, object, name, mode, path); return NULL; } die("%s is unknown object", name); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,127
radare2
1dd65336f0f0c351d6ea853efcf73cf9c0030862
static void r_coresym_cache_element_symbol_fini(RCoreSymCacheElementSymbol *sym) { if (sym) { free (sym->name); free (sym->mangled_name); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,493
linux
42cb14b110a5698ccf26ce59c4441722605a3743
void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); }
1
CVE-2016-3070
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.
7,987
php-src
8fa9d1ce28f3a894b104979df30d0b65e0f21107
int gdImageSetInterpolationMethod(gdImagePtr im, gdInterpolationMethod id) { if (im == NULL || id < 0 || id > GD_METHOD_COUNT) { return 0; } switch (id) { case GD_DEFAULT: id = GD_BILINEAR_FIXED; /* Optimized versions */ case GD_BILINEAR_FIXED: case GD_BICUBIC_FIXED: case GD_NEAREST_NEIGHBOUR: case GD_WEIGHTED4: im->interpolation = NULL; break; /* generic versions*/ case GD_BELL: im->interpolation = filter_bell; break; case GD_BESSEL: im->interpolation = filter_bessel; break; case GD_BICUBIC: im->interpolation = filter_bicubic; break; case GD_BLACKMAN: im->interpolation = filter_blackman; break; case GD_BOX: im->interpolation = filter_box; break; case GD_BSPLINE: im->interpolation = filter_bspline; break; case GD_CATMULLROM: im->interpolation = filter_catmullrom; break; case GD_GAUSSIAN: im->interpolation = filter_gaussian; break; case GD_GENERALIZED_CUBIC: im->interpolation = filter_generalized_cubic; break; case GD_HERMITE: im->interpolation = filter_hermite; break; case GD_HAMMING: im->interpolation = filter_hamming; break; case GD_HANNING: im->interpolation = filter_hanning; break; case GD_MITCHELL: im->interpolation = filter_mitchell; break; case GD_POWER: im->interpolation = filter_power; break; case GD_QUADRATIC: im->interpolation = filter_quadratic; break; case GD_SINC: im->interpolation = filter_sinc; break; case GD_TRIANGLE: im->interpolation = filter_triangle; break; default: return 0; break; } im->interpolation_id = id; return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,213
postgres
31400a673325147e1205326008e32135a78b4d8a
poly_path(PG_FUNCTION_ARGS) { POLYGON *poly = PG_GETARG_POLYGON_P(0); PATH *path; int size; int i; size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts; path = (PATH *) palloc(size); SET_VARSIZE(path, size); path->npts = poly->npts; path->closed = TRUE; /* prevent instability in unused pad bytes */ path->dummy = 0; for (i = 0; i < poly->npts; i++) { path->p[i].x = poly->p[i].x; path->p[i].y = poly->p[i].y; } PG_RETURN_PATH_P(path); }
1
CVE-2014-2669
CWE-189
Numeric Errors
Weaknesses in this category are related to improper calculation or conversion of numbers.
Not Found in CWE Page
1,524
FFmpeg
4c3e1956ee35fdcc5ffdb28782050164b4623c0b
static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst, const uint8_t *src, const uint8_t *src_end, int width, int esc_count) { int i = 0; int count; uint8_t zero_run = 0; const uint8_t *src_start = src; uint8_t mask1 = -(esc_count < 2); uint8_t mask2 = -(esc_count < 3); uint8_t *end = dst + (width - 2); output_zeros: if (l->zeros_rem) { count = FFMIN(l->zeros_rem, width - i); if (end - dst < count) { av_log(l->avctx, AV_LOG_ERROR, "Too many zeros remaining.\n"); return AVERROR_INVALIDDATA; } memset(dst, 0, count); l->zeros_rem -= count; dst += count; } while (dst < end) { i = 0; while (!zero_run && dst + i < end) { i++; if (src + i >= src_end) return AVERROR_INVALIDDATA; zero_run = !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2)); } if (zero_run) { zero_run = 0; i += esc_count; memcpy(dst, src, i); dst += i; l->zeros_rem = lag_calc_zero_run(src[i]); src += i + 1; goto output_zeros; } else { memcpy(dst, src, i); src += i; dst += i; } } return src_start - src; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,212
linux
4c185ce06dca14f5cea192f5a2c981ef50663f2b
void exit_aio(struct mm_struct *mm) { struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table); int i; if (!table) return; for (i = 0; i < table->nr; ++i) { struct kioctx *ctx = table->table[i]; struct completion requests_done = COMPLETION_INITIALIZER_ONSTACK(requests_done); if (!ctx) continue; /* * We don't need to bother with munmap() here - exit_mmap(mm) * is coming and it'll unmap everything. And we simply can't, * this is not necessarily our ->mm. * Since kill_ioctx() uses non-zero ->mmap_size as indicator * that it needs to unmap the area, just set it to 0. */ ctx->mmap_size = 0; kill_ioctx(mm, ctx, &requests_done); /* Wait until all IO for the context are done. */ wait_for_completion(&requests_done); } RCU_INIT_POINTER(mm->ioctx_table, NULL); kfree(table); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,857
FFmpeg
2fc108f60f98cd00813418a8754a46476b404a3c
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,433
Chrome
673ce95d481ea9368c4d4d43ac756ba1d6d9e608
void Initialized(mojo::ScopedSharedBufferHandle shared_buffer, mojo::ScopedHandle socket_handle, bool initially_muted) { ASSERT_TRUE(shared_buffer.is_valid()); ASSERT_TRUE(socket_handle.is_valid()); base::PlatformFile fd; mojo::UnwrapPlatformFile(std::move(socket_handle), &fd); socket_ = std::make_unique<base::CancelableSyncSocket>(fd); EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle); size_t memory_length; base::SharedMemoryHandle shmem_handle; bool read_only; EXPECT_EQ( mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle, &memory_length, &read_only), MOJO_RESULT_OK); EXPECT_TRUE(read_only); buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only); GotNotification(initially_muted); }
1
CVE-2018-6063
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).
7,287
w3m
a6257663824c63abb3c62c4dd62455fe6f63d958
if (status == R_ST_AMP) { r2 = tagbuf->ptr; t = getescapecmd(&r2); if (*t != '\r' && *t != '\n') len += get_strwidth(t) + get_strwidth(r2); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,110
linux
5edabca9d4cff7f1f2b68f0bac55ef99d9798ba4
static void dccp_enqueue_skb(struct sock *sk, struct sk_buff *skb) { __skb_pull(skb, dccp_hdr(skb)->dccph_doff * 4); __skb_queue_tail(&sk->sk_receive_queue, skb); skb_set_owner_r(skb, sk); sk->sk_data_ready(sk); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,468
launchpad
29014da83e5fc358d6bff0f574e9ed45e61a35ac
static void Set(ContentMainDelegate* delegate, bool single_process) { ContentClient* content_client = oxide::ContentClient::GetInstance(); content_client->browser_ = delegate->CreateContentBrowserClient(); if (single_process) { content_client->renderer_ = delegate->CreateContentRendererClient(); content_client->utility_ = delegate->CreateContentUtilityClient(); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,471
busybox
0402cb32df015d9372578e3db27db47b33d5c7b0
int main(int argc, char **argv) { char c; int i = unpack_bz2_stream(0, 1); if (i < 0) fprintf(stderr, "%s\n", bunzip_errors[-i]); else if (read(STDIN_FILENO, &c, 1)) fprintf(stderr, "Trailing garbage ignored\n"); return -i; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,000
Chrome
69ec52bd0b32622770a25952386596ccb4ad6434
LayoutUnit NGFlexLayoutAlgorithm::MainAxisContentExtent( LayoutUnit sum_hypothetical_main_size) { if (Style().IsColumnFlexDirection()) { return ComputeBlockSizeForFragment( ConstraintSpace(), Style(), sum_hypothetical_main_size + (borders_ + padding_).BlockSum()) - border_scrollbar_padding_.BlockSum(); } return content_box_size_.inline_size; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,493
openssl
6e629b5be45face20b4ca71c4fcbfed78b864a2e
static int check_chain_extensions(X509_STORE_CTX *ctx) { #ifdef OPENSSL_NO_CHAIN_VERIFY return 1; #else int i, ok = 0, must_be_ca, plen = 0; X509 *x; int (*cb) (int xok, X509_STORE_CTX *xctx); int proxy_path_length = 0; int purpose; int allow_proxy_certs; cb = ctx->verify_cb; /*- * must_be_ca can have 1 of 3 values: * -1: we accept both CA and non-CA certificates, to allow direct * use of self-signed certificates (which are marked as CA). * 0: we only accept non-CA certificates. This is currently not * used, but the possibility is present for future extensions. * 1: we only accept CA certificates. This is currently used for * all certificates in the chain except the leaf certificate. */ must_be_ca = -1; /* CRL path validation */ if (ctx->parent) { allow_proxy_certs = 0; purpose = X509_PURPOSE_CRL_SIGN; } else { allow_proxy_certs = ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS); /* * A hack to keep people who don't want to modify their software * happy */ if (getenv("OPENSSL_ALLOW_PROXY_CERTS")) allow_proxy_certs = 1; purpose = ctx->param->purpose; } /* Check all untrusted certificates */ for (i = 0; i < ctx->last_untrusted; i++) { int ret; x = sk_X509_value(ctx->chain, i); if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) && (x->ex_flags & EXFLAG_CRITICAL)) { ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) { ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } ret = X509_check_ca(x); switch (must_be_ca) { case -1: if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1) && (ret != 0)) { ret = 0; ctx->error = X509_V_ERR_INVALID_CA; } else ret = 1; break; case 0: if (ret != 0) { ret = 0; ctx->error = X509_V_ERR_INVALID_NON_CA; } else ret = 1; break; default: if ((ret == 0) || ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1))) { ret = 0; ctx->error = X509_V_ERR_INVALID_CA; } else ret = 1; break; } if (ret == 0) { ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } if (ctx->param->purpose > 0) { ret = X509_check_purpose(x, purpose, must_be_ca > 0); if ((ret == 0) || ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1))) { ctx->error = X509_V_ERR_INVALID_PURPOSE; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } } /* Check pathlen if not self issued */ if ((i > 1) && !(x->ex_flags & EXFLAG_SI) && (x->ex_pathlen != -1) && (plen > (x->ex_pathlen + proxy_path_length + 1))) { ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } /* Increment path length if not self issued */ if (!(x->ex_flags & EXFLAG_SI)) plen++; /* * If this certificate is a proxy certificate, the next certificate * must be another proxy certificate or a EE certificate. If not, * the next certificate must be a CA certificate. */ if (x->ex_flags & EXFLAG_PROXY) { /* * RFC3820, 4.1.3 (b)(1) stipulates that if pCPathLengthConstraint * is less than max_path_length, the former should be copied to * the latter, and 4.1.4 (a) stipulates that max_path_length * should be verified to be larger than zero and decrement it. * * Because we're checking the certs in the reverse order, we start * with verifying that proxy_path_length isn't larger than pcPLC, * and copy the latter to the former if it is, and finally, * increment proxy_path_length. */ if (x->ex_pcpathlen != -1) { if (proxy_path_length > x->ex_pcpathlen) { ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } proxy_path_length = x->ex_pcpathlen; } proxy_path_length++; must_be_ca = 0; } else must_be_ca = 1; } ok = 1; end: return ok; #endif }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,577
linux
54a20552e1eae07aa240fa370a0293e006b5faed
static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); }
1
CVE-2015-5307
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
9,586
Android
d834160d9759f1098df692b34e6eeb548f9e317b
OMX_ERRORTYPE SimpleSoftOMXComponent::useBuffer( OMX_BUFFERHEADERTYPE **header, OMX_U32 portIndex, OMX_PTR appPrivate, OMX_U32 size, OMX_U8 *ptr) { Mutex::Autolock autoLock(mLock); CHECK_LT(portIndex, mPorts.size()); *header = new OMX_BUFFERHEADERTYPE; (*header)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*header)->nVersion.s.nVersionMajor = 1; (*header)->nVersion.s.nVersionMinor = 0; (*header)->nVersion.s.nRevision = 0; (*header)->nVersion.s.nStep = 0; (*header)->pBuffer = ptr; (*header)->nAllocLen = size; (*header)->nFilledLen = 0; (*header)->nOffset = 0; (*header)->pAppPrivate = appPrivate; (*header)->pPlatformPrivate = NULL; (*header)->pInputPortPrivate = NULL; (*header)->pOutputPortPrivate = NULL; (*header)->hMarkTargetComponent = NULL; (*header)->pMarkData = NULL; (*header)->nTickCount = 0; (*header)->nTimeStamp = 0; (*header)->nFlags = 0; (*header)->nOutputPortIndex = portIndex; (*header)->nInputPortIndex = portIndex; PortInfo *port = &mPorts.editItemAt(portIndex); CHECK(mState == OMX_StateLoaded || port->mDef.bEnabled == OMX_FALSE); CHECK_LT(port->mBuffers.size(), port->mDef.nBufferCountActual); port->mBuffers.push(); BufferInfo *buffer = &port->mBuffers.editItemAt(port->mBuffers.size() - 1); buffer->mHeader = *header; buffer->mOwnedByUs = false; if (port->mBuffers.size() == port->mDef.nBufferCountActual) { port->mDef.bPopulated = OMX_TRUE; checkTransitions(); } return OMX_ErrorNone; }
1
CVE-2017-0817
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,462
tcpdump
cc4a7391c616be7a64ed65742ef9ed3f106eb165
l2tp_framing_cap_print(netdissect_options *ndo, const u_char *dat) { const uint32_t *ptr = (const uint32_t *)dat; if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_SYNC_MASK) { ND_PRINT((ndo, "S")); } }
1
CVE-2017-13006
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,489
Chrome
c7a90019bf7054145b11d2577b851cf2779d3d79
void PrintWebViewHelper::OnPrintForPrintPreview( const DictionaryValue& job_settings) { DCHECK(is_preview_); if (print_web_view_) return; if (!render_view()->webview()) return; WebFrame* main_frame = render_view()->webview()->mainFrame(); if (!main_frame) return; WebDocument document = main_frame->document(); WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } WebFrame* pdf_frame = pdf_element.document().frame(); scoped_ptr<PrepareFrameAndViewForPrint> prepare; if (!InitPrintSettingsAndPrepareFrame(pdf_frame, &pdf_element, &prepare)) { LOG(ERROR) << "Failed to initialize print page settings"; return; } if (!UpdatePrintSettings(job_settings, false)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } if (!RenderPagesForPrint(pdf_frame, &pdf_element, prepare.get())) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } }
1
CVE-2011-3897
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
2,517
ngiflib
cf429e0a2fe26b5f01ce0c8e9b79432e94509b6e
int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,235
php
1ddf72180a52d247db88ea42a3e35f824a8fbda1
static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/
1
CVE-2015-7804
CWE-189
Numeric Errors
Weaknesses in this category are related to improper calculation or conversion of numbers.
Not Found in CWE Page
8,918
linux
6e8ab72a812396996035a37e5ca4b3b99b5d214b
int ext4_inline_data_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, int *has_inline, __u64 start, __u64 len) { __u64 physical = 0; __u64 inline_len; __u32 flags = FIEMAP_EXTENT_DATA_INLINE | FIEMAP_EXTENT_NOT_ALIGNED | FIEMAP_EXTENT_LAST; int error = 0; struct ext4_iloc iloc; down_read(&EXT4_I(inode)->xattr_sem); if (!ext4_has_inline_data(inode)) { *has_inline = 0; goto out; } inline_len = min_t(size_t, ext4_get_inline_size(inode), i_size_read(inode)); if (start >= inline_len) goto out; if (start + len < inline_len) inline_len = start + len; inline_len -= start; error = ext4_get_inode_loc(inode, &iloc); if (error) goto out; physical = (__u64)iloc.bh->b_blocknr << inode->i_sb->s_blocksize_bits; physical += (char *)ext4_raw_inode(&iloc) - iloc.bh->b_data; physical += offsetof(struct ext4_inode, i_block); if (physical) error = fiemap_fill_next_extent(fieinfo, start, physical, inline_len, flags); brelse(iloc.bh); out: up_read(&EXT4_I(inode)->xattr_sem); return (error < 0 ? error : 0); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,976
linux
13054abbaa4f1fd4e6f3b4b63439ec033b4c8035
static int hid_debug_events_open(struct inode *inode, struct file *file) { int err = 0; struct hid_debug_list *list; unsigned long flags; if (!(list = kzalloc(sizeof(struct hid_debug_list), GFP_KERNEL))) { err = -ENOMEM; goto out; } err = kfifo_alloc(&list->hid_debug_fifo, HID_DEBUG_FIFOSIZE, GFP_KERNEL); if (err) { kfree(list); goto out; } list->hdev = (struct hid_device *) inode->i_private; file->private_data = list; mutex_init(&list->read_mutex); spin_lock_irqsave(&list->hdev->debug_list_lock, flags); list_add_tail(&list->node, &list->hdev->debug_list); spin_unlock_irqrestore(&list->hdev->debug_list_lock, flags); out: return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,265
ImageMagick
424d40ebfcde48bb872eba75179d3d73704fdf1f
static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if ((image -> colors <= 2 ) || (GetImageType(image,&image->exception ) == BilevelType)) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) CopyMagickMemory(pdb_info.type,"vIMG",4); (void) CopyMagickMemory(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment"); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets, image->rows*sizeof(*runlength)); if (runlength == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); buffer=(unsigned char *) AcquireQuantumMemory(256,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=(size_t) (image->depth > 8 ? 2: 1); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,scanline,&image->exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8* pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); }
1
CVE-2016-7537
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,097
cpython
6c004b40f9d51872d848981ef1a18bb08c2dfc42
_PyBytes_Join(PyObject *sep, PyObject *x) { assert(sep != NULL && PyBytes_Check(sep)); assert(x != NULL); return bytes_join(sep, x); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,416
Chrome
b944f670bb7a8a919daac497a4ea0536c954c201
JSValue JSWebKitMutationObserver::observe(ExecState* exec) { if (exec->argumentCount() < 2) return throwError(exec, createTypeError(exec, "Not enough arguments")); Node* target = toNode(exec->argument(0)); if (exec->hadException()) return jsUndefined(); JSObject* optionsObject = exec->argument(1).getObject(); if (!optionsObject) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } JSDictionary dictionary(exec, optionsObject); MutationObserverOptions options = 0; for (unsigned i = 0; i < numBooleanOptions; ++i) { bool option = false; if (!dictionary.tryGetProperty(booleanOptions[i].name, option)) return jsUndefined(); if (option) options |= booleanOptions[i].value; } HashSet<AtomicString> attributeFilter; if (!dictionary.tryGetProperty("attributeFilter", attributeFilter)) return jsUndefined(); if (!attributeFilter.isEmpty()) options |= WebKitMutationObserver::AttributeFilter; ExceptionCode ec = 0; impl()->observe(target, options, attributeFilter, ec); if (ec) setDOMException(exec, ec); return jsUndefined(); }
1
CVE-2011-2350
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,573