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
|
---|---|---|---|---|---|---|---|---|---|
qemu | a890a2f9137ac3cf5b607649e66a6f3a5512d8dc | static inline uint32_t vring_desc_len(hwaddr desc_pa, int i)
{
hwaddr pa;
pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, len);
return ldl_phys(&address_space_memory, pa);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,020 |
FFmpeg | a3a3730b5456ca00587455004d40c047f7b20a99 | static void cbs_jpeg_free_scan(void *unit, uint8_t *content)
{
JPEGRawScan *scan = (JPEGRawScan*)content;
av_buffer_unref(&scan->data_ref);
av_freep(&content);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,450 |
vim | 5a73e0ca54c77e067c3b12ea6f35e3e8681e8cf8 | modname(
char_u *fname,
char_u *ext,
int prepend_dot) /* may prepend a '.' to file name */
{
return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
fname, ext, prepend_dot);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,976 |
Chrome | 2571533bbb5b554ff47205c8ef1513ccc0817c3e | void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
| 1 | CVE-2014-7909 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 4,838 |
Chrome | c25b198675380f713a56649c857b4367601d4a3d | views::ImageButton* close_button() const {
return media_controls_view_->close_button_;
}
| 1 | CVE-2017-5107 | 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,038 |
Chrome | d82b03d21f7e581f9206ef1fec4959ae7b06b8eb | xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
int what, xmlChar end, xmlChar end2, xmlChar end3) {
xmlChar *buffer = NULL;
int buffer_size = 0;
xmlChar *current = NULL;
xmlChar *rep = NULL;
const xmlChar *last;
xmlEntityPtr ent;
int c,l;
int nbchars = 0;
if ((ctxt == NULL) || (str == NULL) || (len < 0))
return(NULL);
last = str + len;
if (((ctxt->depth > 40) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(ctxt->depth > 1024)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return(NULL);
}
/*
* allocate a translation buffer.
*/
buffer_size = XML_PARSER_BIG_BUFFER_SIZE;
buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar));
if (buffer == NULL) goto mem_error;
/*
* OK loop until we reach one of the ending char or a size limit.
* we are operating on already parsed values.
*/
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
while ((c != 0) && (c != end) && /* non input consuming loop */
(c != end2) && (c != end3)) {
if (c == 0) break;
if ((c == '&') && (str[1] == '#')) {
int val = xmlParseStringCharRef(ctxt, &str);
if (val != 0) {
COPY_BUF(0,buffer,nbchars,val);
}
if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding Entity Reference: %.30s\n",
str);
ent = xmlParseStringEntityRef(ctxt, &str);
if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
(ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
goto int_error;
if (ent != NULL)
ctxt->nbentities += ent->checked;
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (ent->content != NULL) {
COPY_BUF(0,buffer,nbchars,ent->content[0]);
if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"predefined entity has no content\n");
}
} else if ((ent != NULL) && (ent->content != NULL)) {
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars >
buffer_size - XML_PARSER_BUFFER_SIZE) {
if (xmlParserEntityCheck(ctxt, nbchars, ent))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
} else if (ent != NULL) {
int i = xmlStrlen(ent->name);
const xmlChar *cur = ent->name;
buffer[nbchars++] = '&';
if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
for (;i > 0;i--)
buffer[nbchars++] = *cur++;
buffer[nbchars++] = ';';
}
} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding PE Reference: %.30s\n", str);
ent = xmlParseStringPEReference(ctxt, &str);
if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
goto int_error;
if (ent != NULL)
ctxt->nbentities += ent->checked;
if (ent != NULL) {
if (ent->content == NULL) {
xmlLoadEntityContent(ctxt, ent);
}
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars >
buffer_size - XML_PARSER_BUFFER_SIZE) {
if (xmlParserEntityCheck(ctxt, nbchars, ent))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
}
} else {
COPY_BUF(l,buffer,nbchars,c);
str += l;
if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
}
buffer[nbchars] = 0;
return(buffer);
mem_error:
xmlErrMemory(ctxt, NULL);
int_error:
if (rep != NULL)
xmlFree(rep);
if (buffer != NULL)
xmlFree(buffer);
return(NULL);
}
| 1 | CVE-2011-3919 | 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). | 4,137 |
libgit2 | 4ac39c76c0153d1ee6889a0984c39e97731684b2 | int git_pkt_buffer_done(git_buf *buf)
{
return git_buf_puts(buf, pkt_done_str);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,970 |
OpenSC | cae5c71f90cc5b364efe14040923fd5aa3b5dd90 | sc_pkcs15emu_oberthur_add_cert(struct sc_pkcs15_card *p15card, unsigned int file_id)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_pkcs15_cert_info cinfo;
struct sc_pkcs15_object cobj;
unsigned char *info_blob = NULL, *cert_blob = NULL;
size_t info_len, cert_len, len, offs;
unsigned flags;
int rv;
char ch_tmp[0x20];
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "add certificate(file-id:%04X)", file_id);
memset(&cinfo, 0, sizeof(cinfo));
memset(&cobj, 0, sizeof(cobj));
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id | 0x100);
rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add certificate: read oberthur file error");
if (info_len < 2) {
free(info_blob);
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'tag'");
}
flags = *(info_blob + 0) * 0x100 + *(info_blob + 1);
offs = 2;
/* Label */
if (offs + 2 > info_len) {
free(info_blob);
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'CN'");
}
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len + offs + 2 > info_len) {
free(info_blob);
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Invalid 'CN' length");
} else if (len) {
if (len > sizeof(cobj.label) - 1)
len = sizeof(cobj.label) - 1;
memcpy(cobj.label, info_blob + offs + 2, len);
}
offs += 2 + len;
/* ID */
if (offs + 2 > info_len) {
free(info_blob);
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'ID'");
}
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len + offs + 2 > info_len) {
free(info_blob);
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Invalid 'ID' length");
} else if (len > sizeof(cinfo.id.value)) {
free(info_blob);
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add certificate: invalid 'ID' length");
}
memcpy(cinfo.id.value, info_blob + offs + 2, len);
cinfo.id.len = len;
free(info_blob);
/* Ignore subject, issuer and serial */
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id);
sc_format_path(ch_tmp, &cinfo.path);
rv = sc_oberthur_read_file(p15card, ch_tmp, &cert_blob, &cert_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add certificate: read certificate error");
cinfo.value.value = cert_blob;
cinfo.value.len = cert_len;
rv = sc_oberthur_get_certificate_authority(&cinfo.value, &cinfo.authority);
if (rv != SC_SUCCESS) {
free(cinfo.value.value);
LOG_TEST_RET(ctx, rv, "Failed to add certificate: get certificate attributes error");
}
if (flags & OBERTHUR_ATTR_MODIFIABLE)
cobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE;
rv = sc_pkcs15emu_add_x509_cert(p15card, &cobj, &cinfo);
LOG_FUNC_RETURN(p15card->card->ctx, rv);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,803 |
Android | 295c883fe3105b19bcd0f9e07d54c6b589fc5bff | OMX_ERRORTYPE SoftAMR::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (mMode == MODE_NARROW) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.amrnb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.amrwb",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
const OMX_AUDIO_PARAM_AMRTYPE *aacParams =
(const OMX_AUDIO_PARAM_AMRTYPE *)params;
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 1 | CVE-2016-2476 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,281 |
Chrome | 116d0963cadfbf55ef2ec3d13781987c4d80517a | void PrintPreviewDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (!EndsWith(path, "/print.pdf", true)) {
ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id);
return;
}
scoped_refptr<base::RefCountedBytes> data;
std::vector<std::string> url_substr;
base::SplitString(path, '/', &url_substr);
int page_index = 0;
if (url_substr.size() == 3 && base::StringToInt(url_substr[1], &page_index)) {
PrintPreviewDataService::GetInstance()->GetDataEntry(
url_substr[0], page_index, &data);
}
if (data.get()) {
SendResponse(request_id, data);
return;
}
scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
SendResponse(request_id, empty_bytes);
}
| 1 | CVE-2012-2891 | 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,048 |
linux | bcf3b67d16a4c8ffae0aa79de5853435e683945c | support_nvme_encapsulation_show(struct device_driver *dd, char *buf)
{
return sprintf(buf, "%u\n", support_nvme_encapsulation);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,893 |
linux | 34b2cef20f19c87999fff3da4071e66937db9644 | static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,
int tlen, int offset)
{
__wsum csum = skb->csum;
if (skb->ip_summed != CHECKSUM_COMPLETE)
return;
if (offset != 0)
csum = csum_sub(csum,
csum_partial(skb_transport_header(skb) + tlen,
offset, 0));
put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,414 |
linux-stable | 59643d1535eb220668692a5359de22545af579f6 | ring_buffer_commit_overrun_cpu(struct ring_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
unsigned long ret;
if (!cpumask_test_cpu(cpu, buffer->cpumask))
return 0;
cpu_buffer = buffer->buffers[cpu];
ret = local_read(&cpu_buffer->commit_overrun);
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,186 |
x11vnc | 69eeb9f7baa14ca03b16c9de821f9876def7a36a | static void print_tiles(void) {
/* hack for viewing tile diffs on the screen. */
static char *prev = NULL;
int n, x, y, ms = 1500;
ms = 1;
if (! prev) {
prev = (char *) malloc((size_t) ntiles);
for (n=0; n < ntiles; n++) {
prev[n] = 0;
}
}
fprintf(stderr, " ");
for (x=0; x < ntiles_x; x++) {
fprintf(stderr, "%1d", x % 10);
}
fprintf(stderr, "\n");
n = 0;
for (y=0; y < ntiles_y; y++) {
fprintf(stderr, "%2d ", y);
for (x=0; x < ntiles_x; x++) {
if (tile_has_diff[n]) {
fprintf(stderr, "X");
} else if (prev[n]) {
fprintf(stderr, "o");
} else {
fprintf(stderr, ".");
}
n++;
}
fprintf(stderr, "\n");
}
for (n=0; n < ntiles; n++) {
prev[n] = tile_has_diff[n];
}
usleep(ms * 1000);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,683 |
Android | 086d84f45ab7b64d1a7ed7ac8ba5833664a6a5ab | status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
buffer_meta->CopyToOMX(header);
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer);
}
| 1 | CVE-2015-3835 | 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,709 |
tensorflow | 3d89911481ba6ebe8c88c1c0b595412121e6c645 | string DebugString(const GraphDef& instantiated_func_def) {
std::vector<const NodeDef*> ptrs;
for (const NodeDef& n : instantiated_func_def.node()) {
ptrs.push_back(&n);
}
return Print(ptrs);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,442 |
ovs | 803ed12e31b0377c37d7aa8c94b3b92f2081e349 | ipf_is_first_v6_frag(ovs_be16 ip6f_offlg)
{
if (!(ip6f_offlg & IP6F_OFF_MASK) &&
ip6f_offlg & IP6F_MORE_FRAG) {
return true;
}
return false;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,368 |
Chrome | 744c2a2d90c3c9a33c818e1ea4b7ccb5010663a0 | virtual bool IsURLAcceptableForWebUI(
BrowserContext* browser_context, const GURL& url) const {
return HasWebUIScheme(url);
}
| 1 | CVE-2011-3084 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 8,440 |
openssl | ef11e19d1365eea2b1851e6f540a0bf365d303e7 | static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
{
BIGNUM *kinv = NULL;
BIGNUM *m, *blind, *blindm, *tmp;
BN_CTX *ctx = NULL;
int reason = ERR_R_BN_LIB;
DSA_SIG *ret = NULL;
int rv = 0;
if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) {
reason = DSA_R_MISSING_PARAMETERS;
goto err;
}
ret = DSA_SIG_new();
if (ret == NULL)
goto err;
ret->r = BN_new();
ret->s = BN_new();
if (ret->r == NULL || ret->s == NULL)
goto err;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
m = BN_CTX_get(ctx);
blind = BN_CTX_get(ctx);
blindm = BN_CTX_get(ctx);
tmp = BN_CTX_get(ctx);
if (tmp == NULL)
goto err;
redo:
if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen))
goto err;
if (dlen > BN_num_bytes(dsa->q))
/*
* if the digest length is greater than the size of q use the
* BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
* 4.2
*/
dlen = BN_num_bytes(dsa->q);
if (BN_bin2bn(dgst, dlen, m) == NULL)
goto err;
/*
* The normal signature calculation is:
*
* s := k^-1 * (m + r * priv_key) mod q
*
* We will blind this to protect against side channel attacks
*
* s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q
*/
/* Generate a blinding value */
do {
if (!BN_rand(blind, BN_num_bits(dsa->q) - 1, BN_RAND_TOP_ANY,
BN_RAND_BOTTOM_ANY))
goto err;
} while (BN_is_zero(blind));
BN_set_flags(blind, BN_FLG_CONSTTIME);
BN_set_flags(blindm, BN_FLG_CONSTTIME);
BN_set_flags(tmp, BN_FLG_CONSTTIME);
/* tmp := blind * priv_key * r mod q */
if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->q, ctx))
goto err;
if (!BN_mod_mul(tmp, tmp, ret->r, dsa->q, ctx))
goto err;
/* blindm := blind * m mod q */
if (!BN_mod_mul(blindm, blind, m, dsa->q, ctx))
goto err;
/* s : = (blind * priv_key * r) + (blind * m) mod q */
if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->q))
goto err;
/* s := s * k^-1 mod q */
if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->q, ctx))
goto err;
/* s:= s * blind^-1 mod q */
if (BN_mod_inverse(blind, blind, dsa->q, ctx) == NULL)
goto err;
if (!BN_mod_mul(ret->s, ret->s, blind, dsa->q, ctx))
goto err;
/*
* Redo if r or s is zero as required by FIPS 186-3: this is very
* unlikely.
*/
if (BN_is_zero(ret->r) || BN_is_zero(ret->s))
goto redo;
rv = 1;
err:
if (rv == 0) {
DSAerr(DSA_F_DSA_DO_SIGN, reason);
DSA_SIG_free(ret);
ret = NULL;
}
BN_CTX_free(ctx);
BN_clear_free(kinv);
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,283 |
samba | 63d98ed90466295d0e946f79868d3d7aad6e7589 | bool file_compare(const char *path1, const char *path2)
{
size_t size1, size2;
char *p1, *p2;
TALLOC_CTX *mem_ctx = talloc_new(NULL);
p1 = file_load(path1, &size1, 0, mem_ctx);
p2 = file_load(path2, &size2, 0, mem_ctx);
if (!p1 || !p2 || size1 != size2) {
talloc_free(mem_ctx);
return false;
}
if (memcmp(p1, p2, size1) != 0) {
talloc_free(mem_ctx);
return false;
}
talloc_free(mem_ctx);
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,937 |
ytnef | 3cb0f914d6427073f262e1b2b5fd973e3043cdf7 | int TNEFParse(TNEFStruct *TNEF) {
WORD key;
DWORD type;
DWORD size;
DWORD signature;
BYTE *data;
WORD checksum, header_checksum;
int i;
if (TNEF->IO.ReadProc == NULL) {
printf("ERROR: Setup incorrectly: No ReadProc\n");
return YTNEF_INCORRECT_SETUP;
}
if (TNEF->IO.InitProc != NULL) {
DEBUG(TNEF->Debug, 2, "About to initialize");
if (TNEF->IO.InitProc(&TNEF->IO) != 0) {
return YTNEF_CANNOT_INIT_DATA;
}
DEBUG(TNEF->Debug, 2, "Initialization finished");
}
DEBUG(TNEF->Debug, 2, "Reading Signature");
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {
printf("ERROR: Error reading signature\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "Checking Signature");
if (TNEFCheckForSignature(signature) < 0) {
printf("ERROR: Signature does not match. Not TNEF.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NOT_TNEF_STREAM;
}
DEBUG(TNEF->Debug, 2, "Reading Key.");
if (TNEFGetKey(TNEF, &key) < 0) {
printf("ERROR: Unable to retrieve key.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NO_KEY;
}
DEBUG(TNEF->Debug, 2, "Starting Full Processing.");
while (TNEFGetHeader(TNEF, &type, &size) == 0) {
DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size);
DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size);
data = calloc(size, sizeof(BYTE));
ALLOCCHECK(data);
if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {
printf("ERROR: Unable to read data.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {
printf("ERROR: Unable to read checksum.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));
if (checksum != header_checksum) {
printf("ERROR: Checksum mismatch. Data corruption?:\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_BAD_CHECKSUM;
}
for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {
if (TNEFList[i].id == type) {
if (TNEFList[i].handler != NULL) {
if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {
free(data);
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_IN_HANDLER;
} else {
// Found our handler and processed it. now time to get out
break;
}
} else {
DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes",
TNEFList[i].name, size);
}
}
}
free(data);
}
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return 0;
} | 1 | CVE-2017-6801 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 2,076 |
mutt | 04b06aaa3e0cc0022b9b01dbca2863756ebbf59a | int imap_open_connection (IMAP_DATA* idata)
{
if (mutt_socket_open (idata->conn) < 0)
return -1;
idata->state = IMAP_CONNECTED;
if (imap_cmd_step (idata) != IMAP_CMD_OK)
{
imap_close_connection (idata);
return -1;
}
if (ascii_strncasecmp ("* OK", idata->buf, 4) == 0)
{
if (ascii_strncasecmp ("* OK [CAPABILITY", idata->buf, 16)
&& imap_check_capabilities (idata))
goto bail;
#if defined(USE_SSL)
/* Attempt STARTTLS if available and desired. */
if (!idata->conn->ssf && (option(OPTSSLFORCETLS) ||
mutt_bit_isset (idata->capabilities, STARTTLS)))
{
int rc;
if (option(OPTSSLFORCETLS))
rc = MUTT_YES;
else if ((rc = query_quadoption (OPT_SSLSTARTTLS,
_("Secure connection with TLS?"))) == -1)
goto err_close_conn;
if (rc == MUTT_YES)
{
if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
goto bail;
if (rc != -2)
{
if (mutt_ssl_starttls (idata->conn))
{
mutt_error (_("Could not negotiate TLS connection"));
mutt_sleep (1);
goto err_close_conn;
}
else
{
/* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
if (imap_exec (idata, "CAPABILITY", 0))
goto bail;
}
}
}
}
if (option(OPTSSLFORCETLS) && ! idata->conn->ssf)
{
mutt_error _("Encrypted connection unavailable");
mutt_sleep (1);
goto err_close_conn;
}
#endif
}
else if (ascii_strncasecmp ("* PREAUTH", idata->buf, 9) == 0)
{
#if defined(USE_SSL)
/* Unless using a secure $tunnel, an unencrypted PREAUTH response
* may be a MITM attack. The only way to stop "STARTTLS" MITM
* attacks is via $ssl_force_tls: an attacker can easily spoof
* "* OK" and strip the STARTTLS capability. So consult
* $ssl_force_tls, not $ssl_starttls, to decide whether to
* abort. Note that if using $tunnel and $tunnel_is_secure,
* conn->ssf will be set to 1. */
if (!idata->conn->ssf && option(OPTSSLFORCETLS))
{
mutt_error _("Encrypted connection unavailable");
mutt_sleep (1);
goto err_close_conn;
}
#endif
idata->state = IMAP_AUTHENTICATED;
if (imap_check_capabilities (idata) != 0)
goto bail;
FREE (&idata->capstr);
}
else
{
imap_error ("imap_open_connection()", idata->buf);
goto bail;
}
return 0;
#if defined(USE_SSL)
err_close_conn:
#endif
bail:
imap_close_connection (idata);
FREE (&idata->capstr);
return -1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,541 |
suricata | 843d0b7a10bb45627f94764a6c5d468a24143345 | static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,801 |
linux | f6d8bd051c391c1c0458a30b2a7abcd939329259 | void inet_sock_destruct(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
__skb_queue_purge(&sk->sk_receive_queue);
__skb_queue_purge(&sk->sk_error_queue);
sk_mem_reclaim(sk);
if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) {
pr_err("Attempt to release TCP socket in state %d %p\n",
sk->sk_state, sk);
return;
}
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Attempt to release alive inet socket %p\n", sk);
return;
}
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(sk->sk_wmem_queued);
WARN_ON(sk->sk_forward_alloc);
kfree(inet->opt);
dst_release(rcu_dereference_check(sk->sk_dst_cache, 1));
sk_refcnt_debug_dec(sk);
}
| 1 | CVE-2012-3552 | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently. | Phase: Architecture and Design
In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.
Phase: Architecture and Design
Use thread-safe capabilities such as the data access abstraction in Spring.
Phase: Architecture and Design
Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring.
Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).
Phase: Implementation
When using multithreading and operating on shared variables, only use thread-safe functions.
Phase: Implementation
Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.
Phase: Implementation
Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.
Phase: Implementation
Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.
Phase: Implementation
Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.
Phase: Implementation
Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help.
Phases: Architecture and Design; Operation
Strategy: Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations | 7,215 |
linux | ce1fad2740c648a4340f6f6c391a8a83769d2e8c | static struct key *construct_key_and_link(struct keyring_search_context *ctx,
const char *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct key_user *user;
struct key *key;
int ret;
kenter("");
user = key_user_lookup(current_fsuid());
if (!user)
return ERR_PTR(-ENOMEM);
construct_get_dest_keyring(&dest_keyring);
ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
key_user_put(user);
if (ret == 0) {
ret = construct_key(key, callout_info, callout_len, aux,
dest_keyring);
if (ret < 0) {
kdebug("cons failed");
goto construction_failed;
}
} else if (ret == -EINPROGRESS) {
ret = 0;
} else {
goto couldnt_alloc_key;
}
key_put(dest_keyring);
kleave(" = key %d", key_serial(key));
return key;
construction_failed:
key_negate_and_link(key, key_negative_timeout, NULL, NULL);
key_put(key);
couldnt_alloc_key:
key_put(dest_keyring);
kleave(" = %d", ret);
return ERR_PTR(ret);
}
| 1 | CVE-2015-7872 | 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,341 |
linux | 819cbb120eaec7e014e5abd029260db1ca8c5735 | static void comedi_cleanup_legacy_minors(void)
{
unsigned i;
for (i = 0; i < comedi_num_legacy_minors; i++)
comedi_free_board_minor(i);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,372 |
linux | 43629f8f5ea32a998d06d1bb41eefa0e821ff573 | static int bnep_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct bnep_connlist_req cl;
struct bnep_connadd_req ca;
struct bnep_conndel_req cd;
struct bnep_conninfo ci;
struct socket *nsock;
void __user *argp = (void __user *)arg;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
switch (cmd) {
case BNEPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
nsock = sockfd_lookup(ca.sock, &err);
if (!nsock)
return err;
if (nsock->sk->sk_state != BT_CONNECTED) {
sockfd_put(nsock);
return -EBADFD;
}
ca.device[sizeof(ca.device)-1] = 0;
err = bnep_add_connection(&ca, nsock);
if (!err) {
if (copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
} else
sockfd_put(nsock);
return err;
case BNEPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return bnep_del_connection(&cd);
case BNEPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case BNEPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = bnep_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
default:
return -EINVAL;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,599 |
polkit | bc7ffad53643a9c80231fc41f5582d6a8931c32c | polkit_backend_session_monitor_class_init (PolkitBackendSessionMonitorClass *klass)
{
GObjectClass *gobject_class;
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = polkit_backend_session_monitor_finalize;
/**
* PolkitBackendSessionMonitor::changed:
* @monitor: A #PolkitBackendSessionMonitor
*
* Emitted when something changes.
*/
signals[CHANGED_SIGNAL] = g_signal_new ("changed",
POLKIT_BACKEND_TYPE_SESSION_MONITOR,
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (PolkitBackendSessionMonitorClass, changed),
NULL, /* accumulator */
NULL, /* accumulator data */
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE,
0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,646 |
Chrome | 1c40f9042ae2d6ee7483d72998aabb5e73b2ff60 | ResourceRequestBlockedReason BaseFetchContext::CanRequest(
Resource::Type type,
const ResourceRequest& resource_request,
const KURL& url,
const ResourceLoaderOptions& options,
SecurityViolationReportingPolicy reporting_policy,
FetchParameters::OriginRestriction origin_restriction,
ResourceRequest::RedirectStatus redirect_status) const {
ResourceRequestBlockedReason blocked_reason =
CanRequestInternal(type, resource_request, url, options, reporting_policy,
origin_restriction, redirect_status);
if (blocked_reason != ResourceRequestBlockedReason::kNone &&
reporting_policy == SecurityViolationReportingPolicy::kReport) {
DispatchDidBlockRequest(resource_request, options.initiator_info,
blocked_reason);
}
return blocked_reason;
}
| 1 | CVE-2017-5009 | 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,414 |
Android | 9f0fb67540d2259e4930d9bd5f1a1a6fb95af862 | void ihevcd_parse_sei_payload(codec_t *ps_codec,
UWORD32 u4_payload_type,
UWORD32 u4_payload_size,
WORD8 i1_nal_type)
{
parse_ctxt_t *ps_parse = &ps_codec->s_parse;
bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm;
WORD32 payload_bits_remaining = 0;
sps_t *ps_sps;
UWORD32 i;
for(i = 0; i < MAX_SPS_CNT; i++)
{
ps_sps = ps_codec->ps_sps_base + i;
if(ps_sps->i1_sps_valid)
{
break;
}
}
if(NULL == ps_sps)
{
return;
}
if(NAL_PREFIX_SEI == i1_nal_type)
{
switch(u4_payload_type)
{
case SEI_BUFFERING_PERIOD:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_buffering_period_sei(ps_codec, ps_sps);
break;
case SEI_PICTURE_TIMING:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_pic_timing_sei(ps_codec, ps_sps);
break;
case SEI_TIME_CODE:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_time_code_sei(ps_codec);
break;
case SEI_MASTERING_DISPLAY_COLOUR_VOLUME:
ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1;
ihevcd_parse_mastering_disp_params_sei(ps_codec);
break;
case SEI_USER_DATA_REGISTERED_ITU_T_T35:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
if(ps_parse->s_sei_params.i4_sei_user_data_cnt >= USER_DATA_MAX)
{
for(i = 0; i < u4_payload_size / 4; i++)
{
ihevcd_bits_flush(ps_bitstrm, 4 * 8);
}
ihevcd_bits_flush(ps_bitstrm, (u4_payload_size - i * 4) * 8);
}
else
{
ihevcd_parse_user_data_registered_itu_t_t35(ps_codec,
u4_payload_size);
}
break;
default:
for(i = 0; i < u4_payload_size; i++)
{
ihevcd_bits_flush(ps_bitstrm, 8);
}
break;
}
}
else /* NAL_SUFFIX_SEI */
{
switch(u4_payload_type)
{
case SEI_USER_DATA_REGISTERED_ITU_T_T35:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
if(ps_parse->s_sei_params.i4_sei_user_data_cnt >= USER_DATA_MAX)
{
for(i = 0; i < u4_payload_size / 4; i++)
{
ihevcd_bits_flush(ps_bitstrm, 4 * 8);
}
ihevcd_bits_flush(ps_bitstrm, (u4_payload_size - i * 4) * 8);
}
else
{
ihevcd_parse_user_data_registered_itu_t_t35(ps_codec,
u4_payload_size);
}
break;
default:
for(i = 0; i < u4_payload_size; i++)
{
ihevcd_bits_flush(ps_bitstrm, 8);
}
break;
}
}
/**
* By definition the underlying bitstream terminates in a byte-aligned manner.
* 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data
* 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker
* 3. Extract the remainingreserved_payload_extension_data bits.
*
* If there are fewer than 9 bits available, extract them.
*/
payload_bits_remaining = ihevcd_bits_num_bits_remaining(ps_bitstrm);
if(payload_bits_remaining) /* more_data_in_payload() */
{
WORD32 final_bits;
WORD32 final_payload_bits = 0;
WORD32 mask = 0xFF;
UWORD32 u4_dummy;
UWORD32 u4_reserved_payload_extension_data;
UNUSED(u4_dummy);
UNUSED(u4_reserved_payload_extension_data);
while(payload_bits_remaining > 9)
{
BITS_PARSE("reserved_payload_extension_data",
u4_reserved_payload_extension_data, ps_bitstrm, 1);
payload_bits_remaining--;
}
final_bits = ihevcd_bits_nxt(ps_bitstrm, payload_bits_remaining);
while(final_bits & (mask >> final_payload_bits))
{
final_payload_bits++;
continue;
}
while(payload_bits_remaining > (9 - final_payload_bits))
{
BITS_PARSE("reserved_payload_extension_data",
u4_reserved_payload_extension_data, ps_bitstrm, 1);
payload_bits_remaining--;
}
BITS_PARSE("payload_bit_equal_to_one", u4_dummy, ps_bitstrm, 1);
payload_bits_remaining--;
while(payload_bits_remaining)
{
BITS_PARSE("payload_bit_equal_to_zero", u4_dummy, ps_bitstrm, 1);
payload_bits_remaining--;
}
}
return;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,583 |
kvm | a2c118bfab8bc6b8bb213abfc35201e441693d55 | void kvm_ioapic_clear_all(struct kvm_ioapic *ioapic, int irq_source_id)
{
int i;
spin_lock(&ioapic->lock);
for (i = 0; i < KVM_IOAPIC_NUM_PINS; i++)
__clear_bit(irq_source_id, &ioapic->irq_states[i]);
spin_unlock(&ioapic->lock);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,162 |
Chrome | 6b96dd532af164a73f2aac757bafff58211aca2c | void ChromeWebContentsDelegateAndroid::AddNewContents(
WebContents* source,
WebContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
DCHECK_NE(disposition, SAVE_TO_DISK);
DCHECK_NE(disposition, CURRENT_TAB);
TabHelpers::AttachTabHelpers(new_contents);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = GetJavaDelegate(env);
AddWebContentsResult add_result =
ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE;
if (!obj.is_null()) {
ScopedJavaLocalRef<jobject> jsource;
if (source)
jsource = source->GetJavaWebContents();
ScopedJavaLocalRef<jobject> jnew_contents;
if (new_contents)
jnew_contents = new_contents->GetJavaWebContents();
add_result = static_cast<AddWebContentsResult>(
Java_ChromeWebContentsDelegateAndroid_addNewContents(
env,
obj.obj(),
jsource.obj(),
jnew_contents.obj(),
static_cast<jint>(disposition),
NULL,
user_gesture));
}
if (was_blocked)
*was_blocked = !(add_result == ADD_WEB_CONTENTS_RESULT_PROCEED);
if (add_result == ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE)
delete new_contents;
}
| 1 | CVE-2013-6635 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 5,670 |
jasper | 12db8078ba17a8ffc5cc2429fb506988f0f11b44 | static int ras_putint(jas_stream_t *out, int_fast32_t val)
{
int_fast32_t x;
int i;
int c;
assert(val >= 0);
x = val;
for (i = 0; i < 4; i++) {
c = (x >> (8 * (3 - i))) & 0xff;
if (jas_stream_putc(out, c) == EOF) {
return -1;
}
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,995 |
tensorflow | 99085e8ff02c3763a0ec2263e44daec416f6a387 | void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(0);
const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);
Tensor* output = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));
Tensor num_bits_tensor;
num_bits_tensor = ctx->input(3);
int num_bits_val = num_bits_tensor.scalar<int32>()();
OP_REQUIRES(
ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63),
errors::InvalidArgument("num_bits is out of range: ", num_bits_val,
" with signed_input_ ", signed_input_));
Tensor input_min_tensor;
Tensor input_max_tensor;
if (range_given_) {
input_min_tensor = ctx->input(1);
input_max_tensor = ctx->input(2);
if (axis_ == -1) {
auto min_val = input_min_tensor.scalar<T>()();
auto max_val = input_max_tensor.scalar<T>()();
OP_REQUIRES(ctx, min_val <= max_val,
errors::InvalidArgument("Invalid range: input_min ",
min_val, " > input_max ", max_val));
} else {
OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_min_tensor has incorrect size, was ",
input_min_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_min_tensor.shape()));
OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_max_tensor has incorrect size, was ",
input_max_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_max_tensor.shape()));
}
} else {
auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_min_tensor));
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_max_tensor));
}
if (axis_ == -1) {
functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,
num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,
ROUND_HALF_TO_EVEN, narrow_range_, output->flat<T>());
} else {
functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;
f(ctx->eigen_device<Device>(),
input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,
num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,
ROUND_HALF_TO_EVEN, narrow_range_,
output->template flat_inner_outer_dims<T, 3>(axis_ - 1));
}
} | 1 | CVE-2021-29553 | 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,822 |
unbound | 6c3a0b54ed8ace93d5b5ca7b8078dc87e75cd640 | static int inplace_cb_reply_call_generic(
struct inplace_cb* callback_list, enum inplace_cb_list_type type,
struct query_info* qinfo, struct module_qstate* qstate,
struct reply_info* rep, int rcode, struct edns_data* edns,
struct comm_reply* repinfo, struct regional* region)
{
struct inplace_cb* cb;
struct edns_option* opt_list_out = NULL;
#if defined(EXPORT_ALL_SYMBOLS)
(void)type; /* param not used when fptr_ok disabled */
#endif
if(qstate)
opt_list_out = qstate->edns_opts_front_out;
for(cb=callback_list; cb; cb=cb->next) {
fptr_ok(fptr_whitelist_inplace_cb_reply_generic(
(inplace_cb_reply_func_type*)cb->cb, type));
(void)(*(inplace_cb_reply_func_type*)cb->cb)(qinfo, qstate, rep,
rcode, edns, &opt_list_out, repinfo, region, cb->id, cb->cb_arg);
}
edns->opt_list = opt_list_out;
return 1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,872 |
optee_os | 7e768f8a473409215fe3fff8f6e31f8a3a0103c6 | static void set_ta_ctx_ops(struct tee_ta_ctx *ctx)
{
ctx->ops = _user_ta_ops;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,182 |
linux | 6cd1ed50efd88261298577cd92a14f2768eddeeb | long vt_compat_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct vc_data *vc = tty->driver_data;
struct console_font_op op; /* used in multiple places here */
unsigned int console = vc->vc_num;
void __user *up = compat_ptr(arg);
int perm;
if (!vc_cons_allocated(console)) /* impossible? */
return -ENOIOCTLCMD;
/*
* To have permissions to do most of the vt ioctls, we either have
* to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
*/
perm = 0;
if (current->signal->tty == tty || capable(CAP_SYS_TTY_CONFIG))
perm = 1;
switch (cmd) {
/*
* these need special handlers for incompatible data structures
*/
case PIO_FONTX:
case GIO_FONTX:
return compat_fontx_ioctl(cmd, up, perm, &op);
case KDFONTOP:
return compat_kdfontop_ioctl(up, perm, &op, vc);
case PIO_UNIMAP:
case GIO_UNIMAP:
return compat_unimap_ioctl(cmd, up, perm, vc);
/*
* all these treat 'arg' as an integer
*/
case KIOCSOUND:
case KDMKTONE:
#ifdef CONFIG_X86
case KDADDIO:
case KDDELIO:
#endif
case KDSETMODE:
case KDMAPDISP:
case KDUNMAPDISP:
case KDSKBMODE:
case KDSKBMETA:
case KDSKBLED:
case KDSETLED:
case KDSIGACCEPT:
case VT_ACTIVATE:
case VT_WAITACTIVE:
case VT_RELDISP:
case VT_DISALLOCATE:
case VT_RESIZE:
case VT_RESIZEX:
return vt_ioctl(tty, cmd, arg);
/*
* the rest has a compatible data structure behind arg,
* but we have to convert it to a proper 64 bit pointer.
*/
default:
return vt_ioctl(tty, cmd, (unsigned long)up);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,482 |
ghostscript | 60dabde18d7fe12b19da8b509bdfee9cc886aafc | xps_lookup_alternate_content(fz_xml *node)
{
for (node = fz_xml_down(node); node; node = fz_xml_next(node))
{
if (!strcmp(fz_xml_tag(node), "mc:Choice") && fz_xml_att(node, "Requires"))
{
char list[64];
char *next = list, *item;
fz_strlcpy(list, fz_xml_att(node, "Requires"), sizeof(list));
while ((item = fz_strsep(&next, " \t\r\n")) != NULL && (!*item || !strcmp(item, "xps")));
if (!item)
return fz_xml_down(node);
}
else if (!strcmp(fz_xml_tag(node), "mc:Fallback"))
return fz_xml_down(node);
}
return NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,117 |
libarchive | 98dcbbf0bf4854bf987557e55e55fff7abbf3ea9 | lha_read_file_header_1(struct archive_read *a, struct lha *lha)
{
const unsigned char *p;
size_t extdsize;
int i, err, err2;
int namelen, padding;
unsigned char headersum, sum_calculated;
err = ARCHIVE_OK;
if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
return (truncated_error(a));
lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
headersum = p[H1_HEADER_SUM_OFFSET];
/* Note: An extended header size is included in a compsize. */
lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
namelen = p[H1_NAME_LEN_OFFSET];
/* Calculate a padding size. The result will be normally 0 only(?) */
padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
if (namelen > 230 || padding < 0)
goto invalid;
if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
return (truncated_error(a));
for (i = 0; i < namelen; i++) {
if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
goto invalid;/* Invalid filename. */
}
archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
lha->setflag |= CRC_IS_SET;
sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
/* Consume used bytes but not include `next header size' data
* since it will be consumed in lha_read_file_extended_header(). */
__archive_read_consume(a, lha->header_size - 2);
/* Read extended headers */
err2 = lha_read_file_extended_header(a, lha, NULL, 2,
(size_t)(lha->compsize + 2), &extdsize);
if (err2 < ARCHIVE_WARN)
return (err2);
if (err2 < err)
err = err2;
/* Get a real compressed file size. */
lha->compsize -= extdsize - 2;
if (sum_calculated != headersum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LHa header sum error");
return (ARCHIVE_FATAL);
}
return (err);
invalid:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid LHa header");
return (ARCHIVE_FATAL);
}
| 1 | CVE-2017-5601 | 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. | 2,125 |
sqlcipher | cb71f53e8cea4802509f182fa5bead0ac6ab0e7f | int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) {
int db_index;
if(zDb == NULL){
return 0;
}
for(db_index = 0; db_index < db->nDb; db_index++) {
struct Db *pDb = &db->aDb[db_index];
if(strcmp(pDb->zDbSName, zDb) == 0) {
return db_index;
}
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,529 |
Chrome | 80742f2ffeb9e90cd85cbee27acb9f924ffebd16 | bool AutofillDownloadManager::StartUploadRequest(
const FormStructure& form,
bool form_was_autofilled,
const FieldTypeSet& available_field_types) {
if (next_upload_request_ > base::Time::Now()) {
VLOG(1) << "AutofillDownloadManager: Upload request is throttled.";
return false;
}
double upload_rate = form_was_autofilled ? GetPositiveUploadRate() :
GetNegativeUploadRate();
if (base::RandDouble() > upload_rate) {
VLOG(1) << "AutofillDownloadManager: Upload request is ignored.";
return false;
}
std::string form_xml;
if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled,
&form_xml))
return false;
FormRequestData request_data;
request_data.form_signatures.push_back(form.FormSignature());
request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD;
return StartRequest(form_xml, request_data);
}
| 1 | CVE-2011-2797 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 3,623 |
php-src | 426aeb2808955ee3d3f52e0cfb102834cdb836a5?w=1 | static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,407 |
pure-ftpd | 65c4d4ad331e94661de763e9b5304d28698999c4 | int sfgets(void)
{
struct pollfd pfd;
int pollret;
ssize_t readnb;
signed char seen_r = 0;
static size_t scanned;
static size_t readnbd;
if (scanned > (size_t) 0U) { /* support pipelining */
readnbd -= scanned;
memmove(cmd, cmd + scanned, readnbd); /* safe */
scanned = (size_t) 0U;
}
pfd.fd = clientfd;
#ifdef __APPLE_CC__
pfd.events = POLLIN | POLLERR | POLLHUP;
#else
pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP;
#endif
while (scanned < cmdsize) {
if (scanned >= readnbd) { /* nothing left in the buffer */
pfd.revents = 0;
while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 &&
errno == EINTR);
if (pollret == 0) {
return -1;
}
if (pollret <= 0 ||
(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
return -2;
}
if ((pfd.revents & (POLLIN | POLLPRI)) == 0) {
continue;
}
if (readnbd >= cmdsize) {
break;
}
#ifdef WITH_TLS
if (tls_cnx != NULL) {
while ((readnb = SSL_read
(tls_cnx, cmd + readnbd, cmdsize - readnbd))
< (ssize_t) 0 && errno == EINTR);
} else
#endif
{
while ((readnb = read(clientfd, cmd + readnbd,
cmdsize - readnbd)) < (ssize_t) 0 &&
errno == EINTR);
}
if (readnb <= (ssize_t) 0) {
return -2;
}
readnbd += readnb;
if (readnbd > cmdsize) {
return -2;
}
}
#ifdef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
if (cmd[scanned] == '\n') {
#ifndef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
cmd[scanned - 1U] = 0;
#ifndef RFC_CONFORMANT_LINES
} else {
cmd[scanned] = 0;
}
#endif
if (++scanned >= readnbd) { /* non-pipelined command */
scanned = readnbd = (size_t) 0U;
}
return 0;
}
seen_r = 0;
#ifdef RFC_CONFORMANT_LINES
}
#endif
if (ISCTRLCODE(cmd[scanned])) {
if (cmd[scanned] == '\r') {
seen_r = 1;
}
#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */
else if (cmd[scanned] == 0) {
cmd[scanned] = '\n';
}
#else
/* replace control chars with _ */
cmd[scanned] = '_';
#endif
}
scanned++;
}
die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */
return 0; /* to please GCC */
}
| 1 | CVE-2011-1575 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 5,886 |
yara | 3119b232c9c453c98d8fa8b6ae4e37ba18117cd4 | YYSTYPE * re_yyget_lval (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yylval;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,616 |
tensorflow | eccb7ec454e6617738554a255d77f08e60ee0808 | void operator()(const CPUDevice& d, typename TTypes<T>::ConstVec input,
const bool signed_input, const int num_bits,
const bool range_given, Tensor* input_min_tensor,
Tensor* input_max_tensor, QuantizerRoundMode round_mode,
bool narrow_range, typename TTypes<T>::Vec out) {
QuantizeAndDequantizeOneScaleImpl<CPUDevice, T>::Compute(
d, input, signed_input, num_bits, range_given, input_min_tensor,
input_max_tensor, round_mode, narrow_range, out);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,543 |
Chrome | 29734f46c6dc9362783091180c2ee279ad53637f | void V4L2JpegEncodeAccelerator::EncodeTaskLegacy(
std::unique_ptr<JobRecord> job_record) {
DCHECK(encoder_task_runner_->BelongsToCurrentThread());
if (!job_record->output_shm.MapAt(job_record->output_offset,
job_record->output_shm.size())) {
VPLOGF(1) << "could not map I420 bitstream_buffer";
NotifyError(job_record->task_id, PLATFORM_FAILURE);
return;
}
if (job_record->exif_shm &&
!job_record->exif_shm->MapAt(job_record->exif_offset,
job_record->exif_shm->size())) {
VPLOGF(1) << "could not map exif bitstream_buffer";
NotifyError(job_record->task_id, PLATFORM_FAILURE);
return;
}
gfx::Size coded_size = job_record->input_frame->coded_size();
if (latest_input_buffer_coded_size_legacy_ != coded_size ||
latest_quality_legacy_ != job_record->quality) {
std::unique_ptr<EncodedInstance> encoded_device(new EncodedInstance(this));
VLOGF(1) << "Open Device for quality " << job_record->quality
<< ", width: " << coded_size.width()
<< ", height: " << coded_size.height();
if (!encoded_device->Initialize()) {
VLOGF(1) << "Failed to initialize device";
NotifyError(job_record->task_id, PLATFORM_FAILURE);
return;
}
if (!encoded_device->SetUpJpegParameters(job_record->quality, coded_size)) {
VLOGF(1) << "SetUpJpegParameters failed";
NotifyError(job_record->task_id, PLATFORM_FAILURE);
return;
}
if (!encoded_device->CreateBuffers(coded_size,
job_record->output_shm.size())) {
VLOGF(1) << "Create buffers failed.";
NotifyError(job_record->task_id, PLATFORM_FAILURE);
return;
}
latest_input_buffer_coded_size_legacy_ = coded_size;
latest_quality_legacy_ = job_record->quality;
encoded_instances_.push(std::move(encoded_device));
}
encoded_instances_.back()->input_job_queue_.push(std::move(job_record));
ServiceDeviceTaskLegacy();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,227 |
Chrome | 870f3e99a1282023753fe8d8aed90879cbc6838f | void TraceEvent::Reset() {
duration_ = TimeDelta::FromInternalValue(-1);
parameter_copy_storage_ = NULL;
for (int i = 0; i < kTraceMaxNumArgs; ++i)
convertable_values_[i] = NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,734 |
linux | fa8b18edd752a8b4e9d1ee2cd615b82c93cf8bba | xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
int count, i;
count = be32_to_cpu(aclp->acl_cnt);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
| 1 | CVE-2012-0038 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 729 |
php-src | 91aa340180eccfc15d4a143b54d47b8120f898be | string_modifier_check(struct magic_set *ms, struct magic *m)
{
if ((ms->flags & MAGIC_CHECK) == 0)
return 0;
if (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0) {
file_magwarn(ms,
"'/BHhLl' modifiers are only allowed for pascal strings\n");
return -1;
}
switch (m->type) {
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->str_flags != 0) {
file_magwarn(ms,
"no modifiers allowed for 16-bit strings\n");
return -1;
}
break;
case FILE_STRING:
case FILE_PSTRING:
if ((m->str_flags & REGEX_OFFSET_START) != 0) {
file_magwarn(ms,
"'/%c' only allowed on regex and search\n",
CHAR_REGEX_OFFSET_START);
return -1;
}
break;
case FILE_SEARCH:
if (m->str_range == 0) {
file_magwarn(ms,
"missing range; defaulting to %d\n",
STRING_DEFAULT_RANGE);
m->str_range = STRING_DEFAULT_RANGE;
return -1;
}
break;
case FILE_REGEX:
if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_WHITESPACE);
return -1;
}
if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_OPTIONAL_WHITESPACE);
return -1;
}
break;
default:
file_magwarn(ms, "coding error: m->type=%d\n",
m->type);
return -1;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,350 |
httpd | fa7b2a5250e54363b3a6c8ac3aaa7de4e8da9b2e | AP_DECLARE(void) ap_increment_counts(ap_sb_handle_t *sb, request_rec *r)
{
worker_score *ws;
apr_off_t bytes;
if (!sb)
return;
ws = &ap_scoreboard_image->servers[sb->child_num][sb->thread_num];
if (pfn_ap_logio_get_last_bytes != NULL) {
bytes = pfn_ap_logio_get_last_bytes(r->connection);
}
else if (r->method_number == M_GET && r->method[0] == 'H') {
bytes = 0;
}
else {
bytes = r->bytes_sent;
}
#ifdef HAVE_TIMES
times(&ws->times);
#endif
ws->access_count++;
ws->my_access_count++;
ws->conn_count++;
ws->bytes_served += bytes;
ws->my_bytes_served += bytes;
ws->conn_bytes += bytes;
} | 1 | CVE-2021-34798 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 6,895 |
Chrome | 9fe6e9f89a1c78b8b38e806d35651a15858b053b | void ParamTraits<SkBitmap>::Write(base::Pickle* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.computeByteSize();
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
| 1 | CVE-2018-6067 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 9,141 |
libarchive | fd7e0c02e272913a0a8b6d492c7260dfca0b1408 | header_bin_be(struct archive_read *a, struct cpio *cpio,
struct archive_entry *entry, size_t *namelength, size_t *name_pad)
{
const void *h;
const unsigned char *header;
a->archive.archive_format = ARCHIVE_FORMAT_CPIO_BIN_BE;
a->archive.archive_format_name = "cpio (big-endian binary)";
/* Read fixed-size portion of header. */
h = __archive_read_ahead(a, bin_header_size, NULL);
if (h == NULL) {
archive_set_error(&a->archive, 0,
"End of file trying to read next cpio header");
return (ARCHIVE_FATAL);
}
/* Parse out binary fields. */
header = (const unsigned char *)h;
archive_entry_set_dev(entry, header[bin_dev_offset] * 256 + header[bin_dev_offset + 1]);
archive_entry_set_ino(entry, header[bin_ino_offset] * 256 + header[bin_ino_offset + 1]);
archive_entry_set_mode(entry, header[bin_mode_offset] * 256 + header[bin_mode_offset + 1]);
archive_entry_set_uid(entry, header[bin_uid_offset] * 256 + header[bin_uid_offset + 1]);
archive_entry_set_gid(entry, header[bin_gid_offset] * 256 + header[bin_gid_offset + 1]);
archive_entry_set_nlink(entry, header[bin_nlink_offset] * 256 + header[bin_nlink_offset + 1]);
archive_entry_set_rdev(entry, header[bin_rdev_offset] * 256 + header[bin_rdev_offset + 1]);
archive_entry_set_mtime(entry, be4(header + bin_mtime_offset), 0);
*namelength = header[bin_namesize_offset] * 256 + header[bin_namesize_offset + 1];
*name_pad = *namelength & 1; /* Pad to even. */
cpio->entry_bytes_remaining = be4(header + bin_filesize_offset);
archive_entry_set_size(entry, cpio->entry_bytes_remaining);
cpio->entry_padding = cpio->entry_bytes_remaining & 1; /* Pad to even. */
__archive_read_consume(a, bin_header_size);
return (ARCHIVE_OK);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,252 |
linux | 45e093ae2830cd1264677d47ff9a95a71f5d9f9c | static void tipc_sk_timeout(unsigned long data)
{
struct tipc_sock *tsk = (struct tipc_sock *)data;
struct sock *sk = &tsk->sk;
struct sk_buff *skb = NULL;
u32 peer_port, peer_node;
u32 own_node = tsk_own_node(tsk);
bh_lock_sock(sk);
if (!tsk->connected) {
bh_unlock_sock(sk);
goto exit;
}
peer_port = tsk_peer_port(tsk);
peer_node = tsk_peer_node(tsk);
if (tsk->probing_state == TIPC_CONN_PROBING) {
if (!sock_owned_by_user(sk)) {
sk->sk_socket->state = SS_DISCONNECTING;
tsk->connected = 0;
tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
tsk_peer_port(tsk));
sk->sk_state_change(sk);
} else {
/* Try again later */
sk_reset_timer(sk, &sk->sk_timer, (HZ / 20));
}
} else {
skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE,
INT_H_SIZE, 0, peer_node, own_node,
peer_port, tsk->portid, TIPC_OK);
tsk->probing_state = TIPC_CONN_PROBING;
sk_reset_timer(sk, &sk->sk_timer, jiffies + tsk->probing_intv);
}
bh_unlock_sock(sk);
if (skb)
tipc_node_xmit_skb(sock_net(sk), skb, peer_node, tsk->portid);
exit:
sock_put(sk);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,845 |
tcpdump | d515b4b4a300479cdf1a6e0d1bb95bc1f9fee514 | decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
| 1 | CVE-2017-13043 | 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,003 |
Chrome | 0c45ffd2a1b2b6b91aaaac989ad10a76765083c6 | bool CSSStyleSheet::SheetLoaded() {
DCHECK(owner_node_);
SetLoadCompleted(owner_node_->SheetLoaded());
return load_completed_;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,682 |
Chrome | 58c433b2426f8d23ad27f1976635506ee3643034 | QuicConnectionHelperTest()
: framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)),
creator_(guid_, &framer_),
net_log_(BoundNetLog()),
scheduler_(new MockScheduler()),
socket_(&empty_data_, net_log_.net_log()),
runner_(new TestTaskRunner(&clock_)),
helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)),
connection_(guid_, IPEndPoint(), helper_),
frame1_(1, false, 0, data1) {
connection_.set_visitor(&visitor_);
connection_.SetScheduler(scheduler_);
}
| 1 | CVE-2013-0896 | 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). | 450 |
pjproject | 856f87c2e97a27b256482dbe0d748b1194355a21 | PJ_DEF(int) pj_xml_print(const pj_xml_node *node, char *buf, pj_size_t len,
pj_bool_t include_prolog)
{
int prolog_len = 0;
int printed;
if (!node || !buf || !len)
return 0;
if (include_prolog) {
pj_str_t prolog = {"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", 39};
if ((int)len < prolog.slen)
return -1;
pj_memcpy(buf, prolog.ptr, prolog.slen);
prolog_len = (int)prolog.slen;
}
printed = xml_print_node(node, 0, buf+prolog_len, len-prolog_len) + prolog_len;
if (printed > 0 && len-printed >= 1) {
buf[printed++] = '\n';
}
return printed;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,016 |
linux | ea702b80e0bbb2448e201472127288beb82ca2fe | smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst)
{
int rc;
struct kvec *iov = rqst->rq_iov;
int n_vec = rqst->rq_nvec;
unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
unsigned int i;
size_t total_len = 0, sent;
struct socket *ssocket = server->ssocket;
int val = 1;
cFYI(1, "Sending smb: smb_len=%u", smb_buf_length);
dump_smb(iov[0].iov_base, iov[0].iov_len);
/* cork the socket */
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
rc = smb_send_kvec(server, iov, n_vec, &sent);
if (rc < 0)
goto uncork;
total_len += sent;
/* now walk the page array and send each page in it */
for (i = 0; i < rqst->rq_npages; i++) {
struct kvec p_iov;
cifs_rqst_page_to_kvec(rqst, i, &p_iov);
rc = smb_send_kvec(server, &p_iov, 1, &sent);
kunmap(rqst->rq_pages[i]);
if (rc < 0)
break;
total_len += sent;
}
uncork:
/* uncork it */
val = 0;
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
cFYI(1, "partial send (wanted=%u sent=%zu): terminating "
"session", smb_buf_length + 4, total_len);
/*
* If we have only sent part of an SMB then the next SMB could
* be taken as the remainder of this one. We need to kill the
* socket so the server throws away the partial SMB
*/
server->tcpStatus = CifsNeedReconnect;
}
if (rc < 0 && rc != -EINTR)
cERROR(1, "Error %d sending data on socket to server", rc);
else
rc = 0;
return rc;
}
| 1 | CVE-2013-3302 | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently. | Phase: Architecture and Design
In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.
Phase: Architecture and Design
Use thread-safe capabilities such as the data access abstraction in Spring.
Phase: Architecture and Design
Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring.
Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).
Phase: Implementation
When using multithreading and operating on shared variables, only use thread-safe functions.
Phase: Implementation
Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.
Phase: Implementation
Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.
Phase: Implementation
Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.
Phase: Implementation
Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.
Phase: Implementation
Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help.
Phases: Architecture and Design; Operation
Strategy: Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations | 8,824 |
openssl | 21c856b75d81eff61aa63b4f036bb64a85bf6d46 | int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *point)
{
if (group->meth->is_at_infinity == 0) {
ECerr(EC_F_EC_POINT_IS_AT_INFINITY,
ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (group->meth != point->meth) {
ECerr(EC_F_EC_POINT_IS_AT_INFINITY, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return group->meth->is_at_infinity(group, point);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,266 |
samba | 9280051bfba337458722fb157f3082f93cbd9f2b | static void reply_sesssetup_and_X_spnego(struct smb_request *req)
{
const uint8 *p;
DATA_BLOB blob1;
size_t bufrem;
char *tmp;
const char *native_os;
const char *native_lanman;
const char *primary_domain;
const char *p2;
uint16 data_blob_len = SVAL(req->vwv+7, 0);
enum remote_arch_types ra_type = get_remote_arch();
int vuid = req->vuid;
user_struct *vuser = NULL;
NTSTATUS status = NT_STATUS_OK;
uint16 smbpid = req->smbpid;
struct smbd_server_connection *sconn = smbd_server_conn;
DEBUG(3,("Doing spnego session setup\n"));
if (global_client_caps == 0) {
global_client_caps = IVAL(req->vwv+10, 0);
if (!(global_client_caps & CAP_STATUS32)) {
remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES);
}
}
p = req->buf;
if (data_blob_len == 0) {
/* an invalid request */
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
return;
}
bufrem = smbreq_bufrem(req, p);
/* pull the spnego blob */
blob1 = data_blob(p, MIN(bufrem, data_blob_len));
#if 0
file_save("negotiate.dat", blob1.data, blob1.length);
#endif
p2 = (char *)req->buf + data_blob_len;
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_os = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_lanman = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
primary_domain = tmp ? tmp : "";
DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n",
native_os, native_lanman, primary_domain));
if ( ra_type == RA_WIN2K ) {
/* Vista sets neither the OS or lanman strings */
if ( !strlen(native_os) && !strlen(native_lanman) )
set_remote_arch(RA_VISTA);
/* Windows 2003 doesn't set the native lanman string,
but does set primary domain which is a bug I think */
if ( !strlen(native_lanman) ) {
ra_lanman_string( primary_domain );
} else {
ra_lanman_string( native_lanman );
}
}
/* Did we get a valid vuid ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, then try and see if this is an intermediate sessionsetup
* for a large SPNEGO packet. */
struct pending_auth_data *pad;
pad = get_pending_auth_data(sconn, smbpid);
if (pad) {
DEBUG(10,("reply_sesssetup_and_X_spnego: found "
"pending vuid %u\n",
(unsigned int)pad->vuid ));
vuid = pad->vuid;
}
}
/* Do we have a valid vuid now ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, start a new authentication setup. */
vuid = register_initial_vuid(sconn);
if (vuid == UID_FIELD_INVALID) {
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(
NT_STATUS_INVALID_PARAMETER));
return;
}
}
vuser = get_partial_auth_user_struct(sconn, vuid);
/* This MUST be valid. */
if (!vuser) {
smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
}
/* Large (greater than 4k) SPNEGO blobs are split into multiple
* sessionsetup requests as the Windows limit on the security blob
* field is 4k. Bug #4400. JRA.
*/
status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
if (!NT_STATUS_IS_OK(status)) {
if (!NT_STATUS_EQUAL(status,
NT_STATUS_MORE_PROCESSING_REQUIRED)) {
/* Real error - kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
}
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
if (blob1.data[0] == ASN1_APPLICATION(0)) {
/* its a negTokenTarg packet */
reply_spnego_negotiate(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (blob1.data[0] == ASN1_CONTEXT(1)) {
/* its a auth packet */
reply_spnego_auth(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) {
DATA_BLOB chal;
if (!vuser->auth_ntlmssp_state) {
status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
if (!NT_STATUS_IS_OK(status)) {
/* Kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
}
status = auth_ntlmssp_update(vuser->auth_ntlmssp_state,
blob1, &chal);
data_blob_free(&blob1);
reply_spnego_ntlmssp(req, vuid,
&vuser->auth_ntlmssp_state,
&chal, status, OID_NTLMSSP, false);
data_blob_free(&chal);
return;
}
/* what sort of packet is this? */
DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n"));
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
}
| 1 | CVE-2010-1642 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,907 |
linux | a5ec6ae161d72f01411169a938fa5f8baea16e8f | 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);
return -EACCES;
}
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;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,652 |
linux | f85daf0e725358be78dfd208dea5fd665d8cb901 | static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
{
const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
struct dst_ops *dst_ops;
struct xfrm_dst *xdst;
if (!afinfo)
return ERR_PTR(-EINVAL);
switch (family) {
case AF_INET:
dst_ops = &net->xfrm.xfrm4_dst_ops;
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
dst_ops = &net->xfrm.xfrm6_dst_ops;
break;
#endif
default:
BUG();
}
xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
if (likely(xdst)) {
memset_after(xdst, 0, u.dst);
} else
xdst = ERR_PTR(-ENOBUFS);
rcu_read_unlock();
return xdst;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,881 |
linux | a1616a5ac99ede5d605047a9012481ce7ff18b16 | static int hidp_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
void __user *argp = compat_ptr(arg);
int err;
if (cmd == HIDPGETCONNLIST) {
struct hidp_connlist_req cl;
u32 __user *p = argp;
u32 uci;
if (get_user(cl.cnum, p) || get_user(uci, p + 1))
return -EFAULT;
cl.ci = compat_ptr(uci);
if (cl.cnum <= 0)
return -EINVAL;
err = hidp_get_connlist(&cl);
if (!err && put_user(cl.cnum, p))
err = -EFAULT;
return err;
} else if (cmd == HIDPCONNADD) {
struct compat_hidp_connadd_req ca32;
struct hidp_connadd_req ca;
struct socket *csock;
struct socket *isock;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ca32, (void __user *) arg, sizeof(ca32)))
return -EFAULT;
ca.ctrl_sock = ca32.ctrl_sock;
ca.intr_sock = ca32.intr_sock;
ca.parser = ca32.parser;
ca.rd_size = ca32.rd_size;
ca.rd_data = compat_ptr(ca32.rd_data);
ca.country = ca32.country;
ca.subclass = ca32.subclass;
ca.vendor = ca32.vendor;
ca.product = ca32.product;
ca.version = ca32.version;
ca.flags = ca32.flags;
ca.idle_to = ca32.idle_to;
memcpy(ca.name, ca32.name, 128);
csock = sockfd_lookup(ca.ctrl_sock, &err);
if (!csock)
return err;
isock = sockfd_lookup(ca.intr_sock, &err);
if (!isock) {
sockfd_put(csock);
return err;
}
err = hidp_connection_add(&ca, csock, isock);
if (!err && copy_to_user(argp, &ca32, sizeof(ca32)))
err = -EFAULT;
sockfd_put(csock);
sockfd_put(isock);
return err;
}
return hidp_sock_ioctl(sock, cmd, arg);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,548 |
ImageMagick | a6240a163cb787909703d9fc649cf861f60ddd7c | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
}
clone_info=DestroyImageInfo(clone_info);
RelinquishMagickMemory(BImgBuff);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,090 |
libtiff | be4c85b16e8801a16eec25e80eb9f3dd6a96731b | _TIFFprintAscii(FILE* fd, const char* cp)
{
_TIFFprintAsciiBounded( fd, cp, strlen(cp));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,207 |
libxml2 | 0bcd05c5cd83dec3406c8f68b769b1d610c72f76 | xmlNextChar(xmlParserCtxtPtr ctxt)
{
if ((ctxt == NULL) || (ctxt->instate == XML_PARSER_EOF) ||
(ctxt->input == NULL))
return;
if (ctxt->charset == XML_CHAR_ENCODING_UTF8) {
if ((*ctxt->input->cur == 0) &&
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0) &&
(ctxt->instate != XML_PARSER_COMMENT)) {
/*
* If we are at the end of the current entity and
* the context allows it, we pop consumed entities
* automatically.
* the auto closing should be blocked in other cases
*/
xmlPopInput(ctxt);
} else {
const unsigned char *cur;
unsigned char c;
/*
* 2.11 End-of-Line Handling
* the literal two-character sequence "#xD#xA" or a standalone
* literal #xD, an XML processor must pass to the application
* the single character #xA.
*/
if (*(ctxt->input->cur) == '\n') {
ctxt->input->line++; ctxt->input->col = 1;
} else
ctxt->input->col++;
/*
* We are supposed to handle UTF8, check it's valid
* From rfc2044: encoding of the Unicode values on UTF-8:
*
* UCS-4 range (hex.) UTF-8 octet sequence (binary)
* 0000 0000-0000 007F 0xxxxxxx
* 0000 0080-0000 07FF 110xxxxx 10xxxxxx
* 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
*
* Check for the 0x110000 limit too
*/
cur = ctxt->input->cur;
c = *cur;
if (c & 0x80) {
if (c == 0xC0)
goto encoding_error;
if (cur[1] == 0) {
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
if ((cur[1] & 0xc0) != 0x80)
goto encoding_error;
if ((c & 0xe0) == 0xe0) {
unsigned int val;
if (cur[2] == 0) {
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
if ((cur[2] & 0xc0) != 0x80)
goto encoding_error;
if ((c & 0xf0) == 0xf0) {
if (cur[3] == 0) {
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
if (((c & 0xf8) != 0xf0) ||
((cur[3] & 0xc0) != 0x80))
goto encoding_error;
/* 4-byte code */
ctxt->input->cur += 4;
val = (cur[0] & 0x7) << 18;
val |= (cur[1] & 0x3f) << 12;
val |= (cur[2] & 0x3f) << 6;
val |= cur[3] & 0x3f;
} else {
/* 3-byte code */
ctxt->input->cur += 3;
val = (cur[0] & 0xf) << 12;
val |= (cur[1] & 0x3f) << 6;
val |= cur[2] & 0x3f;
}
if (((val > 0xd7ff) && (val < 0xe000)) ||
((val > 0xfffd) && (val < 0x10000)) ||
(val >= 0x110000)) {
xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
"Char 0x%X out of allowed range\n",
val);
}
} else
/* 2-byte code */
ctxt->input->cur += 2;
} else
/* 1-byte code */
ctxt->input->cur++;
ctxt->nbChars++;
if (*ctxt->input->cur == 0)
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
}
} else {
/*
* Assume it's a fixed length encoding (1) with
* a compatible encoding for the ASCII set, since
* XML constructs only use < 128 chars
*/
if (*(ctxt->input->cur) == '\n') {
ctxt->input->line++; ctxt->input->col = 1;
} else
ctxt->input->col++;
ctxt->input->cur++;
ctxt->nbChars++;
if (*ctxt->input->cur == 0)
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
}
if ((*ctxt->input->cur == '%') && (!ctxt->html))
xmlParserHandlePEReference(ctxt);
if ((*ctxt->input->cur == 0) &&
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
xmlPopInput(ctxt);
return;
encoding_error:
/*
* If we detect an UTF8 error that probably mean that the
* input encoding didn't get properly advertised in the
* declaration header. Report the error and switch the encoding
* to ISO-Latin-1 (if you don't like this policy, just declare the
* encoding !)
*/
if ((ctxt == NULL) || (ctxt->input == NULL) ||
(ctxt->input->end - ctxt->input->cur < 4)) {
__xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
"Input is not proper UTF-8, indicate encoding !\n",
NULL, NULL);
} else {
char buffer[150];
snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
ctxt->input->cur[0], ctxt->input->cur[1],
ctxt->input->cur[2], ctxt->input->cur[3]);
__xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
"Input is not proper UTF-8, indicate encoding !\n%s",
BAD_CAST buffer, NULL);
}
ctxt->charset = XML_CHAR_ENCODING_8859_1;
ctxt->input->cur++;
return;
} | 1 | CVE-2016-1833 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 3,909 |
Chrome | ab5e55ff333def909d025ac45da9ffa0d88a63f2 | PassRefPtr<RTCSessionDescription> RTCPeerConnection::localDescription(ExceptionCode& ec)
{
if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) {
ec = INVALID_STATE_ERR;
return 0;
}
RefPtr<RTCSessionDescriptionDescriptor> descriptor = m_peerHandler->localDescription();
if (!descriptor)
return 0;
RefPtr<RTCSessionDescription> desc = RTCSessionDescription::create(descriptor.release());
return desc.release();
}
| 1 | CVE-2011-2875 | 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. | 5,690 |
Chrome | 87a082c5137a63dedb3fe5b1f48f75dcd1fd780c | void Layer::ClearRenderSurface() {
draw_properties_.render_surface.reset();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,669 |
linux | 5d2e73a5f80a5b5aff3caf1ec6d39b5b3f54b26e | static int zr364xx_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct zr364xx_camera *cam =
container_of(ctrl->handler, struct zr364xx_camera, ctrl_handler);
int temp;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
/* hardware brightness */
send_control_msg(cam->udev, 1, 0x2001, 0, NULL, 0);
temp = (0x60 << 8) + 127 - ctrl->val;
send_control_msg(cam->udev, 1, temp, 0, NULL, 0);
break;
default:
return -EINVAL;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,048 |
linux | 4683f42fde3977bdb4e8a09622788cc8b5313778 | static void *bt_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct bt_seq_state *s = seq->private;
struct bt_sock_list *l = s->l;
return seq_hlist_next(v, &l->head, pos);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,138 |
mbedtls | 5224a7544c95552553e2e6be0b4a789956a6464e | static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) > end - len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,197 |
Chrome | a4150b688a754d3d10d2ca385155b1c95d77d6ae | void GLES2DecoderPassthroughImpl::ProcessPendingQueries(bool did_finish) {
ProcessQueries(did_finish);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,145 |
Espruino | ce1924193862d58cb43d3d4d9dada710a8361b89 | JsVar *jsvAsArrayIndexAndUnLock(JsVar *a) {
JsVar *b = jsvAsArrayIndex(a);
jsvUnLock(a);
return b;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,364 |
qemu | 7285477ab11831b1cf56e45878a89170dd06d9b9 | static void scsi_free_request(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
qemu_vfree(r->iov.iov_base);
}
| 1 | CVE-2011-3346 | 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). | 867 |
Chrome | 116d0963cadfbf55ef2ec3d13781987c4d80517a | void ChromeMockRenderThread::OnGetDefaultPrintSettings(
PrintMsg_Print_Params* params) {
if (printer_.get())
printer_->GetDefaultPrintSettings(params);
}
| 1 | CVE-2012-2891 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 6,425 |
Android | ffab15eb80630dc799eb410855c93525b75233c3 | WORD32 impeg2d_get_slice_pos(dec_state_multi_core_t *ps_dec_state_multi_core)
{
WORD32 u4_bits;
WORD32 i4_row;
dec_state_t *ps_dec = ps_dec_state_multi_core->ps_dec_state[0];
WORD32 i4_prev_row;
stream_t s_bitstrm;
WORD32 i4_start_row;
WORD32 i4_slice_bistream_ofst;
WORD32 i;
s_bitstrm = ps_dec->s_bit_stream;
i4_prev_row = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_start_mb_y = 0;
ps_dec_state_multi_core->ps_dec_state[1]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_end_mb_y = ps_dec->u2_num_vert_mb;
ps_dec_state_multi_core->ps_dec_state[1]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_end_mb_y = -1;
if(ps_dec->i4_num_cores == 1)
return 0;
/* Reset the jobq to start of the jobq buffer */
impeg2_jobq_reset((jobq_t *)ps_dec->pv_jobq);
i4_start_row = -1;
i4_slice_bistream_ofst = 0;
while(1)
{
WORD32 i4_is_slice;
if(s_bitstrm.u4_offset + START_CODE_LEN >= s_bitstrm.u4_max_offset)
{
break;
}
u4_bits = impeg2d_bit_stream_nxt(&s_bitstrm,START_CODE_LEN);
i4_row = u4_bits & 0xFF;
/* Detect end of frame */
i4_is_slice = (((u4_bits >> 8) == 0x01) && (i4_row) && (i4_row <= ps_dec->u2_num_vert_mb));
if(!i4_is_slice)
break;
i4_row -= 1;
if(i4_prev_row != i4_row)
{
/* Create a job for previous slice row */
if(i4_start_row != -1)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = i4_row;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
/* Store current slice's bitstream offset */
i4_slice_bistream_ofst = s_bitstrm.u4_offset >> 3;
i4_slice_bistream_ofst -= (size_t)s_bitstrm.pv_bs_buf & 3;
i4_prev_row = i4_row;
/* Store current slice's row position */
i4_start_row = i4_row;
}
impeg2d_bit_stream_flush(&s_bitstrm, START_CODE_LEN);
/* Flush the bytes till a start code is encountered */
while(impeg2d_bit_stream_nxt(&s_bitstrm, 24) != START_CODE_PREFIX)
{
impeg2d_bit_stream_get(&s_bitstrm, 8);
if(s_bitstrm.u4_offset >= s_bitstrm.u4_max_offset)
{
break;
}
}
}
/* Create job for the last slice row */
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = ps_dec->u2_num_vert_mb;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
e_ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(e_ret != IV_SUCCESS)
return e_ret;
}
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
{
for(i = 0; i < ps_dec->u2_vertical_size; i+=64)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i;
s_job.i2_start_mb_y >>= 4;
s_job.i2_end_mb_y = (i + 64);
s_job.i2_end_mb_y >>= 4;
s_job.i4_cmd = CMD_FMTCONV;
s_job.i4_bistream_ofst = 0;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
}
impeg2_jobq_terminate(ps_dec->pv_jobq);
ps_dec->i4_bytes_consumed = s_bitstrm.u4_offset >> 3;
ps_dec->i4_bytes_consumed -= ((size_t)s_bitstrm.pv_bs_buf & 3);
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,398 |
claws | d390fa07f5548f3173dd9cc13b233db5ce934c82 | static gint conv_sjistoeuc(gchar *outbuf, gint outlen, const gchar *inbuf)
{
const guchar *in = inbuf;
guchar *out = outbuf;
while (*in != '\0') {
if (IS_ASCII(*in)) {
*out++ = *in++;
} else if (issjiskanji1(*in)) {
if (issjiskanji2(*(in + 1))) {
guchar out1 = *in;
guchar out2 = *(in + 1);
guchar row;
row = out1 < 0xa0 ? 0x70 : 0xb0;
if (out2 < 0x9f) {
out1 = (out1 - row) * 2 - 1;
out2 -= out2 > 0x7f ? 0x20 : 0x1f;
} else {
out1 = (out1 - row) * 2;
out2 -= 0x7e;
}
*out++ = out1 | 0x80;
*out++ = out2 | 0x80;
in += 2;
} else {
*out++ = SUBST_CHAR;
in++;
if (*in != '\0' && !IS_ASCII(*in)) {
*out++ = SUBST_CHAR;
in++;
}
}
} else if (issjishwkana(*in)) {
*out++ = 0x8e;
*out++ = *in++;
} else {
*out++ = SUBST_CHAR;
in++;
}
}
*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,426 |
ImageMagick | c0fe488e7052f68d4eb7768805a857ef6fef928d | static size_t PCLDeltaCompressImage(const size_t length,
const unsigned char *previous_pixels,const unsigned char *pixels,
unsigned char *compress_pixels)
{
int
delta,
j,
replacement;
register ssize_t
i,
x;
register unsigned char
*q;
q=compress_pixels;
for (x=0; x < (ssize_t) length; )
{
j=0;
for (i=0; x < (ssize_t) length; x++)
{
if (*pixels++ != *previous_pixels++)
{
i=1;
break;
}
j++;
}
while (x < (ssize_t) length)
{
x++;
if (*pixels == *previous_pixels)
break;
i++;
previous_pixels++;
pixels++;
}
if (i == 0)
break;
replacement=j >= 31 ? 31 : j;
j-=replacement;
delta=i >= 8 ? 8 : i;
*q++=(unsigned char) (((delta-1) << 5) | replacement);
if (replacement == 31)
{
for (replacement=255; j != 0; )
{
if (replacement > j)
replacement=j;
*q++=(unsigned char) replacement;
j-=replacement;
}
if (replacement == 255)
*q++='\0';
}
for (pixels-=i; i != 0; )
{
for (i-=delta; delta != 0; delta--)
*q++=(*pixels++);
if (i == 0)
break;
delta=i;
if (i >= 8)
delta=8;
*q++=(unsigned char) ((delta-1) << 5);
}
}
return((size_t) (q-compress_pixels));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,762 |
Chrome | 4026d85fcded8c4ee5113cb1bd1a7e8149e03827 | static int GetCSITransitionType(WebNavigationType nav_type) {
switch (nav_type) {
case blink::WebNavigationTypeLinkClicked:
case blink::WebNavigationTypeFormSubmitted:
case blink::WebNavigationTypeFormResubmitted:
return kTransitionLink;
case blink::WebNavigationTypeBackForward:
return kTransitionForwardBack;
case blink::WebNavigationTypeReload:
return kTransitionReload;
case blink::WebNavigationTypeOther:
return kTransitionOther;
}
return kTransitionOther;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,063 |
Chrome | 4d17163f4b66be517dc49019a029e5ddbd45078c | void CSSDefaultStyleSheets::loadSimpleDefaultStyle()
{
ASSERT(!defaultStyle);
ASSERT(!simpleDefaultStyleSheet);
defaultStyle = RuleSet::create().leakPtr();
defaultPrintStyle = defaultStyle;
defaultQuirksStyle = RuleSet::create().leakPtr();
simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval());
}
| 1 | CVE-2013-0828 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 1,314 |
tmux | 2ffbd5b5f05dded1564ba32a6a00b0b417439b2f | input_csi_dispatch_sm(struct input_ctx *ictx)
{
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
switch (input_get(ictx, i, 0, -1)) {
case 4: /* IRM */
screen_write_mode_set(&ictx->ctx, MODE_INSERT);
break;
case 34:
screen_write_mode_clear(&ictx->ctx, MODE_BLINKING);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,431 |
php-src | 08da7c73726f7b86b67d6f0ff87c73c585a7834a | static int firebird_handle_begin(pdo_dbh_t *dbh) /* {{{ */
{
pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
char tpb[8] = { isc_tpb_version3 }, *ptpb = tpb+1;
#if abies_0
if (dbh->transaction_flags & PDO_TRANS_ISOLATION_LEVEL) {
if (dbh->transaction_flags & PDO_TRANS_READ_UNCOMMITTED) {
/* this is a poor fit, but it's all we have */
*ptpb++ = isc_tpb_read_committed;
*ptpb++ = isc_tpb_rec_version;
dbh->transaction_flags &= ~(PDO_TRANS_ISOLATION_LEVEL^PDO_TRANS_READ_UNCOMMITTED);
} else if (dbh->transaction_flags & PDO_TRANS_READ_COMMITTED) {
*ptpb++ = isc_tpb_read_committed;
*ptpb++ = isc_tpb_no_rec_version;
dbh->transaction_flags &= ~(PDO_TRANS_ISOLATION_LEVEL^PDO_TRANS_READ_COMMITTED);
} else if (dbh->transaction_flags & PDO_TRANS_REPEATABLE_READ) {
*ptpb++ = isc_tpb_concurrency;
dbh->transaction_flags &= ~(PDO_TRANS_ISOLATION_LEVEL^PDO_TRANS_REPEATABLE_READ);
} else {
*ptpb++ = isc_tpb_consistency;
dbh->transaction_flags &= ~(PDO_TRANS_ISOLATION_LEVEL^PDO_TRANS_SERIALIZABLE);
}
}
if (dbh->transaction_flags & PDO_TRANS_ACCESS_MODE) {
if (dbh->transaction_flags & PDO_TRANS_READONLY) {
*ptpb++ = isc_tpb_read;
dbh->transaction_flags &= ~(PDO_TRANS_ACCESS_MODE^PDO_TRANS_READONLY);
} else {
*ptpb++ = isc_tpb_write;
dbh->transaction_flags &= ~(PDO_TRANS_ACCESS_MODE^PDO_TRANS_READWRITE);
}
}
if (dbh->transaction_flags & PDO_TRANS_CONFLICT_RESOLUTION) {
if (dbh->transaction_flags & PDO_TRANS_RETRY) {
*ptpb++ = isc_tpb_wait;
dbh->transaction_flags &= ~(PDO_TRANS_CONFLICT_RESOLUTION^PDO_TRANS_RETRY);
} else {
*ptpb++ = isc_tpb_nowait;
dbh->transaction_flags &= ~(PDO_TRANS_CONFLICT_RESOLUTION^PDO_TRANS_ABORT);
}
}
#endif
if (isc_start_transaction(H->isc_status, &H->tr, 1, &H->db, (unsigned short)(ptpb-tpb), tpb)) {
RECORD_ERROR(dbh);
return 0;
}
return 1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,877 |
openldap | 4c774220a752bf8e3284984890dc0931fe73165d | do_modrdn(
Operation *op,
SlapReply *rs
)
{
struct berval dn = BER_BVNULL;
struct berval newrdn = BER_BVNULL;
struct berval newSuperior = BER_BVNULL;
ber_int_t deloldrdn;
struct berval pnewSuperior = BER_BVNULL;
struct berval nnewSuperior = BER_BVNULL;
ber_len_t length;
Debug( LDAP_DEBUG_TRACE, "%s do_modrdn\n",
op->o_log_prefix, 0, 0 );
/*
* Parse the modrdn request. It looks like this:
*
* ModifyRDNRequest := SEQUENCE {
* entry DistinguishedName,
* newrdn RelativeDistinguishedName
* deleteoldrdn BOOLEAN,
* newSuperior [0] LDAPDN OPTIONAL (v3 Only!)
* }
*/
if ( ber_scanf( op->o_ber, "{mmb", &dn, &newrdn, &deloldrdn )
== LBER_ERROR )
{
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: ber_scanf failed\n",
op->o_log_prefix, 0, 0 );
send_ldap_discon( op, rs, LDAP_PROTOCOL_ERROR, "decoding error" );
return SLAPD_DISCONNECT;
}
/* Check for newSuperior parameter, if present scan it */
if ( ber_peek_tag( op->o_ber, &length ) == LDAP_TAG_NEWSUPERIOR ) {
if ( op->o_protocol < LDAP_VERSION3 ) {
/* Connection record indicates v2 but field
* newSuperior is present: report error.
*/
Debug( LDAP_DEBUG_ANY,
"%s do_modrdn: newSuperior requires LDAPv3\n",
op->o_log_prefix, 0, 0 );
send_ldap_discon( op, rs,
LDAP_PROTOCOL_ERROR, "newSuperior requires LDAPv3" );
rs->sr_err = SLAPD_DISCONNECT;
goto cleanup;
}
if ( ber_scanf( op->o_ber, "m", &newSuperior )
== LBER_ERROR ) {
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: ber_scanf(\"m\") failed\n",
op->o_log_prefix, 0, 0 );
send_ldap_discon( op, rs,
LDAP_PROTOCOL_ERROR, "decoding error" );
rs->sr_err = SLAPD_DISCONNECT;
goto cleanup;
}
op->orr_newSup = &pnewSuperior;
op->orr_nnewSup = &nnewSuperior;
}
Debug( LDAP_DEBUG_ARGS,
"do_modrdn: dn (%s) newrdn (%s) newsuperior (%s)\n",
dn.bv_val, newrdn.bv_val,
newSuperior.bv_len ? newSuperior.bv_val : "" );
if ( ber_scanf( op->o_ber, /*{*/ "}") == LBER_ERROR ) {
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: ber_scanf failed\n",
op->o_log_prefix, 0, 0 );
send_ldap_discon( op, rs,
LDAP_PROTOCOL_ERROR, "decoding error" );
rs->sr_err = SLAPD_DISCONNECT;
goto cleanup;
}
if( get_ctrls( op, rs, 1 ) != LDAP_SUCCESS ) {
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: get_ctrls failed\n",
op->o_log_prefix, 0, 0 );
/* get_ctrls has sent results. Now clean up. */
goto cleanup;
}
rs->sr_err = dnPrettyNormal( NULL, &dn, &op->o_req_dn, &op->o_req_ndn, op->o_tmpmemctx );
if( rs->sr_err != LDAP_SUCCESS ) {
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: invalid dn (%s)\n",
op->o_log_prefix, dn.bv_val, 0 );
send_ldap_error( op, rs, LDAP_INVALID_DN_SYNTAX, "invalid DN" );
goto cleanup;
}
/* FIXME: should have/use rdnPretty / rdnNormalize routines */
rs->sr_err = dnPrettyNormal( NULL, &newrdn, &op->orr_newrdn, &op->orr_nnewrdn, op->o_tmpmemctx );
if( rs->sr_err != LDAP_SUCCESS ) {
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: invalid newrdn (%s)\n",
op->o_log_prefix, newrdn.bv_val, 0 );
send_ldap_error( op, rs, LDAP_INVALID_DN_SYNTAX, "invalid new RDN" );
goto cleanup;
}
if( rdn_validate( &op->orr_newrdn ) != LDAP_SUCCESS ) {
Debug( LDAP_DEBUG_ANY, "%s do_modrdn: invalid rdn (%s)\n",
op->o_log_prefix, op->orr_newrdn.bv_val, 0 );
send_ldap_error( op, rs, LDAP_INVALID_DN_SYNTAX, "invalid new RDN" );
goto cleanup;
}
if( op->orr_newSup ) {
rs->sr_err = dnPrettyNormal( NULL, &newSuperior, &pnewSuperior,
&nnewSuperior, op->o_tmpmemctx );
if( rs->sr_err != LDAP_SUCCESS ) {
Debug( LDAP_DEBUG_ANY,
"%s do_modrdn: invalid newSuperior (%s)\n",
op->o_log_prefix, newSuperior.bv_val, 0 );
send_ldap_error( op, rs, LDAP_INVALID_DN_SYNTAX, "invalid newSuperior" );
goto cleanup;
}
}
Statslog( LDAP_DEBUG_STATS, "%s MODRDN dn=\"%s\"\n",
op->o_log_prefix, op->o_req_dn.bv_val, 0, 0, 0 );
op->orr_deleteoldrdn = deloldrdn;
op->orr_modlist = NULL;
/* prepare modlist of modifications from old/new RDN */
rs->sr_err = slap_modrdn2mods( op, rs );
if ( rs->sr_err != LDAP_SUCCESS ) {
send_ldap_result( op, rs );
goto cleanup;
}
op->o_bd = frontendDB;
rs->sr_err = frontendDB->be_modrdn( op, rs );
#ifdef LDAP_X_TXN
if( rs->sr_err == LDAP_X_TXN_SPECIFY_OKAY ) {
/* skip cleanup */
}
#endif
cleanup:
op->o_tmpfree( op->o_req_dn.bv_val, op->o_tmpmemctx );
op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
if ( op->orr_modlist != NULL )
slap_mods_free( op->orr_modlist, 1 );
if ( !BER_BVISNULL( &pnewSuperior ) ) {
op->o_tmpfree( pnewSuperior.bv_val, op->o_tmpmemctx );
}
if ( !BER_BVISNULL( &nnewSuperior ) ) {
op->o_tmpfree( nnewSuperior.bv_val, op->o_tmpmemctx );
}
return rs->sr_err;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,502 |
linux | 592acbf16821288ecdc4192c47e3774a4c48bb64 | static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
{
ext4_fsblk_t block = ext4_ext_pblock(ext);
int len = ext4_ext_get_actual_len(ext);
ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
/*
* We allow neither:
* - zero length
* - overflow/wrap-around
*/
if (lblock + len <= lblock)
return 0;
return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,782 |
Android | f81038006b4c59a5a148dcad887371206033c28f | int64_t NuPlayer::GenericSource::getLastReadPosition() {
if (mAudioTrack.mSource != NULL) {
return mAudioTimeUs;
} else if (mVideoTrack.mSource != NULL) {
return mVideoTimeUs;
} else {
return 0;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,178 |
Android | 5e751957ba692658b7f67eb03ae5ddb2cd3d970c | status_t ESDS::parseESDescriptor(size_t offset, size_t size) {
if (size < 3) {
return ERROR_MALFORMED;
}
offset += 2; // skip ES_ID
size -= 2;
unsigned streamDependenceFlag = mData[offset] & 0x80;
unsigned URL_Flag = mData[offset] & 0x40;
unsigned OCRstreamFlag = mData[offset] & 0x20;
++offset;
--size;
if (streamDependenceFlag) {
offset += 2;
size -= 2;
}
if (URL_Flag) {
if (offset >= size) {
return ERROR_MALFORMED;
}
unsigned URLlength = mData[offset];
offset += URLlength + 1;
size -= URLlength + 1;
}
if (OCRstreamFlag) {
offset += 2;
size -= 2;
if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor)
&& offset - 2 < size
&& mData[offset - 2] == kTag_DecoderConfigDescriptor) {
offset -= 2;
size += 2;
ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id.");
}
}
if (offset >= size) {
return ERROR_MALFORMED;
}
uint8_t tag;
size_t sub_offset, sub_size;
status_t err = skipDescriptorHeader(
offset, size, &tag, &sub_offset, &sub_size);
if (err != OK) {
return err;
}
if (tag != kTag_DecoderConfigDescriptor) {
return ERROR_MALFORMED;
}
err = parseDecoderConfigDescriptor(sub_offset, sub_size);
return err;
}
| 1 | CVE-2015-1539 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 1,135 |
Android | cc274e2abe8b2a6698a5c47d8aa4bb45f1f9538d | ContentEncoding::ContentEncoding()
: compression_entries_(NULL),
compression_entries_end_(NULL),
encryption_entries_(NULL),
encryption_entries_end_(NULL),
encoding_order_(0),
encoding_scope_(1),
encoding_type_(0) {}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,396 |
linux | a8b0ca17b80e92faab46ee7179ba9e99ccb61233 | asmlinkage void __kprobes do_sparc64_fault(struct pt_regs *regs)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned int insn = 0;
int si_code, fault_code, fault;
unsigned long address, mm_rss;
fault_code = get_thread_fault_code();
if (notify_page_fault(regs))
return;
si_code = SEGV_MAPERR;
address = current_thread_info()->fault_address;
if ((fault_code & FAULT_CODE_ITLB) &&
(fault_code & FAULT_CODE_DTLB))
BUG();
if (test_thread_flag(TIF_32BIT)) {
if (!(regs->tstate & TSTATE_PRIV)) {
if (unlikely((regs->tpc >> 32) != 0)) {
bogus_32bit_fault_tpc(regs);
goto intr_or_no_mm;
}
}
if (unlikely((address >> 32) != 0)) {
bogus_32bit_fault_address(regs, address);
goto intr_or_no_mm;
}
}
if (regs->tstate & TSTATE_PRIV) {
unsigned long tpc = regs->tpc;
/* Sanity check the PC. */
if ((tpc >= KERNBASE && tpc < (unsigned long) __init_end) ||
(tpc >= MODULES_VADDR && tpc < MODULES_END)) {
/* Valid, no problems... */
} else {
bad_kernel_pc(regs, address);
return;
}
}
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto intr_or_no_mm;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
if (!down_read_trylock(&mm->mmap_sem)) {
if ((regs->tstate & TSTATE_PRIV) &&
!search_exception_tables(regs->tpc)) {
insn = get_fault_insn(regs, insn);
goto handle_kernel_fault;
}
down_read(&mm->mmap_sem);
}
vma = find_vma(mm, address);
if (!vma)
goto bad_area;
/* Pure DTLB misses do not tell us whether the fault causing
* load/store/atomic was a write or not, it only says that there
* was no match. So in such a case we (carefully) read the
* instruction to try and figure this out. It's an optimization
* so it's ok if we can't do this.
*
* Special hack, window spill/fill knows the exact fault type.
*/
if (((fault_code &
(FAULT_CODE_DTLB | FAULT_CODE_WRITE | FAULT_CODE_WINFIXUP)) == FAULT_CODE_DTLB) &&
(vma->vm_flags & VM_WRITE) != 0) {
insn = get_fault_insn(regs, 0);
if (!insn)
goto continue_fault;
/* All loads, stores and atomics have bits 30 and 31 both set
* in the instruction. Bit 21 is set in all stores, but we
* have to avoid prefetches which also have bit 21 set.
*/
if ((insn & 0xc0200000) == 0xc0200000 &&
(insn & 0x01780000) != 0x01680000) {
/* Don't bother updating thread struct value,
* because update_mmu_cache only cares which tlb
* the access came from.
*/
fault_code |= FAULT_CODE_WRITE;
}
}
continue_fault:
if (vma->vm_start <= address)
goto good_area;
if (!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
if (!(fault_code & FAULT_CODE_WRITE)) {
/* Non-faulting loads shouldn't expand stack. */
insn = get_fault_insn(regs, insn);
if ((insn & 0xc0800000) == 0xc0800000) {
unsigned char asi;
if (insn & 0x2000)
asi = (regs->tstate >> 24);
else
asi = (insn >> 5);
if ((asi & 0xf2) == 0x82)
goto bad_area;
}
}
if (expand_stack(vma, address))
goto bad_area;
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
si_code = SEGV_ACCERR;
/* If we took a ITLB miss on a non-executable page, catch
* that here.
*/
if ((fault_code & FAULT_CODE_ITLB) && !(vma->vm_flags & VM_EXEC)) {
BUG_ON(address != regs->tpc);
BUG_ON(regs->tstate & TSTATE_PRIV);
goto bad_area;
}
if (fault_code & FAULT_CODE_WRITE) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
/* Spitfire has an icache which does not snoop
* processor stores. Later processors do...
*/
if (tlb_type == spitfire &&
(vma->vm_flags & VM_EXEC) != 0 &&
vma->vm_file != NULL)
set_thread_fault_code(fault_code |
FAULT_CODE_BLKCOMMIT);
} else {
/* Allow reads even for write-only mappings */
if (!(vma->vm_flags & (VM_READ | VM_EXEC)))
goto bad_area;
}
fault = handle_mm_fault(mm, vma, address, (fault_code & FAULT_CODE_WRITE) ? FAULT_FLAG_WRITE : 0);
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (fault & VM_FAULT_MAJOR) {
current->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,
regs, address);
} else {
current->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,
regs, address);
}
up_read(&mm->mmap_sem);
mm_rss = get_mm_rss(mm);
#ifdef CONFIG_HUGETLB_PAGE
mm_rss -= (mm->context.huge_pte_count * (HPAGE_SIZE / PAGE_SIZE));
#endif
if (unlikely(mm_rss >
mm->context.tsb_block[MM_TSB_BASE].tsb_rss_limit))
tsb_grow(mm, MM_TSB_BASE, mm_rss);
#ifdef CONFIG_HUGETLB_PAGE
mm_rss = mm->context.huge_pte_count;
if (unlikely(mm_rss >
mm->context.tsb_block[MM_TSB_HUGE].tsb_rss_limit))
tsb_grow(mm, MM_TSB_HUGE, mm_rss);
#endif
return;
/*
* Something tried to access memory that isn't in our memory map..
* Fix it, but check if it's kernel or user first..
*/
bad_area:
insn = get_fault_insn(regs, insn);
up_read(&mm->mmap_sem);
handle_kernel_fault:
do_kernel_fault(regs, si_code, fault_code, insn, address);
return;
/*
* We ran out of memory, or some other thing happened to us that made
* us unable to handle the page fault gracefully.
*/
out_of_memory:
insn = get_fault_insn(regs, insn);
up_read(&mm->mmap_sem);
if (!(regs->tstate & TSTATE_PRIV)) {
pagefault_out_of_memory();
return;
}
goto handle_kernel_fault;
intr_or_no_mm:
insn = get_fault_insn(regs, 0);
goto handle_kernel_fault;
do_sigbus:
insn = get_fault_insn(regs, insn);
up_read(&mm->mmap_sem);
/*
* Send a sigbus, regardless of whether we were in kernel
* or user mode.
*/
do_fault_siginfo(BUS_ADRERR, SIGBUS, regs, insn, fault_code);
/* Kernel mode? Handle exceptions or die */
if (regs->tstate & TSTATE_PRIV)
goto handle_kernel_fault;
}
| 1 | CVE-2011-2918 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 763 |
vim | 5c68617d395f9d7b824f68475b24ce3e38d653a3 | spell_suggest(int count)
{
char_u *line;
pos_T prev_cursor = curwin->w_cursor;
char_u wcopy[MAXWLEN + 2];
char_u *p;
int i;
int c;
suginfo_T sug;
suggest_T *stp;
int mouse_used;
int need_cap;
int limit;
int selected = count;
int badlen = 0;
int msg_scroll_save = msg_scroll;
int wo_spell_save = curwin->w_p_spell;
if (!curwin->w_p_spell)
{
did_set_spelllang(curwin);
curwin->w_p_spell = TRUE;
}
if (*curwin->w_s->b_p_spl == NUL)
{
emsg(_(e_spell_checking_is_not_possible));
return;
}
if (VIsual_active)
{
// Use the Visually selected text as the bad word. But reject
// a multi-line selection.
if (curwin->w_cursor.lnum != VIsual.lnum)
{
vim_beep(BO_SPELL);
return;
}
badlen = (int)curwin->w_cursor.col - (int)VIsual.col;
if (badlen < 0)
badlen = -badlen;
else
curwin->w_cursor.col = VIsual.col;
++badlen;
end_visual_mode();
// make sure we don't include the NUL at the end of the line
line = ml_get_curline();
if (badlen > STRLEN(line) - curwin->w_cursor.col)
badlen = STRLEN(line) - curwin->w_cursor.col;
}
// Find the start of the badly spelled word.
else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0
|| curwin->w_cursor.col > prev_cursor.col)
{
// No bad word or it starts after the cursor: use the word under the
// cursor.
curwin->w_cursor = prev_cursor;
line = ml_get_curline();
p = line + curwin->w_cursor.col;
// Backup to before start of word.
while (p > line && spell_iswordp_nmw(p, curwin))
MB_PTR_BACK(line, p);
// Forward to start of word.
while (*p != NUL && !spell_iswordp_nmw(p, curwin))
MB_PTR_ADV(p);
if (!spell_iswordp_nmw(p, curwin)) // No word found.
{
beep_flush();
return;
}
curwin->w_cursor.col = (colnr_T)(p - line);
}
// Get the word and its length.
// Figure out if the word should be capitalised.
need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);
// Make a copy of current line since autocommands may free the line.
line = vim_strsave(ml_get_curline());
if (line == NULL)
goto skip;
// Get the list of suggestions. Limit to 'lines' - 2 or the number in
// 'spellsuggest', whatever is smaller.
if (sps_limit > (int)Rows - 2)
limit = (int)Rows - 2;
else
limit = sps_limit;
spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
TRUE, need_cap, TRUE);
if (sug.su_ga.ga_len == 0)
msg(_("Sorry, no suggestions"));
else if (count > 0)
{
if (count > sug.su_ga.ga_len)
smsg(_("Sorry, only %ld suggestions"), (long)sug.su_ga.ga_len);
}
else
{
#ifdef FEAT_RIGHTLEFT
// When 'rightleft' is set the list is drawn right-left.
cmdmsg_rl = curwin->w_p_rl;
if (cmdmsg_rl)
msg_col = Columns - 1;
#endif
// List the suggestions.
msg_start();
msg_row = Rows - 1; // for when 'cmdheight' > 1
lines_left = Rows; // avoid more prompt
vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"),
sug.su_badlen, sug.su_badptr);
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0)
{
// And now the rabbit from the high hat: Avoid showing the
// untranslated message rightleft.
vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC",
sug.su_badlen, sug.su_badptr);
}
#endif
msg_puts((char *)IObuff);
msg_clr_eos();
msg_putchar('\n');
msg_scroll = TRUE;
for (i = 0; i < sug.su_ga.ga_len; ++i)
{
stp = &SUG(sug.su_ga, i);
// The suggested word may replace only part of the bad word, add
// the not replaced part.
vim_strncpy(wcopy, stp->st_word, MAXWLEN);
if (sug.su_badlen > stp->st_orglen)
vim_strncpy(wcopy + stp->st_wordlen,
sug.su_badptr + stp->st_orglen,
sug.su_badlen - stp->st_orglen);
vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1);
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
rl_mirror(IObuff);
#endif
msg_puts((char *)IObuff);
vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy);
msg_puts((char *)IObuff);
// The word may replace more than "su_badlen".
if (sug.su_badlen < stp->st_orglen)
{
vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""),
stp->st_orglen, sug.su_badptr);
msg_puts((char *)IObuff);
}
if (p_verbose > 0)
{
// Add the score.
if (sps_flags & (SPS_DOUBLE | SPS_BEST))
vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)",
stp->st_salscore ? "s " : "",
stp->st_score, stp->st_altscore);
else
vim_snprintf((char *)IObuff, IOSIZE, " (%d)",
stp->st_score);
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
// Mirror the numbers, but keep the leading space.
rl_mirror(IObuff + 1);
#endif
msg_advance(30);
msg_puts((char *)IObuff);
}
msg_putchar('\n');
}
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl = FALSE;
msg_col = 0;
#endif
// Ask for choice.
selected = prompt_for_number(&mouse_used);
if (mouse_used)
selected -= lines_left;
lines_left = Rows; // avoid more prompt
// don't delay for 'smd' in normal_cmd()
msg_scroll = msg_scroll_save;
}
if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)
{
// Save the from and to text for :spellrepall.
VIM_CLEAR(repl_from);
VIM_CLEAR(repl_to);
stp = &SUG(sug.su_ga, selected - 1);
if (sug.su_badlen > stp->st_orglen)
{
// Replacing less than "su_badlen", append the remainder to
// repl_to.
repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);
vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word,
sug.su_badlen - stp->st_orglen,
sug.su_badptr + stp->st_orglen);
repl_to = vim_strsave(IObuff);
}
else
{
// Replacing su_badlen or more, use the whole word.
repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);
repl_to = vim_strsave(stp->st_word);
}
// Replace the word.
p = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1);
if (p != NULL)
{
c = (int)(sug.su_badptr - line);
mch_memmove(p, line, c);
STRCPY(p + c, stp->st_word);
STRCAT(p, sug.su_badptr + stp->st_orglen);
// For redo we use a change-word command.
ResetRedobuff();
AppendToRedobuff((char_u *)"ciw");
AppendToRedobuffLit(p + c,
stp->st_wordlen + sug.su_badlen - stp->st_orglen);
AppendCharToRedobuff(ESC);
// "p" may be freed here
ml_replace(curwin->w_cursor.lnum, p, FALSE);
curwin->w_cursor.col = c;
changed_bytes(curwin->w_cursor.lnum, c);
}
}
else
curwin->w_cursor = prev_cursor;
spell_find_cleanup(&sug);
skip:
vim_free(line);
curwin->w_p_spell = wo_spell_save;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,604 |
Chrome | 87c724d81f0210494211cd36814c4cb2cf4c4bd1 | void GpuDataManager::UpdateGpuFeatureFlags() {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &GpuDataManager::UpdateGpuFeatureFlags));
return;
}
GpuBlacklist* gpu_blacklist = GetGpuBlacklist();
if (gpu_blacklist == NULL)
return;
if (!gpu_blacklist) {
gpu_feature_flags_.set_flags(0);
return;
}
{
base::AutoLock auto_lock(gpu_info_lock_);
gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags(
GpuBlacklist::kOsAny, NULL, gpu_info_);
}
uint32 max_entry_id = gpu_blacklist->max_entry_id();
if (!gpu_feature_flags_.flags()) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
0, max_entry_id + 1);
return;
}
RunGpuInfoUpdateCallbacks();
std::vector<uint32> flag_entries;
gpu_blacklist->GetGpuFeatureFlagEntries(
GpuFeatureFlags::kGpuFeatureAll, flag_entries);
DCHECK_GT(flag_entries.size(), 0u);
for (size_t i = 0; i < flag_entries.size(); ++i) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
flag_entries[i], max_entry_id + 1);
}
}
| 1 | CVE-2011-2850 | 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). | 651 |
Android | 4a524d3a8ae9aa20c36430008e6bd429443f8f1d | WORD32 ih264d_parse_inter_slice_data_cavlc(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD32 uc_more_data_flag;
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2, u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_read_mb_type;
UWORD32 u1_mbaff;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end = 0;
UWORD32 u1_tfr_n_mb = 0;
UWORD32 u1_decode_nmb = 0;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data = ps_dec->ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD32 u1_mb_threshold;
WORD32 ret = OK;
/******************************************************/
/* Initialisations specific to B or P slice */
/******************************************************/
if(ps_slice->u1_slice_type == P_SLICE)
{
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
u1_mb_threshold = 5;
}
else // B_SLICE
{
u1_inter_mb_type = B_MB;
u1_deblk_mb_type = D_B_SLICE;
u1_mb_threshold = 23;
}
/******************************************************/
/* Slice Level Initialisations */
/******************************************************/
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
u1_num_mbsNby2 = 0;
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
i2_mb_skip_run = 0;
uc_more_data_flag = 1;
u1_read_mb_type = 0;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
if((!i2_mb_skip_run) && (!u1_read_mb_type))
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
{
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
}
*pu4_bitstrm_ofst = u4_bitstream_offset;
i2_mb_skip_run = ((1 << u4_ldz) + u4_word - 1);
COPYTHECONTEXT("mb_skip_run", i2_mb_skip_run);
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
u1_read_mb_type = uc_more_data_flag;
}
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
if(i2_mb_skip_run)
{
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
{
/* Storing Skip partition info */
parse_part_params_t *ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
}
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
}
else
{
u1_read_mb_type = 0;
/**************************************************************/
/* Macroblock Layer Begins, Decode the u1_mb_type */
/**************************************************************/
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz, u4_temp;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
*pu4_bitstrm_ofst = u4_bitstream_offset;
u4_temp = ((1 << u4_ldz) + u4_word - 1);
if(u4_temp > (UWORD32)(25 + u1_mb_threshold))
return ERROR_MB_TYPE;
u1_mb_type = u4_temp;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
}
ps_cur_mb_info->u1_mb_type = u1_mb_type;
/**************************************************************/
/* Parse Macroblock data */
/**************************************************************/
if(u1_mb_type < u1_mb_threshold)
{
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ret = ps_dec->pf_parse_inter_mb(ps_dec, ps_cur_mb_info, u1_num_mbs,
u1_num_mbsNby2);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
}
else
{
/* Storing Intra partition info */
ps_parse_mb_data->u1_num_part = 0;
ps_parse_mb_data->u1_isI_mb = 1;
if((25 + u1_mb_threshold) == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_dec->u1_qp = 0;
}
else
{
ret = ih264d_parse_imb_cavlc(
ps_dec, ps_cur_mb_info, u1_num_mbs,
(UWORD8)(u1_mb_type - u1_mb_threshold));
if(ret != OK)
return ret;
}
ps_cur_deblk_mb->u1_mb_type |= D_INTRA_MB;
}
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
}
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = (!(uc_more_data_flag || i2_mb_skip_run));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
/*u1_dma_nby2mb = u1_decode_nmb ||
(u1_num_mbsNby2 == ps_dec->u1_recon_mb_grp_pair);*/
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
{
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
}
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_decode_nmb: %d", u1_decode_nmb);*/
if(u1_decode_nmb)
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
| 1 | CVE-2016-0816 | 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). | 2,884 |
Chrome | 2706470a422dec8f4ae2538e80f0e7e3c4f4f7f6 | PaymentRequest::PaymentRequest(
content::RenderFrameHost* render_frame_host,
content::WebContents* web_contents,
std::unique_ptr<ContentPaymentRequestDelegate> delegate,
PaymentRequestWebContentsManager* manager,
PaymentRequestDisplayManager* display_manager,
mojo::InterfaceRequest<mojom::PaymentRequest> request,
ObserverForTest* observer_for_testing)
: web_contents_(web_contents),
delegate_(std::move(delegate)),
manager_(manager),
display_manager_(display_manager),
display_handle_(nullptr),
binding_(this, std::move(request)),
top_level_origin_(url_formatter::FormatUrlForSecurityDisplay(
web_contents_->GetLastCommittedURL())),
frame_origin_(url_formatter::FormatUrlForSecurityDisplay(
render_frame_host->GetLastCommittedURL())),
observer_for_testing_(observer_for_testing),
journey_logger_(delegate_->IsIncognito(),
ukm::GetSourceIdForWebContentsDocument(web_contents)),
weak_ptr_factory_(this) {
binding_.set_connection_error_handler(base::BindOnce(
&PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr()));
}
| 1 | CVE-2019-5755 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 2,039 |
linux | 75a493e60ac4bbe2e977e7129d6d8cbb0dd236be | int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
struct ipv6_txoptions *opt, int tclass)
{
struct net *net = sock_net(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *first_hop = &fl6->daddr;
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr;
u8 proto = fl6->flowi6_proto;
int seg_len = skb->len;
int hlimit = -1;
u32 mtu;
if (opt) {
unsigned int head_room;
/* First: exthdrs may take lots of space (~8K for now)
MAX_HEADER is not enough.
*/
head_room = opt->opt_nflen + opt->opt_flen;
seg_len += head_room;
head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev);
if (skb_headroom(skb) < head_room) {
struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room);
if (skb2 == NULL) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -ENOBUFS;
}
consume_skb(skb);
skb = skb2;
skb_set_owner_w(skb, sk);
}
if (opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop);
}
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
/*
* Fill in the IPv6 header
*/
if (np)
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
ip6_flow_hdr(hdr, tclass, fl6->flowlabel);
hdr->payload_len = htons(seg_len);
hdr->nexthdr = proto;
hdr->hop_limit = hlimit;
hdr->saddr = fl6->saddr;
hdr->daddr = *first_hop;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
mtu = dst_mtu(dst);
if ((skb->len <= mtu) || skb->local_df || skb_is_gso(skb)) {
IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUT, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
dst->dev, dst_output);
}
skb->dev = dst->dev;
ipv6_local_error(sk, EMSGSIZE, fl6, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,430 |
ImageMagick | a6240a163cb787909703d9fc649cf861f60ddd7c | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
}
clone_info=DestroyImageInfo(clone_info);
RelinquishMagickMemory(BImgBuff);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
} | 1 | CVE-2016-10070 | 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. | 4,729 |
qemu | 3c99afc779c2c78718a565ad8c5e98de7c2c7484 | static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)
{
struct Vmxnet3_TxDesc txd;
uint32_t txd_idx;
uint32_t data_len;
hwaddr data_pa;
for (;;) {
if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) {
break;
}
vmxnet3_dump_tx_descr(&txd);
if (!s->skip_current_tx_pkt) {
data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE;
data_pa = le64_to_cpu(txd.addr);
if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt,
data_pa,
data_len)) {
s->skip_current_tx_pkt = true;
}
}
if (s->tx_sop) {
vmxnet3_tx_retrieve_metadata(s, &txd);
s->tx_sop = false;
}
if (txd.eop) {
if (!s->skip_current_tx_pkt) {
vmxnet_tx_pkt_parse(s->tx_pkt);
if (s->needs_vlan) {
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet3_send_packet(s, qidx);
} else {
vmxnet3_on_tx_done_update_stats(s, qidx,
VMXNET3_PKT_STATUS_ERROR);
}
vmxnet3_complete_packet(s, qidx, txd_idx);
s->tx_sop = true;
s->skip_current_tx_pkt = false;
vmxnet_tx_pkt_reset(s->tx_pkt);
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,150 |
curl | 75dc096e01ef1e21b6c57690d99371dedb2c0b80 | ConnectionDone(struct Curl_easy *data, struct connectdata *conn)
{
/* data->multi->maxconnects can be negative, deal with it. */
size_t maxconnects =
(data->multi->maxconnects < 0) ? data->multi->num_easy * 4:
data->multi->maxconnects;
struct connectdata *conn_candidate = NULL;
/* Mark the current connection as 'unused' */
conn->inuse = FALSE;
if(maxconnects > 0 &&
data->state.conn_cache->num_connections > maxconnects) {
infof(data, "Connection cache is full, closing the oldest one.\n");
conn_candidate = Curl_oldest_idle_connection(data);
if(conn_candidate) {
/* Set the connection's owner correctly */
conn_candidate->data = data;
/* the winner gets the honour of being disconnected */
(void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
}
}
return (conn_candidate == conn) ? FALSE : TRUE;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,759 |
engine | 7df766124f87768b43b9e8947c5a01e17545772c | static int pkey_GOST_ECcp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out,
size_t *out_len, const unsigned char *key,
size_t key_len)
{
GOST_KEY_TRANSPORT *gkt = NULL;
EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx);
struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx);
int pkey_nid = EVP_PKEY_base_id(pubk);
ASN1_OBJECT *crypt_params_obj = (pkey_nid == NID_id_GostR3410_2001 || pkey_nid == NID_id_GostR3410_2001DH) ?
OBJ_nid2obj(NID_id_Gost28147_89_CryptoPro_A_ParamSet) :
OBJ_nid2obj(NID_id_tc26_gost_28147_param_Z);
const struct gost_cipher_info *param =
get_encryption_params(crypt_params_obj);
unsigned char ukm[8], shared_key[32], crypted_key[44];
int ret = 0;
int key_is_ephemeral = 1;
gost_ctx cctx;
EVP_PKEY *sec_key = EVP_PKEY_CTX_get0_peerkey(pctx);
if (data->shared_ukm_size) {
memcpy(ukm, data->shared_ukm, 8);
} else {
if (RAND_bytes(ukm, 8) <= 0) {
GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR);
return 0;
}
}
if (!param)
goto err;
/* Check for private key in the peer_key of context */
if (sec_key) {
key_is_ephemeral = 0;
if (!gost_get0_priv_key(sec_key)) {
GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR);
goto err;
}
} else {
key_is_ephemeral = 1;
if (out) {
sec_key = EVP_PKEY_new();
if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new())
|| !EVP_PKEY_copy_parameters(sec_key, pubk)
|| !gost_ec_keygen(EVP_PKEY_get0(sec_key))) {
GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
GOST_R_ERROR_COMPUTING_SHARED_KEY);
goto err;
}
}
}
if (out) {
int dgst_nid = NID_undef;
EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid);
if (dgst_nid == NID_id_GostR3411_2012_512)
dgst_nid = NID_id_GostR3411_2012_256;
if (!VKO_compute_key(shared_key,
EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),
EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) {
GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
GOST_R_ERROR_COMPUTING_SHARED_KEY);
goto err;
}
gost_init(&cctx, param->sblock);
keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key);
}
gkt = GOST_KEY_TRANSPORT_new();
if (!gkt) {
goto err;
}
if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) {
goto err;
}
if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) {
goto err;
}
if (!ASN1_OCTET_STRING_set
(gkt->key_info->encrypted_key, crypted_key + 8, 32)) {
goto err;
}
if (key_is_ephemeral) {
if (!X509_PUBKEY_set
(&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) {
GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT,
GOST_R_CANNOT_PACK_EPHEMERAL_KEY);
goto err;
}
}
ASN1_OBJECT_free(gkt->key_agreement_info->cipher);
gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid);
if (key_is_ephemeral)
EVP_PKEY_free(sec_key);
if (!key_is_ephemeral) {
/* Set control "public key from client certificate used" */
if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL)
<= 0) {
GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED);
goto err;
}
}
if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, out ? &out : NULL)) > 0)
ret = 1;
OPENSSL_cleanse(shared_key, sizeof(shared_key));
GOST_KEY_TRANSPORT_free(gkt);
return ret;
err:
OPENSSL_cleanse(shared_key, sizeof(shared_key));
if (key_is_ephemeral)
EVP_PKEY_free(sec_key);
GOST_KEY_TRANSPORT_free(gkt);
return -1;
} | 1 | CVE-2022-29242 | 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). | 720 |
Android | 33ef7de9ddc8ea7eb9cbc440d1cf89957a0c267b | WORD32 ih264d_allocate_static_bufs(iv_obj_t **dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_ip_t *ps_create_ip;
ih264d_create_op_t *ps_create_op;
void *pv_buf;
UWORD8 *pu1_buf;
dec_struct_t *ps_dec;
void *(*pf_aligned_alloc)(void *pv_mem_ctxt, WORD32 alignment, WORD32 size);
void (*pf_aligned_free)(void *pv_mem_ctxt, void *pv_buf);
void *pv_mem_ctxt;
WORD32 size;
ps_create_ip = (ih264d_create_ip_t *)pv_api_ip;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
pf_aligned_alloc = ps_create_ip->s_ivd_create_ip_t.pf_aligned_alloc;
pf_aligned_free = ps_create_ip->s_ivd_create_ip_t.pf_aligned_free;
pv_mem_ctxt = ps_create_ip->s_ivd_create_ip_t.pv_mem_ctxt;
/* Initialize return handle to NULL */
ps_create_op->s_ivd_create_op_t.pv_handle = NULL;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, sizeof(iv_obj_t));
RETURN_IF((NULL == pv_buf), IV_FAIL);
*dec_hdl = (iv_obj_t *)pv_buf;
ps_create_op->s_ivd_create_op_t.pv_handle = *dec_hdl;
(*dec_hdl)->pv_codec_handle = NULL;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, sizeof(dec_struct_t));
RETURN_IF((NULL == pv_buf), IV_FAIL);
(*dec_hdl)->pv_codec_handle = (dec_struct_t *)pv_buf;
ps_dec = (dec_struct_t *)pv_buf;
memset(ps_dec, 0, sizeof(dec_struct_t));
#ifndef LOGO_EN
ps_dec->u4_share_disp_buf = ps_create_ip->s_ivd_create_ip_t.u4_share_disp_buf;
#else
ps_dec->u4_share_disp_buf = 0;
#endif
ps_dec->u1_chroma_format =
(UWORD8)(ps_create_ip->s_ivd_create_ip_t.e_output_format);
if((ps_dec->u1_chroma_format != IV_YUV_420P)
&& (ps_dec->u1_chroma_format
!= IV_YUV_420SP_UV)
&& (ps_dec->u1_chroma_format
!= IV_YUV_420SP_VU))
{
ps_dec->u4_share_disp_buf = 0;
}
ps_dec->pf_aligned_alloc = pf_aligned_alloc;
ps_dec->pf_aligned_free = pf_aligned_free;
ps_dec->pv_mem_ctxt = pv_mem_ctxt;
size = ((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_sps = pv_buf;
size = (sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_pps = pv_buf;
size = ithread_get_handle_size();
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pv_dec_thread_handle = pv_buf;
size = ithread_get_handle_size();
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pv_bs_deblk_thread_handle = pv_buf;
size = sizeof(dpb_manager_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_dpb_mgr = pv_buf;
size = sizeof(pred_info_t) * 2 * 32;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_pred = pv_buf;
size = sizeof(disp_mgr_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pv_disp_buf_mgr = pv_buf;
size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size();
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pv_pic_buf_mgr = pv_buf;
size = sizeof(struct pic_buffer_t) * (H264_MAX_REF_PICS * 2);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_pic_buf_base = pv_buf;
size = sizeof(dec_err_status_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_dec_err_status = (dec_err_status_t *)pv_buf;
size = sizeof(sei);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_sei = (sei *)pv_buf;
size = sizeof(dpb_commands_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_dpb_cmds = (dpb_commands_t *)pv_buf;
size = sizeof(dec_bit_stream_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_bitstrm = (dec_bit_stream_t *)pv_buf;
size = sizeof(dec_slice_params_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_cur_slice = (dec_slice_params_t *)pv_buf;
size = MAX(sizeof(dec_seq_params_t), sizeof(dec_pic_params_t));
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pv_scratch_sps_pps = pv_buf;
ps_dec->u4_static_bits_buf_size = 256000;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, ps_dec->u4_static_bits_buf_size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_bits_buf_static = pv_buf;
size = ((TOTAL_LIST_ENTRIES + PAD_MAP_IDX_POC)
* sizeof(void *));
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ppv_map_ref_idx_to_poc_base = pv_buf;
memset(ps_dec->ppv_map_ref_idx_to_poc_base, 0, size);
ps_dec->ppv_map_ref_idx_to_poc = ps_dec->ppv_map_ref_idx_to_poc_base + OFFSET_MAP_IDX_POC;
size = (sizeof(bin_ctxt_model_t) * NUM_CABAC_CTXTS);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->p_cabac_ctxt_table_t = pv_buf;
size = sizeof(ctxt_inc_mb_info_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_left_mb_ctxt_info = pv_buf;
size = MAX_REF_BUF_SIZE * 2;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_ref_buff_base = pv_buf;
ps_dec->pu1_ref_buff = ps_dec->pu1_ref_buff_base + MAX_REF_BUF_SIZE;
size = ((sizeof(WORD16)) * PRED_BUFFER_WIDTH
* PRED_BUFFER_HEIGHT * 2);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pi2_pred1 = pv_buf;
size = sizeof(UWORD8) * (MB_LUM_SIZE);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_temp_mc_buffer = pv_buf;
size = 8 * MAX_REF_BUFS * sizeof(struct pic_buffer_t);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_init_dpb_base = pv_buf;
pu1_buf = pv_buf;
ps_dec->ps_dpb_mgr->ps_init_dpb[0][0] = (struct pic_buffer_t *)pu1_buf;
pu1_buf += size / 2;
ps_dec->ps_dpb_mgr->ps_init_dpb[1][0] = (struct pic_buffer_t *)pu1_buf;
size = (sizeof(UWORD32) * 3
* (MAX_FRAMES * MAX_FRAMES))
<< 3;
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu4_mbaff_wt_mat = pv_buf;
size = sizeof(UWORD32) * 2 * 3
* ((MAX_FRAMES << 1) * (MAX_FRAMES << 1));
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu4_wts_ofsts_mat = pv_buf;
size = (sizeof(neighbouradd_t) << 2);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_left_mvpred_addr = pv_buf;
size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size();
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pv_mv_buf_mgr = pv_buf;
size = sizeof(col_mv_buf_t) * (H264_MAX_REF_PICS * 2);
pv_buf = pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->ps_col_mv_base = pv_buf;
memset(ps_dec->ps_col_mv_base, 0, size);
{
UWORD8 i;
struct pic_buffer_t *ps_init_dpb;
ps_init_dpb = ps_dec->ps_dpb_mgr->ps_init_dpb[0][0];
for(i = 0; i < 2 * MAX_REF_BUFS; i++)
{
ps_init_dpb->pu1_buf1 = NULL;
ps_init_dpb->u1_long_term_frm_idx = MAX_REF_BUFS + 1;
ps_dec->ps_dpb_mgr->ps_init_dpb[0][i] = ps_init_dpb;
ps_dec->ps_dpb_mgr->ps_mod_dpb[0][i] = ps_init_dpb;
ps_init_dpb++;
}
ps_init_dpb = ps_dec->ps_dpb_mgr->ps_init_dpb[1][0];
for(i = 0; i < 2 * MAX_REF_BUFS; i++)
{
ps_init_dpb->pu1_buf1 = NULL;
ps_init_dpb->u1_long_term_frm_idx = MAX_REF_BUFS + 1;
ps_dec->ps_dpb_mgr->ps_init_dpb[1][i] = ps_init_dpb;
ps_dec->ps_dpb_mgr->ps_mod_dpb[1][i] = ps_init_dpb;
ps_init_dpb++;
}
}
ih264d_init_decoder(ps_dec);
return IV_SUCCESS;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,194 |
gpac | bceb03fd2be95097a7b409ea59914f332fb6bc86 | GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
GF_HandlerBox *p = (GF_HandlerBox *)a;
gf_isom_box_dump_start(a, "HandlerBox", trace);
if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
} else {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
}
fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
dump_data(trace, (char *) p->reserved2, 12);
fprintf(trace, "\"");
fprintf(trace, ">\n");
gf_isom_box_dump_done("HandlerBox", a, trace);
return GF_OK;
}
| 1 | CVE-2018-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. | 6,443 |
httpd | fa7b2a5250e54363b3a6c8ac3aaa7de4e8da9b2e | const char * ap_set_scoreboard(cmd_parms *cmd, void *dummy,
const char *arg)
{
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
return err;
}
ap_scoreboard_fname = arg;
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,153 |
Subsets and Splits