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
|
---|---|---|---|---|---|---|---|---|---|
sudo | c4d384082fdbc8406cf19e08d05db4cded920a55 | parse_bool(const char *line, int varlen, int *flags, int fval)
{
debug_decl(parse_bool, SUDOERS_DEBUG_PLUGIN);
switch (sudo_strtobool(line + varlen + 1)) {
case true:
SET(*flags, fval);
debug_return_int(true);
case false:
CLR(*flags, fval);
debug_return_int(false);
default:
sudo_warn(U_("invalid %.*s set by sudo front-end"),
varlen, line);
debug_return_int(-1);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,890 |
Chrome | 5a2de6455f565783c73e53eae2c8b953e7d48520 | static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView)
{
Settings* settings = core(webView)->settings();
const gchar* name = g_intern_string(pspec->name);
GValue value = { 0, { { 0 } } };
g_value_init(&value, pspec->value_type);
g_object_get_property(G_OBJECT(webSettings), name, &value);
if (name == g_intern_string("default-encoding"))
settings->setDefaultTextEncodingName(g_value_get_string(&value));
else if (name == g_intern_string("cursive-font-family"))
settings->setCursiveFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-family"))
settings->setStandardFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("fantasy-font-family"))
settings->setFantasyFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("monospace-font-family"))
settings->setFixedFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("sans-serif-font-family"))
settings->setSansSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("serif-font-family"))
settings->setSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-size"))
settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("default-monospace-font-size"))
settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-font-size"))
settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-logical-font-size"))
settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("enforce-96-dpi"))
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
else if (name == g_intern_string("auto-load-images"))
settings->setLoadsImagesAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("auto-shrink-images"))
settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value));
else if (name == g_intern_string("print-backgrounds"))
settings->setShouldPrintBackgrounds(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-scripts"))
settings->setJavaScriptEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-plugins"))
settings->setPluginsEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dns-prefetching"))
settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("resizable-text-areas"))
settings->setTextAreasAreResizable(g_value_get_boolean(&value));
else if (name == g_intern_string("user-stylesheet-uri"))
settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value)));
else if (name == g_intern_string("enable-developer-extras"))
settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-private-browsing"))
settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-caret-browsing"))
settings->setCaretBrowsingEnabled(g_value_get_boolean(&value));
#if ENABLE(DATABASE)
else if (name == g_intern_string("enable-html5-database")) {
AbstractDatabase::setIsAvailable(g_value_get_boolean(&value));
}
#endif
else if (name == g_intern_string("enable-html5-local-storage"))
settings->setLocalStorageEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-xss-auditor"))
settings->setXSSAuditorEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-spatial-navigation"))
settings->setSpatialNavigationEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-frame-flattening"))
settings->setFrameFlatteningEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-open-windows-automatically"))
settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-access-clipboard"))
settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-offline-web-application-cache"))
settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("editing-behavior"))
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(g_value_get_enum(&value)));
else if (name == g_intern_string("enable-universal-access-from-file-uris"))
settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-file-access-from-file-uris"))
settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dom-paste"))
settings->setDOMPasteAllowed(g_value_get_boolean(&value));
else if (name == g_intern_string("tab-key-cycles-through-elements")) {
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value));
} else if (name == g_intern_string("enable-site-specific-quirks"))
settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-page-cache"))
settings->setUsesPageCache(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-java-applet"))
settings->setJavaEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-hyperlink-auditing"))
settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value));
#if ENABLE(SPELLCHECK)
else if (name == g_intern_string("spell-checking-languages")) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value));
}
#endif
#if ENABLE(WEBGL)
else if (name == g_intern_string("enable-webgl"))
settings->setWebGLEnabled(g_value_get_boolean(&value));
#endif
else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name))
g_warning("Unexpected setting '%s'", name);
g_value_unset(&value);
}
| 1 | CVE-2011-2799 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 9,489 |
linux | a5ec6ae161d72f01411169a938fa5f8baea16e8f | static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
| 1 | CVE-2017-17856 | 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,385 |
linux | db29a9508a9246e77087c5531e45b2c88ec6988b | static int generic_kmemdup_compat_sysctl_table(struct nf_proto_net *pn,
struct nf_generic_net *gn)
{
#ifdef CONFIG_SYSCTL
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
pn->ctl_compat_table = kmemdup(generic_compat_sysctl_table,
sizeof(generic_compat_sysctl_table),
GFP_KERNEL);
if (!pn->ctl_compat_table)
return -ENOMEM;
pn->ctl_compat_table[0].data = &gn->timeout;
#endif
#endif
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,247 |
Chrome | 4c19b042ea31bd393d2265656f94339d1c3d82ff | bool FileUtilProxy::Write(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
const char* buffer,
int bytes_to_write,
WriteCallback* callback) {
if (bytes_to_write <= 0)
return false;
return Start(FROM_HERE, message_loop_proxy,
new RelayWrite(file, offset, buffer, bytes_to_write, callback));
}
| 1 | CVE-2011-2880 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 4,259 |
linux | c06cfb08b88dfbe13be44a69ae2fdc3a7c902d81 | static void ceph_key_destroy(struct key *key)
{
struct ceph_crypto_key *ckey = key->payload.data;
ceph_crypto_key_destroy(ckey);
kfree(ckey);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,803 |
Chrome | 96dbafe288dbe2f0cc45fa3c39daf6d0c37acbab | xsltNumberFormat(xsltTransformContextPtr ctxt,
xsltNumberDataPtr data,
xmlNodePtr node)
{
xmlBufferPtr output = NULL;
int amount, i;
double number;
xsltFormat tokens;
int tempformat = 0;
if ((data->format == NULL) && (data->has_format != 0)) {
data->format = xsltEvalAttrValueTemplate(ctxt, data->node,
(const xmlChar *) "format",
XSLT_NAMESPACE);
tempformat = 1;
}
if (data->format == NULL) {
return;
}
output = xmlBufferCreate();
if (output == NULL)
goto XSLT_NUMBER_FORMAT_END;
xsltNumberFormatTokenize(data->format, &tokens);
/*
* Evaluate the XPath expression to find the value(s)
*/
if (data->value) {
amount = xsltNumberFormatGetValue(ctxt->xpathCtxt,
node,
data->value,
&number);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (data->level) {
if (xmlStrEqual(data->level, (const xmlChar *) "single")) {
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
1,
data->doc,
data->node);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "multiple")) {
double numarray[1024];
int max = sizeof(numarray)/sizeof(numarray[0]);
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
numarray,
max,
data->doc,
data->node);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
numarray,
amount,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "any")) {
amount = xsltNumberFormatGetAnyLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
data->doc,
data->node);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
}
}
/* Insert number as text node */
xsltCopyTextString(ctxt, ctxt->insert, xmlBufferContent(output), 0);
if (tokens.start != NULL)
xmlFree(tokens.start);
if (tokens.end != NULL)
xmlFree(tokens.end);
for (i = 0;i < tokens.nTokens;i++) {
if (tokens.tokens[i].separator != NULL)
xmlFree(tokens.tokens[i].separator);
}
XSLT_NUMBER_FORMAT_END:
if (tempformat == 1) {
/* The format need to be recomputed each time */
data->format = NULL;
}
if (output != NULL)
xmlBufferFree(output);
}
| 1 | CVE-2016-1683 | 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,245 |
zziplib | ac9ae39ef419e9f0f83da1e583314d8c7cda34a6 | static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)
{
ZZIP_FILE* file = zzip_file_open (disk, name, 0);
if (file)
{
char buffer[1024]; int len;
while (0 < (len = zzip_file_read (file, buffer, 1024)))
{
fwrite (buffer, 1, len, out);
}
zzip_file_close (file);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,312 |
linux | b9a532277938798b53178d5a66af6e2915cb27cf | static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version)
{
switch (version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shmid_ds out;
memset(&out, 0, sizeof(out));
ipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm);
out.shm_segsz = in->shm_segsz;
out.shm_atime = in->shm_atime;
out.shm_dtime = in->shm_dtime;
out.shm_ctime = in->shm_ctime;
out.shm_cpid = in->shm_cpid;
out.shm_lpid = in->shm_lpid;
out.shm_nattch = in->shm_nattch;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,076 |
strongswan | 0acd1ab4d08d53d80393b1a37b8781f6e7b2b996 | static void pop_end(stroke_msg_t *msg, const char* label, stroke_end_t *end)
{
pop_string(msg, &end->address);
pop_string(msg, &end->subnets);
pop_string(msg, &end->sourceip);
pop_string(msg, &end->dns);
pop_string(msg, &end->auth);
pop_string(msg, &end->auth2);
pop_string(msg, &end->id);
pop_string(msg, &end->id2);
pop_string(msg, &end->rsakey);
pop_string(msg, &end->cert);
pop_string(msg, &end->cert2);
pop_string(msg, &end->ca);
pop_string(msg, &end->ca2);
pop_string(msg, &end->groups);
pop_string(msg, &end->groups2);
pop_string(msg, &end->cert_policy);
pop_string(msg, &end->updown);
DBG_OPT(" %s=%s", label, end->address);
DBG_OPT(" %ssubnet=%s", label, end->subnets);
DBG_OPT(" %ssourceip=%s", label, end->sourceip);
DBG_OPT(" %sdns=%s", label, end->dns);
DBG_OPT(" %sauth=%s", label, end->auth);
DBG_OPT(" %sauth2=%s", label, end->auth2);
DBG_OPT(" %sid=%s", label, end->id);
DBG_OPT(" %sid2=%s", label, end->id2);
DBG_OPT(" %srsakey=%s", label, end->rsakey);
DBG_OPT(" %scert=%s", label, end->cert);
DBG_OPT(" %scert2=%s", label, end->cert2);
DBG_OPT(" %sca=%s", label, end->ca);
DBG_OPT(" %sca2=%s", label, end->ca2);
DBG_OPT(" %sgroups=%s", label, end->groups);
DBG_OPT(" %sgroups2=%s", label, end->groups2);
DBG_OPT(" %supdown=%s", label, end->updown);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,485 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | bool Chapters::Edition::ExpandAtomsArray()
{
if (m_atoms_size > m_atoms_count)
return true; // nothing else to do
const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size;
Atom* const atoms = new (std::nothrow) Atom[size];
if (atoms == NULL)
return false;
for (int idx = 0; idx < m_atoms_count; ++idx)
{
m_atoms[idx].ShallowCopy(atoms[idx]);
}
delete[] m_atoms;
m_atoms = atoms;
m_atoms_size = size;
return true;
}
| 1 | CVE-2016-1621 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 9,454 |
LibRaw | c243f4539233053466c1309bde606815351bee81 | void LibRaw::parseSonyMakernotes(
int base, unsigned tag, unsigned type, unsigned len, unsigned dng_writer,
uchar *&table_buf_0x0116, ushort &table_buf_0x0116_len,
uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len,
uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len,
uchar *&table_buf_0x9400, ushort &table_buf_0x9400_len,
uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len,
uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len,
uchar *&table_buf_0x9406, ushort &table_buf_0x9406_len,
uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len,
uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len)
{
ushort lid, a, b, c, d;
uchar *table_buf;
uchar uc;
uchar s[2];
int LensDataValid = 0;
unsigned uitemp;
if (tag == 0xb001)
{ // Sony ModelID
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x0116_len)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
if (table_buf_0x2010_len)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
if (table_buf_0x9050_len)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
if (table_buf_0x9400_len)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
if (table_buf_0x9402_len)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
if (table_buf_0x9403_len)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
if (table_buf_0x9406_len)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
if (table_buf_0x940c_len)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
if (table_buf_0x940e_len)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id);
free(table_buf_0x940e);
table_buf_0x940e_len = 0;
}
}
else if (tag == 0xb000)
{
FORC4 imSony.FileFormat = imSony.FileFormat * 10 + fgetc(ifp);
}
else if (tag == 0xb026)
{
uitemp = get4();
if (uitemp != 0xffffffff)
imgdata.shootinginfo.ImageStabilization = uitemp;
}
else if (((tag == 0x0001) || // Minolta CameraSettings, big endian
(tag == 0x0003)) &&
(len >= 196))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
lid = 0x01 << 2;
imgdata.shootinginfo.ExposureMode =
(unsigned)table_buf[lid] << 24 | (unsigned)table_buf[lid + 1] << 16 |
(unsigned)table_buf[lid + 2] << 8 | (unsigned)table_buf[lid + 3];
lid = 0x06 << 2;
imgdata.shootinginfo.DriveMode =
(unsigned)table_buf[lid] << 24 | (unsigned)table_buf[lid + 1] << 16 |
(unsigned)table_buf[lid + 2] << 8 | (unsigned)table_buf[lid + 3];
lid = 0x07 << 2;
imgdata.shootinginfo.MeteringMode =
(unsigned)table_buf[lid] << 24 | (unsigned)table_buf[lid + 1] << 16 |
(unsigned)table_buf[lid + 2] << 8 | (unsigned)table_buf[lid + 3];
lid = 0x25 << 2;
imSony.MinoltaCamID =
(unsigned)table_buf[lid] << 24 | (unsigned)table_buf[lid + 1] << 16 |
(unsigned)table_buf[lid + 2] << 8 | (unsigned)table_buf[lid + 3];
if (imSony.MinoltaCamID != -1)
ilm.CamID = imSony.MinoltaCamID;
lid = 0x30 << 2;
imgdata.shootinginfo.FocusMode =
(unsigned)table_buf[lid] << 24 | (unsigned)table_buf[lid + 1] << 16 |
(unsigned)table_buf[lid + 2] << 8 | (unsigned)table_buf[lid + 3];
free(table_buf);
}
else if ((tag == 0x0004) && // Minolta CameraSettings7D, big endian
(len >= 227))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
lid = 0x0;
imgdata.shootinginfo.ExposureMode =
(ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1];
lid = 0x0e << 1;
imgdata.shootinginfo.FocusMode =
(ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1];
lid = 0x10 << 1;
imgdata.shootinginfo.AFPoint =
(ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1];
lid = 0x25 << 1;
switch ((ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1]) {
case 0:
case 1:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 4:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
lid = 0x71 << 1;
imgdata.shootinginfo.ImageStabilization =
(ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1];
free(table_buf);
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) &&
!strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700 : CameraInfo
(len == 5478) || // a850, a900 : CameraInfo
(len == 5506) || // a200, a300, a350 : CameraInfo2
(len == 6118) || // a230, a290, a330, a380, a390 : CameraInfo2
(len == 15360)) // a450, a500, a550, a560, a580 : CameraInfo3
// a33, a35, a55
// NEX-3, NEX-5, NEX-5C, NEX-C3, NEX-VG10E
)
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
LensDataValid = 1;
}
switch (len)
{
case 368: // a700: CameraInfo
case 5478: // a850, a900: CameraInfo
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2],
table_buf[5], table_buf[4], table_buf[7])))
{
if (LensDataValid)
{
if (table_buf[0] | table_buf[3])
ilm.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
ilm.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
ilm.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
ilm.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
}
imSony.AFPointSelected = table_buf[21];
imgdata.shootinginfo.AFPoint = (ushort)table_buf[25];
if (len == 5478)
{
imSony.AFMicroAdjValue = table_buf[304] - 20;
imSony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0);
imSony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f;
}
}
break;
default:
// CameraInfo2 & 3
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3],
table_buf[4], table_buf[5], table_buf[6])))
{
if ((LensDataValid) && strncasecmp(model, "NEX-5C", 6))
{
if (table_buf[1] | table_buf[2])
ilm.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
ilm.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
ilm.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
ilm.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
if (!strncasecmp(model, "DSLR-A450", 9) ||
!strncasecmp(model, "DSLR-A500", 9) ||
!strncasecmp(model, "DSLR-A550", 9))
{
imSony.AFPointSelected = table_buf[0x14];
imgdata.shootinginfo.FocusMode = table_buf[0x15];
imgdata.shootinginfo.AFPoint = (ushort)table_buf[0x18];
}
else if (!strncasecmp(model, "SLT-", 4) ||
!strncasecmp(model, "DSLR-A560", 9) ||
!strncasecmp(model, "DSLR-A580", 9))
{
imSony.AFPointSelected = table_buf[0x1c];
imgdata.shootinginfo.FocusMode = table_buf[0x1d];
imgdata.shootinginfo.AFPoint = (ushort)table_buf[0x20];
}
}
}
free(table_buf);
}
else if ((!dng_writer) && ((tag == 0x0020) || (tag == 0xb0280020)))
{
if (!strncasecmp(model, "DSLR-A100", 9))
{ // WBInfoA100
fseek(ifp, 0x49dc, SEEK_CUR);
stmread(imgdata.shootinginfo.InternalBodySerial, 13, ifp);
}
else if ((len ==
19154) || // a200 a230 a290 a300 a330 a350 a380 a390 : FocusInfo
(len == 19148))
{ // a700 a850 a900 : FocusInfo
table_buf = (uchar *)malloc(128);
fread(table_buf, 128, 1, ifp);
imgdata.shootinginfo.DriveMode = table_buf[14];
imgdata.shootinginfo.ExposureProgram = table_buf[63];
free(table_buf);
}
else if (len == 20480) // a450 a500 a550 a560 a580 a33 a35 a55 : MoreInfo
// NEX-3 NEX-5 NEX-C3 NEX-VG10E : MoreInfo
{
a = get2();
b = get2();
c = get2();
d = get2();
if ((a) && (c == 1))
{
fseek(ifp, d - 8, SEEK_CUR);
table_buf = (uchar *)malloc(256);
fread(table_buf, 256, 1, ifp);
imgdata.shootinginfo.DriveMode = table_buf[1];
imgdata.shootinginfo.ExposureProgram = table_buf[2];
imgdata.shootinginfo.MeteringMode = table_buf[3];
switch (table_buf[6]) {
case 1:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 2:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
if (strncasecmp(model, "DSLR-A450", 9) &&
strncasecmp(model, "DSLR-A500", 9) &&
strncasecmp(model, "DSLR-A550", 9))
imgdata.shootinginfo.FocusMode = table_buf[0x13];
else
imgdata.shootinginfo.FocusMode = table_buf[0x2c];
free(table_buf);
}
}
}
else if (tag == 0x0102)
{
imSony.Quality = get4();
}
else if (tag == 0x0104)
{
imCommon.FlashEC = getreal(type);
}
else if (tag == 0x0105)
{ // Teleconverter
ilm.TeleconverterID = get4();
}
else if (tag == 0x0107)
{
uitemp = get4();
if (uitemp == 1)
imgdata.shootinginfo.ImageStabilization = 0;
else if (uitemp == 5)
imgdata.shootinginfo.ImageStabilization = 1;
else
imgdata.shootinginfo.ImageStabilization = uitemp;
}
else if ((tag == 0xb0280088) && (dng_writer == nonDNG))
{
thumb_offset = get4() + base;
}
else if ((tag == 0xb0280089) && (dng_writer == nonDNG))
{
thumb_length = get4();
}
else if (((tag == 0x0114) || // CameraSettings
(tag == 0xb0280114)) &&
(len < 256000))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len)
{
case 260: // Sony a100, big endian
imgdata.shootinginfo.ExposureMode =
((ushort)table_buf[0]) << 8 | ((ushort)table_buf[1]);
lid = 0x0a << 1;
imgdata.shootinginfo.DriveMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
lid = 0x0c << 1;
imgdata.shootinginfo.FocusMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
lid = 0x0d << 1;
imSony.AFPointSelected = table_buf[lid + 1];
lid = 0x0e << 1;
imSony.AFAreaModeSetting = table_buf[lid + 1];
lid = 0x12 << 1;
imgdata.shootinginfo.MeteringMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
lid = 0x17 << 1;
switch ((ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1]) {
case 0:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 2:
imCommon.ColorSpace = LIBRAW_COLORSPACE_MonochromeGamma;
break;
case 5:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
break;
case 448: // Minolta "DYNAX 5D" and its aliases, big endian
lid = 0x0a << 1;
imgdata.shootinginfo.ExposureMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
lid = 0x25 << 1;
imgdata.shootinginfo.MeteringMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
lid = 0x2f << 1;
switch ((ushort)table_buf[lid] << 8 | (ushort)table_buf[lid + 1]) {
case 0:
case 1:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 2:
imCommon.ColorSpace = LIBRAW_COLORSPACE_MonochromeGamma;
break;
case 4:
case 5:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
lid = 0xbd << 1;
imgdata.shootinginfo.ImageStabilization =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
break;
case 280: // a200 a300 a350 a700
case 364: // a850 a900
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]);
ilm.CurAp = libraw_powf64l(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f);
}
lid = 0x04 << 1;
imgdata.shootinginfo.DriveMode = table_buf[lid + 1];
lid = 0x1b << 1;
switch (((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1])) {
case 0:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 1:
case 5:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
lid = 0x4d << 1;
imgdata.shootinginfo.FocusMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
if (!imCommon.ColorSpace ||
(imCommon.ColorSpace == LIBRAW_COLORSPACE_Unknown)) {
lid = 0x83 << 1;
switch (((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1])) {
case 6:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 5:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
}
break;
case 332: // a230 a290 a330 a380 a390
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]);
ilm.CurAp = libraw_powf64l(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f);
}
lid = 0x4d << 1;
imgdata.shootinginfo.FocusMode =
((ushort)table_buf[lid]) << 8 | ((ushort)table_buf[lid + 1]);
lid = 0x7e << 1;
imgdata.shootinginfo.DriveMode = table_buf[lid + 1];
break;
case 1536: // a560 a580 a33 a35 a55 NEX-3 NEX-5 NEX-5C NEX-C3 NEX-VG10E
case 2048: // a450 a500 a550
// CameraSettings3 are little endian
switch (table_buf[0x0e]) {
case 1:
imCommon.ColorSpace = LIBRAW_COLORSPACE_sRGB;
break;
case 2:
imCommon.ColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
break;
default:
imCommon.ColorSpace = LIBRAW_COLORSPACE_Unknown;
break;
}
imgdata.shootinginfo.DriveMode = table_buf[0x34];
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (ilm.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153])
{
case 16:
ilm.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 17:
ilm.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
break;
}
free(table_buf);
}
else if ((tag == 0x3000) && (len < 256000))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
for (int i = 0; i < 20; i++)
imSony.SonyDateTime[i] = table_buf[6 + i];
free(table_buf);
}
else if (tag == 0x0116 && len < 256000)
{
table_buf_0x0116 = (uchar *)malloc(len);
table_buf_0x0116_len = len;
fread(table_buf_0x0116, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, ilm.CamID);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
}
else if (tag == 0x2008)
{
imSony.LongExposureNoiseReduction = get4();
}
else if (tag == 0x2009)
{
imSony.HighISONoiseReduction = get2();
}
else if (tag == 0x200a)
{
imSony.HDR[0] = get2();
imSony.HDR[1] = get2();
}
else if (tag == 0x2010 && len < 256000)
{
table_buf_0x2010 = (uchar *)malloc(len);
table_buf_0x2010_len = len;
fread(table_buf_0x2010, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
}
else if (tag == 0x201a)
{
imSony.ElectronicFrontCurtainShutter = get4();
}
else if (tag == 0x201b)
{
if ((imSony.CameraType != LIBRAW_SONY_DSC) ||
(ilm.CamID == SonyID_DSC_RX10M4) ||
(ilm.CamID == SonyID_DSC_RX100M6) ||
(ilm.CamID == SonyID_DSC_RX100M5A) ||
(ilm.CamID == SonyID_DSC_RX0M2) ||
(ilm.CamID == SonyID_DSC_RX100M7))
{
fread(&uc, 1, 1, ifp);
imgdata.shootinginfo.FocusMode = (short)uc;
}
}
else if (tag == 0x201c)
{
if ((imSony.CameraType != LIBRAW_SONY_DSC) ||
(ilm.CamID == SonyID_DSC_RX10M4) ||
(ilm.CamID == SonyID_DSC_RX100M6) ||
(ilm.CamID == SonyID_DSC_RX100M5A) ||
(ilm.CamID == SonyID_DSC_RX0M2) ||
(ilm.CamID == SonyID_DSC_RX100M7))
{
imSony.AFAreaModeSetting = fgetc(ifp);
}
}
else if (tag == 0x201d)
{
if (((imSony.AFAreaModeSetting == 3) &&
((imSony.CameraType == LIBRAW_SONY_ILCE) ||
(imSony.CameraType == LIBRAW_SONY_NEX) ||
(ilm.CamID == SonyID_DSC_RX10M4) ||
(ilm.CamID == SonyID_DSC_RX100M6) ||
(ilm.CamID == SonyID_DSC_RX100M5A) ||
(ilm.CamID == SonyID_DSC_RX0M2) ||
(ilm.CamID == SonyID_DSC_RX100M7))) ||
((imSony.AFAreaModeSetting == 4) &&
(imSony.CameraType == LIBRAW_SONY_ILCA)))
{
imSony.FlexibleSpotPosition[0] = get2();
imSony.FlexibleSpotPosition[1] = get2();
}
}
else if (tag == 0x201e)
{
if (imSony.CameraType != LIBRAW_SONY_DSC)
{
imSony.AFPointSelected = fgetc(ifp);
}
}
else if (tag == 0x2020)
{
if (imSony.CameraType != LIBRAW_SONY_DSC)
{
fread(imSony.AFPointsUsed, 1, 10, ifp);
}
}
else if (tag == 0x2021)
{
if ((imSony.CameraType != LIBRAW_SONY_DSC) ||
(ilm.CamID == SonyID_DSC_RX10M4) ||
(ilm.CamID == SonyID_DSC_RX100M6) ||
(ilm.CamID == SonyID_DSC_RX100M5A) ||
(ilm.CamID == SonyID_DSC_RX0M2) ||
(ilm.CamID == SonyID_DSC_RX100M7))
{
imSony.AFTracking = fgetc(ifp);
}
}
else if (tag == 0x2027)
{
FORC4 imSony.FocusLocation[c] = get2();
}
else if (tag == 0x2028)
{
if (get2())
{
imSony.VariableLowPassFilter = get2();
}
}
else if (tag == 0x2029)
{
imSony.RAWFileType = get2();
}
else if (tag == 0x202c)
{
imSony.MeteringMode2 = get2();
}
else if (tag == 0x202f)
{
imSony.PixelShiftGroupID = get4();
imSony.PixelShiftGroupPrefix = imSony.PixelShiftGroupID >> 22;
imSony.PixelShiftGroupID =
((imSony.PixelShiftGroupID >> 17) & (unsigned)0x1f) *
(unsigned)1000000 +
((imSony.PixelShiftGroupID >> 12) & (unsigned)0x1f) * (unsigned)10000 +
((imSony.PixelShiftGroupID >> 6) & (unsigned)0x3f) * (unsigned)100 +
(imSony.PixelShiftGroupID & (unsigned)0x3f);
imSony.numInPixelShiftGroup = fgetc(ifp);
imSony.nShotsInPixelShiftGroup = fgetc(ifp);
}
else if (tag == 0x9050 && len < 256000)
{ // little endian
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_len = len;
fread(table_buf_0x9050, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, ilm.CamID);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
}
else if (tag == 0x9400 && len < 256000)
{
table_buf_0x9400 = (uchar *)malloc(len);
table_buf_0x9400_len = len;
fread(table_buf_0x9400, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
}
else if (tag == 0x9402 && len < 256000)
{
table_buf_0x9402 = (uchar *)malloc(len);
table_buf_0x9402_len = len;
fread(table_buf_0x9402, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
}
else if (tag == 0x9403 && len < 256000)
{
table_buf_0x9403 = (uchar *)malloc(len);
table_buf_0x9403_len = len;
fread(table_buf_0x9403, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
}
else if ((tag == 0x9405) && (len < 256000) && (len > 0x64))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
uc = table_buf[0x0];
if (imCommon.real_ISO < 0.1f)
{
if ((uc == 0x25) || (uc == 0x3a) || (uc == 0x76) || (uc == 0x7e) ||
(uc == 0x8b) || (uc == 0x9a) || (uc == 0xb3) || (uc == 0xe1))
{
s[0] = SonySubstitution[table_buf[0x04]];
s[1] = SonySubstitution[table_buf[0x05]];
imCommon.real_ISO =
100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
free(table_buf);
}
else if (tag == 0x9406 && len < 256000)
{
table_buf_0x9406 = (uchar *)malloc(len);
table_buf_0x9406_len = len;
fread(table_buf_0x9406, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_len = len;
fread(table_buf_0x940c, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
}
else if (tag == 0x940e && len < 256000)
{
table_buf_0x940e = (uchar *)malloc(len);
table_buf_0x940e_len = len;
fread(table_buf_0x940e, len, 1, ifp);
if (ilm.CamID)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, ilm.CamID);
free(table_buf_0x940e);
table_buf_0x940e_len = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (ilm.LensID == -1))
{
ilm.LensID = get4();
// printf ("==>> 1: ilm.LensID %lld\n", ilm.LensID);
if ((ilm.LensID > 0x4900) && (ilm.LensID <= 0x5900))
{
ilm.AdapterID = 0x4900;
ilm.LensID -= ilm.AdapterID;
ilm.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(ilm.Adapter, "MC-11");
}
else if ((ilm.LensID > 0xef00) && (ilm.LensID < 0xffff) &&
(ilm.LensID != 0xff00))
{
ilm.AdapterID = 0xef00;
ilm.LensID -= ilm.AdapterID;
ilm.LensMount = LIBRAW_MOUNT_Canon_EF;
}
else if (((ilm.LensID != -1) && (ilm.LensID < 0xef00)) ||
(ilm.LensID == 0xff00))
ilm.LensMount = LIBRAW_MOUNT_Minolta_A;
/*
if (tag == 0x010c)
ilm.CameraMount = LIBRAW_MOUNT_Minolta_A;
*/
}
else if (tag == 0xb02a && len < 256000)
{ // Sony LensSpec
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3],
table_buf[4], table_buf[5], table_buf[6])))
{
if (table_buf[1] | table_buf[2])
ilm.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
ilm.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
ilm.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
ilm.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
free(table_buf);
}
else if ((tag == 0xb02b) && !imgdata.sizes.raw_inset_crop.cwidth &&
(len == 2))
{
imgdata.sizes.raw_inset_crop.cheight = get4();
imgdata.sizes.raw_inset_crop.cwidth = get4();
}
else if (tag == 0xb041)
{
imgdata.shootinginfo.ExposureMode = get2();
}
// MetaVersion: (unique_id >= 286)
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,824 |
Chrome | e1e0c4301aaa8228e362f2409dbde2d4d1896866 | void Document::open()
{
ASSERT(!importLoader());
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().provisionalDocumentLoader())
m_frame->loader().stopAllLoaders();
}
removeAllEventListenersRecursively();
implicitOpen(ForceSynchronousParsing);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
m_loadEventProgress = LoadEventNotRun;
}
| 1 | CVE-2015-6782 | 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. | 2,513 |
libarchive | 3014e19820ea53c15c90f9d447ca3e668a0b76c6 | set_directory_record(unsigned char *p, size_t n, struct isoent *isoent,
struct iso9660 *iso9660, enum dir_rec_type t,
enum vdd_type vdd_type)
{
unsigned char *bp;
size_t dr_len;
size_t fi_len;
if (p != NULL) {
/*
* Check whether a write buffer size is less than the
* saved size which is needed to write this Directory
* Record.
*/
switch (t) {
case DIR_REC_VD:
dr_len = isoent->dr_len.vd; break;
case DIR_REC_SELF:
dr_len = isoent->dr_len.self; break;
case DIR_REC_PARENT:
dr_len = isoent->dr_len.parent; break;
case DIR_REC_NORMAL:
default:
dr_len = isoent->dr_len.normal; break;
}
if (dr_len > n)
return (0);/* Needs more buffer size. */
}
if (t == DIR_REC_NORMAL && isoent->identifier != NULL)
fi_len = isoent->id_len;
else
fi_len = 1;
if (p != NULL) {
struct isoent *xisoent;
struct isofile *file;
unsigned char flag;
if (t == DIR_REC_PARENT)
xisoent = isoent->parent;
else
xisoent = isoent;
file = isoent->file;
if (file->hardlink_target != NULL)
file = file->hardlink_target;
/* Make a file flag. */
if (xisoent->dir)
flag = FILE_FLAG_DIRECTORY;
else {
if (file->cur_content->next != NULL)
flag = FILE_FLAG_MULTI_EXTENT;
else
flag = 0;
}
bp = p -1;
/* Extended Attribute Record Length */
set_num_711(bp+2, 0);
/* Location of Extent */
if (xisoent->dir)
set_num_733(bp+3, xisoent->dir_location);
else
set_num_733(bp+3, file->cur_content->location);
/* Data Length */
if (xisoent->dir)
set_num_733(bp+11,
xisoent->dir_block * LOGICAL_BLOCK_SIZE);
else
set_num_733(bp+11, (uint32_t)file->cur_content->size);
/* Recording Date and Time */
/* NOTE:
* If a file type is symbolic link, you are seeing this
* field value is different from a value mkisofs makes.
* libarchive uses lstat to get this one, but it
* seems mkisofs uses stat to get.
*/
set_time_915(bp+19,
archive_entry_mtime(xisoent->file->entry));
/* File Flags */
bp[26] = flag;
/* File Unit Size */
set_num_711(bp+27, 0);
/* Interleave Gap Size */
set_num_711(bp+28, 0);
/* Volume Sequence Number */
set_num_723(bp+29, iso9660->volume_sequence_number);
/* Length of File Identifier */
set_num_711(bp+33, (unsigned char)fi_len);
/* File Identifier */
switch (t) {
case DIR_REC_VD:
case DIR_REC_SELF:
set_num_711(bp+34, 0);
break;
case DIR_REC_PARENT:
set_num_711(bp+34, 1);
break;
case DIR_REC_NORMAL:
if (isoent->identifier != NULL)
memcpy(bp+34, isoent->identifier, fi_len);
else
set_num_711(bp+34, 0);
break;
}
} else
bp = NULL;
dr_len = 33 + fi_len;
/* Padding Field */
if (dr_len & 0x01) {
dr_len ++;
if (p != NULL)
bp[dr_len] = 0;
}
/* Volume Descriptor does not record extension. */
if (t == DIR_REC_VD) {
if (p != NULL)
/* Length of Directory Record */
set_num_711(p, (unsigned char)dr_len);
else
isoent->dr_len.vd = (int)dr_len;
return ((int)dr_len);
}
/* Rockridge */
if (iso9660->opt.rr && vdd_type != VDD_JOLIET)
dr_len = set_directory_record_rr(bp, (int)dr_len,
isoent, iso9660, t);
if (p != NULL)
/* Length of Directory Record */
set_num_711(p, (unsigned char)dr_len);
else {
/*
* Save the size which is needed to write this
* Directory Record.
*/
switch (t) {
case DIR_REC_VD:
/* This case does not come, but compiler
* complains that DIR_REC_VD not handled
* in switch .... */
break;
case DIR_REC_SELF:
isoent->dr_len.self = (int)dr_len; break;
case DIR_REC_PARENT:
isoent->dr_len.parent = (int)dr_len; break;
case DIR_REC_NORMAL:
isoent->dr_len.normal = (int)dr_len; break;
}
}
return ((int)dr_len);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,919 |
Chrome | 5576cbc1d3e214dfbb5d3ffcdbe82aa8ba0088fc | void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client,
uint32_t port_index,
const std::vector<uint8>& data,
double timestamp) {
DCHECK_LT(port_index, output_streams_.size());
output_streams_[port_index]->Send(data);
client->AccumulateMidiBytesSent(data.size());
}
| 1 | CVE-2015-1232 | 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,774 |
ceph | 2927fd91d41e505237cc73f9700e5c6a63e5cb4f | void MonClient::handle_mon_command_ack(MMonCommandAck *ack)
{
MonCommand *r = NULL;
uint64_t tid = ack->get_tid();
if (tid == 0 && !mon_commands.empty()) {
r = mon_commands.begin()->second;
ldout(cct, 10) << __func__ << " has tid 0, assuming it is " << r->tid << dendl;
} else {
map<uint64_t,MonCommand*>::iterator p = mon_commands.find(tid);
if (p == mon_commands.end()) {
ldout(cct, 10) << __func__ << " " << ack->get_tid() << " not found" << dendl;
ack->put();
return;
}
r = p->second;
}
ldout(cct, 10) << __func__ << " " << r->tid << " " << r->cmd << dendl;
if (r->poutbl)
r->poutbl->claim(ack->get_data());
_finish_command(r, ack->r, ack->rs);
ack->put();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,302 |
php-radius | 13c149b051f82b709e8d7cc32111e84b49d57234 | PHP_FUNCTION(radius_create_request)
{
long code;
radius_descriptor *raddesc;
zval *z_radh;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &z_radh, &code) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius);
if (rad_create_request(raddesc->radh, code) == -1) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,083 |
openafs | 396240cf070a806b91fea81131d034e1399af1e0 | listEntries(struct rx_call *call, afs_int32 flag, afs_int32 startindex,
prentries *bulkentries, afs_int32 *nextstartindex, afs_int32 *cid)
{
afs_int32 code;
struct ubik_trans *tt;
afs_int32 i, eof, pos, maxentries, f;
struct prentry tentry;
afs_int32 pollcount = 0;
*nextstartindex = -1;
bulkentries->prentries_val = 0;
bulkentries->prentries_len = 0;
code = Initdb();
if (code != PRSUCCESS)
return code;
code = ubik_BeginTransReadAny(dbase, UBIK_READTRANS, &tt);
if (code)
return code;
code = ubik_SetLock(tt, 1, 1, LOCKREAD);
if (code)
ABORT_WITH(tt, code);
code = read_DbHeader(tt);
if (code)
ABORT_WITH(tt, code);
/* Make sure we are an authenticated caller and that we are on the
* SYSADMIN list.
*/
code = WhoIsThis(call, tt, cid);
if (code)
ABORT_WITH(tt, PRPERM);
code = IsAMemberOf(tt, *cid, SYSADMINID);
if (!code && !pr_noAuth)
ABORT_WITH(tt, PRPERM);
eof = ntohl(cheader.eofPtr) - sizeof(cheader);
maxentries = eof / sizeof(struct prentry);
for (i = startindex; i < maxentries; i++) {
pos = i * sizeof(struct prentry) + sizeof(cheader);
code = pr_ReadEntry(tt, 0, pos, &tentry);
if (code)
goto done;
if (++pollcount > 50) {
#ifndef AFS_PTHREAD_ENV
IOMGR_Poll();
#endif
pollcount = 0;
}
f = (tentry.flags & PRTYPE);
if (((flag & PRUSERS) && (f == 0)) || /* User entry */
((flag & PRGROUPS) && (f & PRGRP))) { /* Group entry */
code = put_prentries(&tentry, bulkentries);
if (code == -1)
break; /* Filled return array */
if (code)
goto done;
}
}
code = 0;
if (i < maxentries)
*nextstartindex = i;
done:
if (code) {
if (bulkentries->prentries_val)
free(bulkentries->prentries_val);
bulkentries->prentries_val = 0;
bulkentries->prentries_len = 0;
ABORT_WITH(tt, code);
} else {
code = ubik_EndTrans(tt);
}
if (code)
return code;
return PRSUCCESS;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,194 |
krb5 | 3db8dfec1ef50ddd78d6ba9503185995876a39fd | iakerb_gss_export_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 maj;
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
/* We don't currently support exporting partially established contexts. */
if (!ctx->established)
return GSS_S_UNAVAILABLE;
maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc,
interprocess_token);
if (ctx->gssc == GSS_C_NO_CONTEXT) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return maj;
}
| 1 | CVE-2015-2698 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 6,361 |
gpac | 64a2e1b799352ac7d7aad1989bc06e7b0f2b01db |
void gitn_box_del(GF_Box *s)
{
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *)s;
if (ptr == NULL) return;
for (i=0; i<ptr->nb_entries; i++) {
if (ptr->entries[i].name) gf_free(ptr->entries[i].name);
}
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr); | 1 | CVE-2021-4043 | 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,290 |
php-src | 7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1 | SPL_METHOD(FilesystemIterator, getFlags)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));
} /* }}} */
/* {{{ proto void FilesystemIterator::setFlags(long $flags)
| 1 | CVE-2016-5770 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 5,331 |
nf | a2f18db0c68fec96631c10cad9384c196e9008ac | static int nf_tables_dump_rules(struct sk_buff *skb,
struct netlink_callback *cb)
{
const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
const struct nft_af_info *afi;
const struct nft_table *table;
const struct nft_chain *chain;
const struct nft_rule *rule;
unsigned int idx = 0, s_idx = cb->args[0];
struct net *net = sock_net(skb->sk);
int family = nfmsg->nfgen_family;
rcu_read_lock();
cb->seq = net->nft.base_seq;
list_for_each_entry_rcu(afi, &net->nft.af_info, list) {
if (family != NFPROTO_UNSPEC && family != afi->family)
continue;
list_for_each_entry_rcu(table, &afi->tables, list) {
list_for_each_entry_rcu(chain, &table->chains, list) {
list_for_each_entry_rcu(rule, &chain->rules, list) {
if (!nft_rule_is_active(net, rule))
goto cont;
if (idx < s_idx)
goto cont;
if (idx > s_idx)
memset(&cb->args[1], 0,
sizeof(cb->args) - sizeof(cb->args[0]));
if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NFT_MSG_NEWRULE,
NLM_F_MULTI | NLM_F_APPEND,
afi->family, table, chain, rule) < 0)
goto done;
nl_dump_check_consistent(cb, nlmsg_hdr(skb));
cont:
idx++;
}
}
}
}
done:
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,867 |
radare2 | bd1bab05083d80464fea854bf4b5c49aaf1b8401 | static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
size_t offset, const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
ut64 abbr_code;
size_t i;
if (cu->hdr.length > debug_str_len) {
return NULL;
}
while (buf && buf < buf_end && buf >= obuf) {
if (cu->length && cu->capacity == cu->length) {
r_bin_dwarf_expand_cu (cu);
}
buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
if (abbr_code > da->length || !buf) {
return NULL;
}
r_bin_dwarf_init_die (&cu->dies[cu->length]);
if (!abbr_code) {
cu->dies[cu->length].abbrev_code = 0;
cu->length++;
buf++;
continue;
}
cu->dies[cu->length].abbrev_code = abbr_code;
cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
abbr_code += offset;
if (da->capacity < abbr_code) {
return NULL;
}
for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
r_bin_dwarf_expand_die (&cu->dies[cu->length]);
}
if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
break;
}
memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i]));
buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
&da->decls[abbr_code - 1].specs[i],
&cu->dies[cu->length].attr_values[i],
&cu->hdr, debug_str, debug_str_len);
if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
sdb_set (s, "DW_AT_comp_dir", name, 0);
}
cu->dies[cu->length].length++;
}
cu->length++;
}
return buf;
}
| 1 | CVE-2018-14015 | 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,279 |
libxslt | ecb6bcb8d1b7e44842edde3929f412d46b40c89f | xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){
xmlNodePtr cur = NULL;
unsigned long val;
xmlChar str[20];
if (nargs == 0) {
cur = ctxt->context->node;
} else if (nargs == 1) {
xmlXPathObjectPtr obj;
xmlNodeSetPtr nodelist;
int i, ret;
if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) {
ctxt->error = XPATH_INVALID_TYPE;
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid arg expecting a node-set\n");
return;
}
obj = valuePop(ctxt);
nodelist = obj->nodesetval;
if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) {
xmlXPathFreeObject(obj);
valuePush(ctxt, xmlXPathNewCString(""));
return;
}
cur = nodelist->nodeTab[0];
for (i = 1;i < nodelist->nodeNr;i++) {
ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]);
if (ret == -1)
cur = nodelist->nodeTab[i];
}
xmlXPathFreeObject(obj);
} else {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid number of args %d\n", nargs);
ctxt->error = XPATH_INVALID_ARITY;
return;
}
/*
* Okay this is ugly but should work, use the NodePtr address
* to forge the ID
*/
val = (unsigned long)((char *)cur - (char *)0);
val /= sizeof(xmlNode);
sprintf((char *)str, "id%ld", val);
valuePush(ctxt, xmlXPathNewString(str));
} | 1 | CVE-2011-1202 | 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. | 7,993 |
Chrome | afbc71b7a78ac99810a6b22b2b0a2e85dde18794 | void OneClickSigninSyncStarter::UntrustedSigninConfirmed(
StartSyncMode response) {
if (response == UNDO_SYNC) {
CancelSigninAndDelete();
} else {
if (response == CONFIGURE_SYNC_FIRST)
start_mode_ = response;
SigninManager* signin = SigninManagerFactory::GetForProfile(profile_);
signin->CompletePendingSignin();
}
}
| 1 | CVE-2013-2879 | 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,173 |
bzrtp | bbb1e6e2f467ee4bd7b9a8c800e4f07343d7d99b | bzrtpPacket_t *bzrtp_createZrtpPacket(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, uint32_t messageType, int *exitCode) {
/* allocate packet */
bzrtpPacket_t *zrtpPacket = (bzrtpPacket_t *)malloc(sizeof(bzrtpPacket_t));
memset(zrtpPacket, 0, sizeof(bzrtpPacket_t));
zrtpPacket->messageData = NULL;
zrtpPacket->packetString = NULL;
/* initialise it */
switch(messageType) {
case MSGTYPE_HELLO:
{
int i;
bzrtpHelloMessage_t *zrtpHelloMessage = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t));
memset(zrtpHelloMessage, 0, sizeof(bzrtpHelloMessage_t));
/* initialise some fields using zrtp context data */
memcpy(zrtpHelloMessage->version, ZRTP_VERSION, 4);
strncpy((char*)zrtpHelloMessage->clientIdentifier, ZRTP_CLIENT_IDENTIFIER, 16);
memcpy(zrtpHelloMessage->H3, zrtpChannelContext->selfH[3], 32);
memcpy(zrtpHelloMessage->ZID, zrtpContext->selfZID, 12);
/* set all S,M,P flags to zero as we're not able to verify signatures, we're not a PBX(TODO: implement?), we're not passive */
zrtpHelloMessage->S = 0;
zrtpHelloMessage->M = 0;
zrtpHelloMessage->P = 0;
/* get the algorithm availabilities from the context */
zrtpHelloMessage->hc = zrtpContext->hc;
zrtpHelloMessage->cc = zrtpContext->cc;
zrtpHelloMessage->ac = zrtpContext->ac;
zrtpHelloMessage->kc = zrtpContext->kc;
zrtpHelloMessage->sc = zrtpContext->sc;
for (i=0; i<zrtpContext->hc; i++) {
zrtpHelloMessage->supportedHash[i] = zrtpContext->supportedHash[i];
}
for (i=0; i<zrtpContext->cc; i++) {
zrtpHelloMessage->supportedCipher[i] = zrtpContext->supportedCipher[i];
}
for (i=0; i<zrtpContext->ac; i++) {
zrtpHelloMessage->supportedAuthTag[i] = zrtpContext->supportedAuthTag[i];
}
for (i=0; i<zrtpContext->kc; i++) {
zrtpHelloMessage->supportedKeyAgreement[i] = zrtpContext->supportedKeyAgreement[i];
}
for (i=0; i<zrtpContext->sc; i++) {
zrtpHelloMessage->supportedSas[i] = zrtpContext->supportedSas[i];
}
/* attach the message data to the packet */
zrtpPacket->messageData = zrtpHelloMessage;
}
break; /* MSGTYPE_HELLO */
case MSGTYPE_HELLOACK :
{
/* nothing to do for the Hello ACK packet as it just contains it's type */
}
break; /* MSGTYPE_HELLOACK */
/* In case of DH commit, this one must be called after the DHPart build and the self DH message and peer Hello message are stored in the context */
case MSGTYPE_COMMIT :
{
bzrtpCommitMessage_t *zrtpCommitMessage = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t));
memset(zrtpCommitMessage, 0, sizeof(bzrtpCommitMessage_t));
/* initialise some fields using zrtp context data */
memcpy(zrtpCommitMessage->H2, zrtpChannelContext->selfH[2], 32);
memcpy(zrtpCommitMessage->ZID, zrtpContext->selfZID, 12);
zrtpCommitMessage->hashAlgo = zrtpChannelContext->hashAlgo;
zrtpCommitMessage->cipherAlgo = zrtpChannelContext->cipherAlgo;
zrtpCommitMessage->authTagAlgo = zrtpChannelContext->authTagAlgo;
zrtpCommitMessage->keyAgreementAlgo = zrtpChannelContext->keyAgreementAlgo;
zrtpCommitMessage->sasAlgo = zrtpChannelContext->sasAlgo;
/* if it is a multistream or preshared commit create a 16 random bytes nonce */
if ((zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) {
bctoolbox_rng_get(zrtpContext->RNGContext, zrtpCommitMessage->nonce, 16);
/* and the keyID for preshared commit only */
if (zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) {
/* TODO at this point we must first compute the preShared key - make sure at least rs1 is present */
/* preshared_key = hash(len(rs1) || rs1 || len(auxsecret) || auxsecret ||
len(pbxsecret) || pbxsecret) using the agreed hash and store it into the env */
/* and then the keyID : MAC(preshared_key, "Prsh") truncated to 64 bits using the agreed MAC */
}
} else { /* it's a DH commit message, set the hvi */
/* hvi = hash(initiator's DHPart2 message || responder's Hello message) using the agreed hash function truncated to 256 bits */
/* create a string with the messages concatenated */
uint16_t DHPartMessageLength = zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength;
uint16_t HelloMessageLength = zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength;
uint16_t DHPartHelloMessageStringLength = DHPartMessageLength + HelloMessageLength;
uint8_t *DHPartHelloMessageString = (uint8_t *)malloc(DHPartHelloMessageStringLength*sizeof(uint8_t));
memcpy(DHPartHelloMessageString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, DHPartMessageLength);
memcpy(DHPartHelloMessageString+DHPartMessageLength, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, HelloMessageLength);
zrtpChannelContext->hashFunction(DHPartHelloMessageString, DHPartHelloMessageStringLength, 32, zrtpCommitMessage->hvi);
free(DHPartHelloMessageString);
}
/* attach the message data to the packet */
zrtpPacket->messageData = zrtpCommitMessage;
}
break; /* MSGTYPE_COMMIT */
/* this one is called after the exchange of Hello messages when the crypto algo agreement have been performed */
case MSGTYPE_DHPART1 :
case MSGTYPE_DHPART2 :
{
uint8_t secretLength; /* is in bytes */
uint8_t bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_UNSET;
bzrtpDHPartMessage_t *zrtpDHPartMessage = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t));
memset(zrtpDHPartMessage, 0, sizeof(bzrtpDHPartMessage_t));
/* initialise some fields using zrtp context data */
memcpy(zrtpDHPartMessage->H1, zrtpChannelContext->selfH[1], 32);
/* get the retained secret from context, we anyway create a DHPart2 packet that we may turn into a DHPart1 packet if we end to
* be the responder and not the initiator, use the initiator retained secret hashes */
memcpy(zrtpDHPartMessage->rs1ID, zrtpContext->initiatorCachedSecretHash.rs1ID, 8);
memcpy(zrtpDHPartMessage->rs2ID, zrtpContext->initiatorCachedSecretHash.rs2ID, 8);
memcpy(zrtpDHPartMessage->auxsecretID, zrtpChannelContext->initiatorAuxsecretID, 8);
memcpy(zrtpDHPartMessage->pbxsecretID, zrtpContext->initiatorCachedSecretHash.pbxsecretID, 8);
/* compute the public value and insert it in the message, will then be used whatever role - initiator or responder - we assume */
/* initialise the dhm context, secret length shall be twice the size of cipher block key length - rfc section 5.1.5 */
switch (zrtpChannelContext->cipherAlgo) {
case ZRTP_CIPHER_AES3:
case ZRTP_CIPHER_2FS3:
secretLength = 64;
break;
case ZRTP_CIPHER_AES2:
case ZRTP_CIPHER_2FS2:
secretLength = 48;
break;
case ZRTP_CIPHER_AES1:
case ZRTP_CIPHER_2FS1:
default:
secretLength = 32;
break;
}
switch (zrtpChannelContext->keyAgreementAlgo) {
case ZRTP_KEYAGREEMENT_DH2k:
bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_2048;
break;
case ZRTP_KEYAGREEMENT_DH3k:
bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_3072;
break;
default:
free(zrtpPacket);
free(zrtpDHPartMessage);
*exitCode = BZRTP_CREATE_ERROR_UNABLETOCREATECRYPTOCONTEXT;
return NULL;
break;
}
zrtpContext->DHMContext = bctoolbox_CreateDHMContext(bctoolbox_keyAgreementAlgo, secretLength);
if (zrtpContext->DHMContext == NULL) {
free(zrtpPacket);
free(zrtpDHPartMessage);
*exitCode = BZRTP_CREATE_ERROR_UNABLETOCREATECRYPTOCONTEXT;
return NULL;
}
/* now compute the public value */
bctoolbox_DHMCreatePublic(zrtpContext->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, zrtpContext->RNGContext);
zrtpDHPartMessage->pv = (uint8_t *)malloc((zrtpChannelContext->keyAgreementLength)*sizeof(uint8_t));
memcpy(zrtpDHPartMessage->pv, zrtpContext->DHMContext->self, zrtpChannelContext->keyAgreementLength);
/* attach the message data to the packet */
zrtpPacket->messageData = zrtpDHPartMessage;
}
break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */
case MSGTYPE_CONFIRM1:
case MSGTYPE_CONFIRM2:
{
bzrtpConfirmMessage_t *zrtpConfirmMessage = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t));
memset(zrtpConfirmMessage, 0, sizeof(bzrtpConfirmMessage_t));
/* initialise some fields using zrtp context data */
memcpy(zrtpConfirmMessage->H0, zrtpChannelContext->selfH[0], 32);
zrtpConfirmMessage->sig_len = 0; /* signature is not supported */
zrtpConfirmMessage->cacheExpirationInterval = 0xFFFFFFFF; /* expiration interval is set to unlimited as recommended in rfc section 4.9 */
zrtpConfirmMessage->E = 0; /* we are not a PBX and then will never signal an enrollment - rfc section 7.3.1 */
zrtpConfirmMessage->V = zrtpContext->cachedSecret.previouslyVerifiedSas;
zrtpConfirmMessage->A = 0; /* Go clear message is not supported - rfc section 4.7.2 */
zrtpConfirmMessage->D = 0; /* The is no backdoor in our implementation of ZRTP - rfc section 11 */
/* generate a random CFB IV */
bctoolbox_rng_get(zrtpContext->RNGContext, zrtpConfirmMessage->CFBIV, 16);
/* attach the message data to the packet */
zrtpPacket->messageData = zrtpConfirmMessage;
}
break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */
case MSGTYPE_CONF2ACK :
{
/* nothing to do for the conf2ACK packet as it just contains it's type */
}
break; /* MSGTYPE_CONF2ACK */
case MSGTYPE_PINGACK:
{
bzrtpPingMessage_t *pingMessage;
bzrtpPingAckMessage_t *zrtpPingAckMessage;
/* to create a pingACK we must have a ping packet in the channel context, check it */
bzrtpPacket_t *pingPacket = zrtpChannelContext->pingPacket;
if (pingPacket == NULL) {
*exitCode = BZRTP_CREATE_ERROR_INVALIDCONTEXT;
return NULL;
}
pingMessage = (bzrtpPingMessage_t *)pingPacket->messageData;
/* create the message */
zrtpPingAckMessage = (bzrtpPingAckMessage_t *)malloc(sizeof(bzrtpPingAckMessage_t));
memset(zrtpPingAckMessage, 0, sizeof(bzrtpPingAckMessage_t));
/* initialise all fields using zrtp context data and the received ping message */
memcpy(zrtpPingAckMessage->version,ZRTP_VERSION , 4); /* we support version 1.10 only, so no need to even check what was sent in the ping */
memcpy(zrtpPingAckMessage->endpointHash, zrtpContext->selfZID, 8); /* as suggested in rfc section 5.16, use the truncated ZID as endPoint hash */
memcpy(zrtpPingAckMessage->endpointHashReceived, pingMessage->endpointHash, 8);
zrtpPingAckMessage->SSRC = pingPacket->sourceIdentifier;
/* attach the message data to the packet */
zrtpPacket->messageData = zrtpPingAckMessage;
} /* MSGTYPE_PINGACK */
break;
default:
free(zrtpPacket);
*exitCode = BZRTP_CREATE_ERROR_INVALIDMESSAGETYPE;
return NULL;
break;
}
zrtpPacket->sequenceNumber = 0; /* this field is not used buy the packet creator, sequence number is given as a parameter when converting
the message to a packet string(packet build). Used only when parsing a string into a packet struct */
zrtpPacket->messageType = messageType;
zrtpPacket->sourceIdentifier = zrtpChannelContext->selfSSRC;
zrtpPacket->messageLength = 0; /* length will be computed at packet build */
zrtpPacket->packetString = NULL;
*exitCode=0;
return zrtpPacket;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,616 |
libjpeg | 51c3241b6da39df30f016b63f43f31c4011222c7 | void LineBitmapRequester::ReconstructRegion(const RectAngle<LONG> &orgregion,const struct RectangleRequest *rr)
{
class ColorTrafo *ctrafo = ColorTrafoOf(false,!rr->rr_bColorTrafo);
UBYTE i;
if (m_bSubsampling && rr->rr_bUpsampling) {
for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) {
class Component *comp = m_pFrame->ComponentOf(i);
UBYTE subx = comp->SubXOf();
UBYTE suby = comp->SubYOf();
class UpsamplerBase *up; // upsampler
LONG bx,by;
RectAngle<LONG> blocks;
//
// Compute the region of blocks
assert(subx > 0 && suby > 0);
if ((up = m_ppUpsampler[i])) {
LONG bwidth = ((m_ulPixelWidth + subx - 1) / subx + 7) >> 3;
LONG bheight = ((m_ulPixelHeight + suby - 1) / suby + 7) >> 3;
LONG rx = (subx > 1)?(1):(0);
LONG ry = (suby > 1)?(1):(0);
// The +/-1 include additional lines required for subsampling expansion
blocks.ra_MinX = ((orgregion.ra_MinX / subx - rx) >> 3);
blocks.ra_MaxX = ((orgregion.ra_MaxX / subx + rx) >> 3);
blocks.ra_MinY = ((orgregion.ra_MinY / suby - ry) >> 3);
blocks.ra_MaxY = ((orgregion.ra_MaxY / suby + ry) >> 3);
// Clip.
if (blocks.ra_MinX < 0) blocks.ra_MinX = 0;
if (blocks.ra_MaxX >= bwidth) blocks.ra_MaxX = bwidth - 1;
if (blocks.ra_MinY < 0) blocks.ra_MinY = 0;
if (blocks.ra_MaxY >= bheight) blocks.ra_MaxY = bheight - 1;
up->SetBufferedRegion(blocks); // also removes the rectangle of blocks already buffered.
//
for(by = blocks.ra_MinY;by <= blocks.ra_MaxY;by++) {
for(bx = blocks.ra_MinX;bx <= blocks.ra_MaxX;bx++) {
LONG dst[64];
if (*m_pppImage[i]) {
FetchRegion(bx,*m_pppImage[i],dst);
} else {
memset(dst,0,sizeof(dst));
}
up->DefineRegion(bx,by,dst);
}
Next8Lines(i);
}
}
}
// Now push blocks into the color transformer from the upsampler.
{
RectAngle<LONG> r;
ULONG minx = orgregion.ra_MinX >> 3;
ULONG maxx = orgregion.ra_MaxX >> 3;
ULONG miny = orgregion.ra_MinY >> 3;
ULONG maxy = orgregion.ra_MaxY >> 3;
ULONG x,y;
if (maxy > m_ulMaxMCU)
maxy = m_ulMaxMCU;
for(y = miny,r.ra_MinY = orgregion.ra_MinY;y <= maxy;y++,r.ra_MinY = r.ra_MaxY + 1) {
r.ra_MaxY = (r.ra_MinY & -8) + 7;
if (r.ra_MaxY > orgregion.ra_MaxY)
r.ra_MaxY = orgregion.ra_MaxY;
for(x = minx,r.ra_MinX = orgregion.ra_MinX;x <= maxx;x++,r.ra_MinX = r.ra_MaxX + 1) {
r.ra_MaxX = (r.ra_MinX & -8) + 7;
if (r.ra_MaxX > orgregion.ra_MaxX)
r.ra_MaxX = orgregion.ra_MaxX;
for(i = 0;i < m_ucCount;i++) {
if (i >= rr->rr_usFirstComponent && i <= rr->rr_usLastComponent) {
ExtractBitmap(m_ppTempIBM[i],r,i);
if (m_ppUpsampler[i]) {
// Upsampled case, take from the upsampler, transform
// into the color buffer.
m_ppUpsampler[i]->UpsampleRegion(r,m_ppCTemp[i]);
} else if (*m_pppImage[i]) {
FetchRegion(x,*m_pppImage[i],m_ppCTemp[i]);
} else {
memset(m_ppCTemp[0],0,sizeof(LONG) * 64);
}
} else {
// Not requested, zero the buffer.
memset(m_ppCTemp[i],0,sizeof(LONG) * 64);
}
}
ctrafo->YCbCr2RGB(r,m_ppTempIBM,m_ppCTemp,NULL);
}
//
// Advance the quantized rows for the non-subsampled components,
// upsampled components have been advanced above.
for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) {
if (m_ppUpsampler[i] == NULL)
Next8Lines(i);
}
}
}
} else { // direct case, no upsampling required, residual coding possible.
RectAngle<LONG> r;
RectAngle<LONG> region = orgregion;
SubsampledRegion(region,rr);
ULONG minx = region.ra_MinX >> 3;
ULONG maxx = region.ra_MaxX >> 3;
ULONG miny = region.ra_MinY >> 3;
ULONG maxy = region.ra_MaxY >> 3;
ULONG x,y;
if (maxy > m_ulMaxMCU)
maxy = m_ulMaxMCU;
for(y = miny,r.ra_MinY = region.ra_MinY;y <= maxy;y++,r.ra_MinY = r.ra_MaxY + 1) {
r.ra_MaxY = (r.ra_MinY & -8) + 7;
if (r.ra_MaxY > region.ra_MaxY)
r.ra_MaxY = region.ra_MaxY;
for(x = minx,r.ra_MinX = region.ra_MinX;x <= maxx;x++,r.ra_MinX = r.ra_MaxX + 1) {
r.ra_MaxX = (r.ra_MinX & -8) + 7;
if (r.ra_MaxX > region.ra_MaxX)
r.ra_MaxX = region.ra_MaxX;
for(i = 0;i < m_ucCount;i++) {
LONG *dst = m_ppCTemp[i];
if (i >= rr->rr_usFirstComponent && i <= rr->rr_usLastComponent) {
ExtractBitmap(m_ppTempIBM[i],r,i);
FetchRegion(x,*m_pppImage[i],dst);
} else {
memset(dst,0,sizeof(LONG) * 64);
}
}
//
// Perform the color transformation now.
ctrafo->YCbCr2RGB(r,m_ppTempIBM,m_ppCTemp,NULL);
} // of loop over x
//
// Advance the rows.
for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) {
Next8Lines(i);
}
}
}
} | 1 | CVE-2022-32202 | 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. | 277 |
gimp | 702c4227e8b6169f781e4bb5ae4b5733f51ab126 | xcf_exit (Gimp *gimp)
{
g_return_if_fail (GIMP_IS_GIMP (gimp));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,100 |
tensorflow | 4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60 | void Compute(OpKernelContext* context) override {
const int64 axis_input = context->input(0).scalar<int64>()();
const Tensor& input_indices = context->input(1);
const Tensor& input_values = context->input(2);
const Tensor& input_shape = context->input(3);
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()),
errors::InvalidArgument(
"Input indices should be a matrix but received shape ",
input_indices.shape().DebugString()));
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()),
errors::InvalidArgument(
"Input values should be a vector but received shape ",
input_indices.shape().DebugString()));
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape.shape()),
errors::InvalidArgument(
"Input shape should be a vector but received shape ",
input_shape.shape().DebugString()));
const int64 input_rank = input_shape.vec<int64>().size();
const int64 axis = (axis_input < 0) ? input_rank + axis_input : axis_input;
OP_REQUIRES(
context, axis >= 0 && axis < input_rank,
errors::InvalidArgument("Input axis should be in range [", -input_rank,
", ", input_rank, "), got ", axis_input));
OP_REQUIRES(context,
num_split_ >= 1 && num_split_ <= input_shape.vec<int64>()(axis),
errors::InvalidArgument("Input num_split should be between 1 "
"and the splitting dimension size (",
input_shape.vec<int64>()(axis),
"), got ", num_split_));
// Prevent overflow by constructing the dense shape separately
TensorShape dense_shape;
const auto input_shape_flat = input_shape.flat<int64>();
for (int i = 0; i < input_shape.NumElements(); i++) {
OP_REQUIRES_OK(context,
dense_shape.AddDimWithStatus(input_shape_flat(i)));
}
sparse::SparseTensor sparse_tensor;
OP_REQUIRES_OK(context,
sparse::SparseTensor::Create(input_indices, input_values,
dense_shape, &sparse_tensor));
std::vector<sparse::SparseTensor> outputs;
OP_REQUIRES_OK(context, sparse::SparseTensor::Split<T>(
sparse_tensor, axis, num_split_, &outputs));
for (int slice_index = 0; slice_index < num_split_; ++slice_index) {
context->set_output(slice_index, outputs[slice_index].indices());
context->set_output(slice_index + num_split_,
outputs[slice_index].values());
Tensor* shape = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
slice_index + 2 * num_split_,
{outputs[slice_index].dims()}, &shape));
auto output_shape = outputs[slice_index].shape();
for (int dim = 0; dim < outputs[slice_index].dims(); ++dim) {
shape->vec<int64>()(dim) = output_shape[dim];
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,495 |
linux-2.6 | 3e8a0a559c66ee9e7468195691a56fefc3589740 | int dccp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int nonblock, int flags, int *addr_len)
{
const struct dccp_hdr *dh;
long timeo;
lock_sock(sk);
if (sk->sk_state == DCCP_LISTEN) {
len = -ENOTCONN;
goto out;
}
timeo = sock_rcvtimeo(sk, nonblock);
do {
struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
if (skb == NULL)
goto verify_sock_status;
dh = dccp_hdr(skb);
switch (dh->dccph_type) {
case DCCP_PKT_DATA:
case DCCP_PKT_DATAACK:
goto found_ok_skb;
case DCCP_PKT_CLOSE:
case DCCP_PKT_CLOSEREQ:
if (!(flags & MSG_PEEK))
dccp_finish_passive_close(sk);
/* fall through */
case DCCP_PKT_RESET:
dccp_pr_debug("found fin (%s) ok!\n",
dccp_packet_name(dh->dccph_type));
len = 0;
goto found_fin_ok;
default:
dccp_pr_debug("packet_type=%s\n",
dccp_packet_name(dh->dccph_type));
sk_eat_skb(sk, skb, 0);
}
verify_sock_status:
if (sock_flag(sk, SOCK_DONE)) {
len = 0;
break;
}
if (sk->sk_err) {
len = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN) {
len = 0;
break;
}
if (sk->sk_state == DCCP_CLOSED) {
if (!sock_flag(sk, SOCK_DONE)) {
/* This occurs when user tries to read
* from never connected socket.
*/
len = -ENOTCONN;
break;
}
len = 0;
break;
}
if (!timeo) {
len = -EAGAIN;
break;
}
if (signal_pending(current)) {
len = sock_intr_errno(timeo);
break;
}
sk_wait_data(sk, &timeo);
continue;
found_ok_skb:
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len)) {
/* Exception. Bailout! */
len = -EFAULT;
break;
}
found_fin_ok:
if (!(flags & MSG_PEEK))
sk_eat_skb(sk, skb, 0);
break;
} while (1);
out:
release_sock(sk);
return len;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,908 |
libtiff | c8d613ef497058fe653c467fc84c70a62a4a71b2 | gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
{
TIFF* tif = img->tif;
tileContigRoutine put = img->put.contig;
uint32 col, row, y, rowstoread;
tmsize_t pos;
uint32 tw, th;
unsigned char* buf = NULL;
int32 fromskew, toskew;
uint32 nrow;
int ret = 1, flip;
uint32 this_tw, tocol;
int32 this_toskew, leftmost_toskew;
int32 leftmost_fromskew;
uint32 leftmost_tw;
tmsize_t bufsize;
bufsize = TIFFTileSize(tif);
if (bufsize == 0) {
TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer");
return (0);
}
TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
flip = setorientation(img);
if (flip & FLIP_VERTICALLY) {
if ((tw + w) > INT_MAX) {
TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "unsupported tile size (too wide)");
return (0);
}
y = h - 1;
toskew = -(int32)(tw + w);
}
else {
if (tw > (INT_MAX + w)) {
TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "unsupported tile size (too wide)");
return (0);
}
y = 0;
toskew = -(int32)(tw - w);
}
/*
* Leftmost tile is clipped on left side if col_offset > 0.
*/
leftmost_fromskew = img->col_offset % tw;
leftmost_tw = tw - leftmost_fromskew;
leftmost_toskew = toskew + leftmost_fromskew;
for (row = 0; ret != 0 && row < h; row += nrow)
{
rowstoread = th - (row + img->row_offset) % th;
nrow = (row + rowstoread > h ? h - row : rowstoread);
fromskew = leftmost_fromskew;
this_tw = leftmost_tw;
this_toskew = leftmost_toskew;
tocol = 0;
col = img->col_offset;
while (tocol < w)
{
if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col,
row+img->row_offset, 0, 0)==(tmsize_t)(-1) &&
(buf == NULL || img->stoponerr))
{
ret = 0;
break;
}
pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \
((tmsize_t) fromskew * img->samplesperpixel);
if (tocol + this_tw > w)
{
/*
* Rightmost tile is clipped on right side.
*/
fromskew = tw - (w - tocol);
this_tw = tw - fromskew;
this_toskew = toskew + fromskew;
}
(*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos);
tocol += this_tw;
col += this_tw;
/*
* After the leftmost tile, tiles are no longer clipped on left side.
*/
fromskew = 0;
this_tw = tw;
this_toskew = toskew;
}
y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow);
}
_TIFFfree(buf);
if (flip & FLIP_HORIZONTALLY) {
uint32 line;
for (line = 0; line < h; line++) {
uint32 *left = raster + (line * w);
uint32 *right = left + w - 1;
while ( left < right ) {
uint32 temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
}
return (ret);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,629 |
linux | bf118a342f10dafe44b14451a1392c3254629a1f | static void buf_to_pages(const void *buf, size_t buflen,
struct page **pages, unsigned int *pgbase)
{
const void *p = buf;
*pgbase = offset_in_page(buf);
p -= *pgbase;
while (p < buf + buflen) {
*(pages++) = virt_to_page(p);
p += PAGE_CACHE_SIZE;
}
}
| 1 | CVE-2011-4131 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 4,561 |
samba | d724f835acb9f4886c0001af32cd325dbbf1f895 | static NTSTATUS do_connect(TALLOC_CTX *ctx,
const char *server,
const char *share,
const struct user_auth_info *auth_info,
bool show_sessetup,
bool force_encrypt,
int max_protocol,
int port,
int name_type,
struct cli_state **pcli)
{
struct cli_state *c = NULL;
char *servicename;
char *sharename;
char *newserver, *newshare;
const char *username;
const char *password;
const char *domain;
NTSTATUS status;
int flags = 0;
/* make a copy so we don't modify the global string 'service' */
servicename = talloc_strdup(ctx,share);
sharename += 2;
if (server == NULL) {
server = sharename;
}
sharename = strchr_m(sharename,'\\');
if (!sharename) {
return NT_STATUS_NO_MEMORY;
}
*sharename = 0;
sharename++;
}
| 1 | CVE-2015-5296 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 4,132 |
Android | 95610818918f6f11fe7d23aca1380e6c0fac2af0 | bool RilSapSocket::SocketExists(const char *socketName) {
RilSapSocketList* current = head;
while(NULL != current) {
if(strcmp(current->socket->name, socketName) == 0) {
return true;
}
current = current->next;
}
return false;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,160 |
booth | 35bf0b7b048d715f671eb68974fb6b4af6528c67 | static inline int is_root(void)
{
return geteuid() == 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,741 |
vim | 5f25c3855071bd7e26255c68bf458b1b5cf92f39 | compile_parenthesis(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
{
int ret;
char_u *p = *arg + 1;
if (may_get_next_line_error(p, arg, cctx) == FAIL)
return FAIL;
if (ppconst->pp_used <= PPSIZE - 10)
{
ret = compile_expr1(arg, cctx, ppconst);
}
else
{
// Not enough space in ppconst, flush constants.
if (generate_ppconst(cctx, ppconst) == FAIL)
return FAIL;
ret = compile_expr0(arg, cctx);
}
if (may_get_next_line_error(*arg, arg, cctx) == FAIL)
return FAIL;
if (**arg == ')')
++*arg;
else if (ret == OK)
{
emsg(_(e_missing_closing_paren));
ret = FAIL;
}
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,331 |
ipmitool | 41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22 | static void print_session_info(const struct get_session_info_rsp * session_info,
int data_len)
{
if (csv_output)
print_session_info_csv(session_info, data_len);
else
print_session_info_verbose(session_info, data_len);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,797 |
contiki-ng | 9cdec6e19865d7b0d8caf61f1a34001f64d565b0 | uipbuf_clear_attr(void)
{
/* set everything to "defaults" */
memcpy(uipbuf_attrs, uipbuf_default_attrs, sizeof(uipbuf_attrs));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,672 |
wireshark | 5efb45231671baa2db2011d8f67f9d6e72bc455b | parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
| 1 | CVE-2016-5355 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 8,906 |
nettle | 971bed6ab4b27014eb23085e8176917e1a096fd5 | equal_h (const struct ecc_modulo *p,
const mp_limb_t *x1, const mp_limb_t *z1,
const mp_limb_t *x2, const mp_limb_t *z2,
mp_limb_t *scratch)
{
#define t0 scratch
#define t1 (scratch + p->size)
ecc_mod_mul_canonical (p, t0, x1, z2, t0);
ecc_mod_mul_canonical (p, t1, x2, z1, t1);
return mpn_cmp (t0, t1, p->size) == 0;
#undef t0
#undef t1
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,545 |
varnish-cache | 176f8a075a963ffbfa56f1c460c15f6a1a6af5a7 | vbf_allocobj(struct busyobj *bo, unsigned l)
{
struct objcore *oc;
const struct stevedore *stv;
double lifetime;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
oc = bo->fetch_objcore;
CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC);
lifetime = oc->ttl + oc->grace + oc->keep;
if (bo->uncacheable || lifetime < cache_param->shortlived)
stv = stv_transient;
else
stv = bo->storage;
bo->storage = NULL;
bo->storage_hint = NULL;
if (stv == NULL)
return (0);
if (STV_NewObject(bo->wrk, bo->fetch_objcore, stv, l))
return (1);
if (stv == stv_transient)
return (0);
/*
* Try to salvage the transaction by allocating a shortlived object
* on Transient storage.
*/
if (oc->ttl > cache_param->shortlived)
oc->ttl = cache_param->shortlived;
oc->grace = 0.0;
oc->keep = 0.0;
return (STV_NewObject(bo->wrk, bo->fetch_objcore, stv_transient, l));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,267 |
qemu | 46609b90d9e3a6304def11038a76b58ff43f77bc | static void test_sense_interrupt(void)
{
int drive = 0;
int head = 0;
int cyl = 0;
int ret = 0;
floppy_send(CMD_SENSE_INT);
ret = floppy_recv();
g_assert(ret == 0x80);
floppy_send(CMD_SEEK);
floppy_send(head << 2 | drive);
g_assert(!get_irq(FLOPPY_IRQ));
floppy_send(cyl);
floppy_send(CMD_SENSE_INT);
ret = floppy_recv();
g_assert(ret == 0x20);
floppy_recv();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,288 |
linux | 06bd3c36a733ac27962fea7d6f47168841376824 | int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk,
unsigned int map_len, struct extent_status *result)
{
struct ext4_map_blocks map;
struct extent_status es = {};
int ret;
map.m_lblk = lblk;
map.m_len = map_len;
/*
* For non-extent based files this loop may iterate several times since
* we do not determine full hole size.
*/
while (map.m_len > 0) {
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
return ret;
/* There's extent covering m_lblk? Just return it. */
if (ret > 0) {
int status;
ext4_es_store_pblock(result, map.m_pblk);
result->es_lblk = map.m_lblk;
result->es_len = map.m_len;
if (map.m_flags & EXT4_MAP_UNWRITTEN)
status = EXTENT_STATUS_UNWRITTEN;
else
status = EXTENT_STATUS_WRITTEN;
ext4_es_store_status(result, status);
return 1;
}
ext4_es_find_delayed_extent_range(inode, map.m_lblk,
map.m_lblk + map.m_len - 1,
&es);
/* Is delalloc data before next block in extent tree? */
if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) {
ext4_lblk_t offset = 0;
if (es.es_lblk < lblk)
offset = lblk - es.es_lblk;
result->es_lblk = es.es_lblk + offset;
ext4_es_store_pblock(result,
ext4_es_pblock(&es) + offset);
result->es_len = es.es_len - offset;
ext4_es_store_status(result, ext4_es_status(&es));
return 1;
}
/* There's a hole at m_lblk, advance us after it */
map.m_lblk += map.m_len;
map_len -= map.m_len;
map.m_len = map_len;
cond_resched();
}
result->es_len = 0;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,189 |
univention-corporate-server | a28053045bd2e778c50ed1acaf4e52e1e34f6e34 | int data_on_connection(int fd, callback_remove_handler remove)
{
int nread;
char *network_packet;
char network_line[8192];
char *p;
unsigned long id;
char string[1024];
unsigned long msg_id = UINT32_MAX;
enum network_protocol version = network_client_get_version(fd);
ioctl(fd, FIONREAD, &nread);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "new connection data = %d\n",nread);
if(nread == 0)
{
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "%d failed, got 0 close connection to listener ", fd);
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
network_client_dump ();
return 0;
}
if ( nread >= 8192 ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, more than 8192 close connection to listener ", fd);
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
return 0;
}
/* read the whole package */
network_packet=malloc((nread+1) * sizeof(char));
read(fd, network_packet, nread);
network_packet[nread]='\0';
memset(network_line, 0, 8192);
p=network_packet;
p_sem(sem_id);
while ( get_network_line(p, network_line) ) {
if ( strlen(network_line) > 0 ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "line = [%s]",network_line);
}
if ( !strncmp(network_line, "MSGID: ", strlen("MSGID: ")) ) {
/* read message id */
msg_id=strtoul(&(network_line[strlen("MSGID: ")]), NULL, 10);
p+=strlen(network_line);
} else if ( !strncmp(network_line, "Version: ", strlen("Version: ")) ) {
char *head = network_line, *end;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: VERSION");
version = strtoul(head + 9, &end, 10);
if (!head[9] || *end)
goto failed;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "VERSION=%d", version);
if (version < network_procotol_version) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Forbidden VERSION=%d < %d, close connection to listener", version, network_procotol_version);
goto close;
} else if (version >= PROTOCOL_LAST) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Future VERSION=%d", version);
version = PROTOCOL_LAST - 1;
}
network_client_set_version(fd, version);
/* reset message id */
msg_id = UINT32_MAX;
p+=strlen(network_line);
} else if ( !strncmp(network_line, "Capabilities: ", strlen("Capabilities: ")) ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: Capabilities");
if ( version > PROTOCOL_UNKNOWN ) {
memset(string, 0, sizeof(string));
snprintf(string, sizeof(string), "Version: %d\nCapabilities: \n\n", version);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "SEND: %s", string);
write(fd, string, strlen(string));
} else {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "Capabilities recv, but no version line");
}
p+=strlen(network_line);
} else if ( !strncmp(network_line, "GET_DN ", strlen("GET_DN ")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_DN");
id=strtoul(&(network_line[strlen("GET_DN ")]), NULL, 10);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld",id);
if ( id <= notify_last_id.id) {
char *dn_string = NULL;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "try to read %ld from cache", id);
/* try to read from cache */
if ( (dn_string = notifier_cache_get(id)) == NULL ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld not found in cache", id);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld get one dn", id);
/* read from transaction file, because not in cache */
if( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld failed ", id);
/* TODO: maybe close connection? */
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, close connection to listener ", fd);
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
return 0;
}
}
if ( dn_string != NULL ) {
snprintf(string, sizeof(string), "MSGID: %ld\n%s\n\n",msg_id,dn_string);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string);
write(fd, string, strlen(string));
free(dn_string);
}
} else {
/* set wanted id */
network_client_set_next_id(fd, id);
network_client_set_msg_id(fd, msg_id);
}
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else if (!strncmp(p, "WAIT_ID ", 8) && msg_id != UINT32_MAX && version >= PROTOCOL_3) {
char *head = network_line, *end;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: WAIT_ID");
id = strtoul(head + 8, &end, 10);
if (!head[8] || *end)
goto failed;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld", id);
if (id <= notify_last_id.id) {
snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n", msg_id, notify_last_id.id);
write(fd, string, strlen(string));
} else {
/* set wanted id */
network_client_set_next_id(fd, id);
network_client_set_msg_id(fd, msg_id);
}
p += strlen(network_line) + 1;
msg_id = UINT32_MAX;
} else if ( !strncmp(network_line, "GET_ID", strlen("GET_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_ID");
memset(string, 0, sizeof(string));
snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,notify_last_id.id);
write(fd, string, strlen(string));
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else if ( !strncmp(network_line, "GET_SCHEMA_ID", strlen("GET_SCHEMA_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_SCHEMA_ID");
memset(string, 0, sizeof(string));
snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,SCHEMA_ID);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string);
write(fd, string, strlen(string));
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else if ( !strncmp(network_line, "ALIVE", strlen("ALIVE")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: ALIVE");
snprintf(string, sizeof(string), "MSGID: %ld\nOKAY\n\n",msg_id);
write(fd, string, strlen(string));
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else {
p+=strlen(network_line);
if (strlen(network_line) == 0 ) {
p+=1;
} else {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "Drop package [%s]", network_line);
}
}
}
v_sem(sem_id);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "END Package");
network_client_dump ();
return 0;
failed:
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Failed parsing [%s]", p);
close:
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
return 0;
} | 1 | CVE-2019-1010283 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 4,939 |
linux | f6d8bd051c391c1c0458a30b2a7abcd939329259 | static int do_ip_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct inet_sock *inet = inet_sk(sk);
int val;
int len;
if (level != SOL_IP)
return -EOPNOTSUPP;
if (ip_mroute_opt(optname))
return ip_mroute_getsockopt(sk, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
unsigned char optbuf[sizeof(struct ip_options)+40];
struct ip_options * opt = (struct ip_options *)optbuf;
opt->optlen = 0;
if (inet->opt)
memcpy(optbuf, inet->opt,
sizeof(struct ip_options)+
inet->opt->optlen);
release_sock(sk);
if (opt->optlen == 0)
return put_user(0, optlen);
ip_options_undo(opt);
len = min_t(unsigned int, len, opt->optlen);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, opt->__data, len))
return -EFAULT;
return 0;
}
case IP_PKTINFO:
val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0;
break;
case IP_RECVTTL:
val = (inet->cmsg_flags & IP_CMSG_TTL) != 0;
break;
case IP_RECVTOS:
val = (inet->cmsg_flags & IP_CMSG_TOS) != 0;
break;
case IP_RECVOPTS:
val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0;
break;
case IP_RETOPTS:
val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0;
break;
case IP_PASSSEC:
val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0;
break;
case IP_RECVORIGDSTADDR:
val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0;
break;
case IP_TOS:
val = inet->tos;
break;
case IP_TTL:
val = (inet->uc_ttl == -1 ?
sysctl_ip_default_ttl :
inet->uc_ttl);
break;
case IP_HDRINCL:
val = inet->hdrincl;
break;
case IP_NODEFRAG:
val = inet->nodefrag;
break;
case IP_MTU_DISCOVER:
val = inet->pmtudisc;
break;
case IP_MTU:
{
struct dst_entry *dst;
val = 0;
dst = sk_dst_get(sk);
if (dst) {
val = dst_mtu(dst);
dst_release(dst);
}
if (!val) {
release_sock(sk);
return -ENOTCONN;
}
break;
}
case IP_RECVERR:
val = inet->recverr;
break;
case IP_MULTICAST_TTL:
val = inet->mc_ttl;
break;
case IP_MULTICAST_LOOP:
val = inet->mc_loop;
break;
case IP_MULTICAST_IF:
{
struct in_addr addr;
len = min_t(unsigned int, len, sizeof(struct in_addr));
addr.s_addr = inet->mc_addr;
release_sock(sk);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &addr, len))
return -EFAULT;
return 0;
}
case IP_MSFILTER:
{
struct ip_msfilter msf;
int err;
if (len < IP_MSFILTER_SIZE(0)) {
release_sock(sk);
return -EINVAL;
}
if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) {
release_sock(sk);
return -EFAULT;
}
err = ip_mc_msfget(sk, &msf,
(struct ip_msfilter __user *)optval, optlen);
release_sock(sk);
return err;
}
case MCAST_MSFILTER:
{
struct group_filter gsf;
int err;
if (len < GROUP_FILTER_SIZE(0)) {
release_sock(sk);
return -EINVAL;
}
if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) {
release_sock(sk);
return -EFAULT;
}
err = ip_mc_gsfget(sk, &gsf,
(struct group_filter __user *)optval,
optlen);
release_sock(sk);
return err;
}
case IP_MULTICAST_ALL:
val = inet->mc_all;
break;
case IP_PKTOPTIONS:
{
struct msghdr msg;
release_sock(sk);
if (sk->sk_type != SOCK_STREAM)
return -ENOPROTOOPT;
msg.msg_control = optval;
msg.msg_controllen = len;
msg.msg_flags = 0;
if (inet->cmsg_flags & IP_CMSG_PKTINFO) {
struct in_pktinfo info;
info.ipi_addr.s_addr = inet->inet_rcv_saddr;
info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr;
info.ipi_ifindex = inet->mc_index;
put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info);
}
if (inet->cmsg_flags & IP_CMSG_TTL) {
int hlim = inet->mc_ttl;
put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim);
}
len -= msg.msg_controllen;
return put_user(len, optlen);
}
case IP_FREEBIND:
val = inet->freebind;
break;
case IP_TRANSPARENT:
val = inet->transparent;
break;
case IP_MINTTL:
val = inet->min_ttl;
break;
default:
release_sock(sk);
return -ENOPROTOOPT;
}
release_sock(sk);
if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) {
unsigned char ucval = (unsigned char)val;
len = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &ucval, 1))
return -EFAULT;
} else {
len = min_t(unsigned int, sizeof(int), len);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
}
return 0;
}
| 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 | 5,190 |
linux | 8c55dedb795be8ec0cf488f98c03a1c2176f7fb1 | static bool rtl_get_fwlps_doze(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
u32 ps_timediff;
ps_timediff = jiffies_to_msecs(jiffies -
ppsc->last_delaylps_stamp_jiffies);
if (ps_timediff < 2000) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"Delay enter Fw LPS for DHCP, ARP, or EAPOL exchanging state\n");
return false;
}
if (mac->link_state != MAC80211_LINKED)
return false;
if (mac->opmode == NL80211_IFTYPE_ADHOC)
return false;
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,513 |
ImageMagick | ee5b9c56b9ca18ed0750f8a15e0d1a6da92a6e99 | static void TimeCodeToString(const size_t timestamp,char *code)
{
#define TimeFields 7
unsigned int
shift;
register ssize_t
i;
*code='\0';
shift=4*TimeFields;
for (i=0; i <= TimeFields; i++)
{
(void) FormatLocaleString(code,MagickPathExtent-strlen(code),"%x",
(unsigned int) ((timestamp >> shift) & 0x0fU));
code++;
if (((i % 2) != 0) && (i < TimeFields))
*code++=':';
shift-=4;
*code='\0';
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,113 |
libarchive | dfd6b54ce33960e420fb206d8872fb759b577ad9 | clear_nochange_fflags(struct archive_write_disk *a)
{
int nochange_flags;
mode_t mode = archive_entry_mode(a->entry);
/* Hopefully, the compiler will optimize this mess into a constant. */
nochange_flags = 0;
#ifdef SF_IMMUTABLE
nochange_flags |= SF_IMMUTABLE;
#endif
#ifdef UF_IMMUTABLE
nochange_flags |= UF_IMMUTABLE;
#endif
#ifdef SF_APPEND
nochange_flags |= SF_APPEND;
#endif
#ifdef UF_APPEND
nochange_flags |= UF_APPEND;
#endif
#ifdef EXT2_APPEND_FL
nochange_flags |= EXT2_APPEND_FL;
#endif
#ifdef EXT2_IMMUTABLE_FL
nochange_flags |= EXT2_IMMUTABLE_FL;
#endif
return (set_fflags_platform(a, a->fd, a->name, mode, 0, nochange_flags));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,622 |
linux | 6b8ac63847bc2f958dd93c09edc941a0118992d9 | vc4_wait_for_seqno_ioctl_helper(struct drm_device *dev,
uint64_t seqno,
uint64_t *timeout_ns)
{
unsigned long start = jiffies;
int ret = vc4_wait_for_seqno(dev, seqno, *timeout_ns, true);
if ((ret == -EINTR || ret == -ERESTARTSYS) && *timeout_ns != ~0ull) {
uint64_t delta = jiffies_to_nsecs(jiffies - start);
if (*timeout_ns >= delta)
*timeout_ns -= delta;
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,681 |
Chrome | 828eab2216a765dea92575c290421c115b8ad028 | void VerifyDailyContentLengthPrefLists(
const int64* original_values, size_t original_count,
const int64* received_values, size_t received_count,
const int64* original_with_data_reduction_proxy_enabled_values,
size_t original_with_data_reduction_proxy_enabled_count,
const int64* received_with_data_reduction_proxy_enabled_values,
size_t received_with_data_reduction_proxy_count,
const int64* original_via_data_reduction_proxy_values,
size_t original_via_data_reduction_proxy_count,
const int64* received_via_data_reduction_proxy_values,
size_t received_via_data_reduction_proxy_count) {
VerifyPrefList(prefs::kDailyHttpOriginalContentLength,
original_values, original_count);
VerifyPrefList(prefs::kDailyHttpReceivedContentLength,
received_values, received_count);
VerifyPrefList(
prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled,
original_with_data_reduction_proxy_enabled_values,
original_with_data_reduction_proxy_enabled_count);
VerifyPrefList(
prefs::kDailyContentLengthWithDataReductionProxyEnabled,
received_with_data_reduction_proxy_enabled_values,
received_with_data_reduction_proxy_count);
VerifyPrefList(
prefs::kDailyOriginalContentLengthViaDataReductionProxy,
original_via_data_reduction_proxy_values,
original_via_data_reduction_proxy_count);
VerifyPrefList(
prefs::kDailyContentLengthViaDataReductionProxy,
received_via_data_reduction_proxy_values,
received_via_data_reduction_proxy_count);
}
| 1 | CVE-2013-2858 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 1,134 |
Singular | 5f28fbf066626fa9c4a8f0e6408c0bb362fb386c | void sdb_show_bp()
{
for(int i=0; i<7;i++)
if (sdb_lines[i]!= -1)
Print("Breakpoint %d: %s::%d\n",i+1,sdb_files[i],sdb_lines[i]);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,638 |
openexr | 74504503cff86e986bac441213c403b0ba28d58f | generatePreview (const char inFileName[],
float exposure,
int previewWidth,
int &previewHeight,
Array2D <PreviewRgba> &previewPixels)
{
//
// Read the input file
//
RgbaInputFile in (inFileName);
Box2i dw = in.dataWindow();
float a = in.pixelAspectRatio();
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
Array2D <Rgba> pixels (h, w);
in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);
in.readPixels (dw.min.y, dw.max.y);
//
// Make a preview image
//
previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
previewPixels.resizeErase (previewHeight, previewWidth);
float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;
float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;
float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
for (int y = 0; y < previewHeight; ++y)
{
for (int x = 0; x < previewWidth; ++x)
{
PreviewRgba &preview = previewPixels[y][x];
const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];
preview.r = gamma (pixel.r, m);
preview.g = gamma (pixel.g, m);
preview.b = gamma (pixel.b, m);
preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);
}
}
} | 1 | CVE-2020-16588 | 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. | 9,767 |
Chrome | 6b5f83842b5edb5d4bd6684b196b3630c6769731 | InstalledBubbleContent(Browser* browser,
const Extension* extension,
ExtensionInstalledBubble::BubbleType type,
SkBitmap* icon,
ExtensionInstalledBubble* bubble)
: browser_(browser),
extension_id_(extension->id()),
bubble_(bubble),
type_(type),
info_(NULL) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont);
gfx::Size size(icon->width(), icon->height());
if (size.width() > kIconSize || size.height() > kIconSize)
size = gfx::Size(kIconSize, kIconSize);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
string16 extension_name = UTF8ToUTF16(extension->name());
base::i18n::AdjustStringForLocaleDirection(&extension_name);
heading_ = new views::Label(l10n_util::GetStringFUTF16(
IDS_EXTENSION_INSTALLED_HEADING,
extension_name,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
heading_->SetFont(rb.GetFont(ResourceBundle::MediumFont));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
switch (type_) {
case ExtensionInstalledBubble::PAGE_ACTION: {
info_ = new views::Label(l10n_util::GetStringUTF16(
IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO));
info_->SetFont(font);
info_->SetMultiLine(true);
info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(info_);
break;
}
case ExtensionInstalledBubble::OMNIBOX_KEYWORD: {
info_ = new views::Label(l10n_util::GetStringFUTF16(
IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO,
UTF8ToUTF16(extension->omnibox_keyword())));
info_->SetFont(font);
info_->SetMultiLine(true);
info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(info_);
break;
}
case ExtensionInstalledBubble::APP: {
views::Link* link = new views::Link(
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_APP_INFO));
link->set_listener(this);
manage_ = link;
manage_->SetFont(font);
manage_->SetMultiLine(true);
manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(manage_);
break;
}
default:
break;
}
if (type_ != ExtensionInstalledBubble::APP) {
manage_ = new views::Label(
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_MANAGE_INFO));
manage_->SetFont(font);
manage_->SetMultiLine(true);
manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(manage_);
}
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetBitmapNamed(IDR_CLOSE_BAR));
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetBitmapNamed(IDR_CLOSE_BAR_H));
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetBitmapNamed(IDR_CLOSE_BAR_P));
AddChildView(close_button_);
}
| 1 | CVE-2011-3104 | 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). | 421 |
Android | 5a9753fca56f0eeb9f61e342b2fccffc364f9426 | void fht16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fht16x16_c(in, out, stride, tx_type);
}
| 1 | CVE-2016-1621 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,034 |
linux | f9432c5ec8b1e9a09b9b0e5569e3c73db8de432a | static void rfcomm_tty_send_xchar(struct tty_struct *tty, char ch)
{
BT_DBG("tty %p ch %c", tty, ch);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,228 |
ceph | 8f396cf35a3826044b089141667a196454c0a587 | int CephxSessionHandler::sign_message(Message *m)
{
// If runtime signing option is off, just return success without signing.
if (!cct->_conf->cephx_sign_messages) {
return 0;
}
uint64_t sig;
int r = _calc_signature(m, &sig);
if (r < 0)
return r;
ceph_msg_footer& f = m->get_footer();
f.sig = sig;
f.flags = (unsigned)f.flags | CEPH_MSG_FOOTER_SIGNED;
ldout(cct, 20) << "Putting signature in client message(seq # " << m->get_seq()
<< "): sig = " << sig << dendl;
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,141 |
Android | 9fe27a9b445f7e911286ed31c1087ceac567736b | void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) {
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
MX_FRAME* p_rx_frame = &rfc_cb.rfc.rx_frame;
uint16_t length = p_buf->len;
uint8_t ea, cr, mx_len;
bool is_command;
if (length < 2) {
RFCOMM_TRACE_ERROR(
"%s: Illegal MX Frame len when reading EA, C/R. len:%d < 2", __func__,
length);
android_errorWriteLog(0x534e4554, "111937065");
osi_free(p_buf);
return;
}
p_rx_frame->ea = *p_data & RFCOMM_EA;
p_rx_frame->cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR;
p_rx_frame->type = *p_data++ & ~(RFCOMM_CR_MASK | RFCOMM_EA_MASK);
if (!p_rx_frame->ea || !length) {
LOG(ERROR) << __func__
<< ": Invalid MX frame ea=" << std::to_string(p_rx_frame->ea)
<< ", len=" << length << ", bd_addr=" << p_mcb->bd_addr;
osi_free(p_buf);
return;
}
length--;
is_command = p_rx_frame->cr;
ea = *p_data & RFCOMM_EA;
mx_len = *p_data++ >> RFCOMM_SHIFT_LENGTH1;
length--;
if (!ea) {
if (length < 1) {
RFCOMM_TRACE_ERROR("%s: Illegal MX Frame when EA = 0. len:%d < 1",
__func__, length);
android_errorWriteLog(0x534e4554, "111937065");
osi_free(p_buf);
return;
}
mx_len += *p_data++ << RFCOMM_SHIFT_LENGTH2;
length--;
}
if (mx_len != length) {
LOG(ERROR) << __func__ << ": Bad MX frame, p_mcb=" << p_mcb
<< ", bd_addr=" << p_mcb->bd_addr;
osi_free(p_buf);
return;
}
RFCOMM_TRACE_DEBUG("%s: type=%d, p_mcb=%p", __func__, p_rx_frame->type,
p_mcb);
switch (p_rx_frame->type) {
case RFCOMM_MX_PN:
if (length != RFCOMM_MX_PN_LEN) {
LOG(ERROR) << __func__ << ": Invalid PN length, p_mcb=" << p_mcb
<< ", bd_addr=" << p_mcb->bd_addr;
break;
}
p_rx_frame->dlci = *p_data++ & RFCOMM_PN_DLCI_MASK;
p_rx_frame->u.pn.frame_type = *p_data & RFCOMM_PN_FRAME_TYPE_MASK;
p_rx_frame->u.pn.conv_layer = *p_data++ & RFCOMM_PN_CONV_LAYER_MASK;
p_rx_frame->u.pn.priority = *p_data++ & RFCOMM_PN_PRIORITY_MASK;
p_rx_frame->u.pn.t1 = *p_data++;
p_rx_frame->u.pn.mtu = *p_data + (*(p_data + 1) << 8);
p_data += 2;
p_rx_frame->u.pn.n2 = *p_data++;
p_rx_frame->u.pn.k = *p_data++ & RFCOMM_PN_K_MASK;
if (!p_rx_frame->dlci || !RFCOMM_VALID_DLCI(p_rx_frame->dlci) ||
(p_rx_frame->u.pn.mtu < RFCOMM_MIN_MTU) ||
(p_rx_frame->u.pn.mtu > RFCOMM_MAX_MTU)) {
LOG(ERROR) << __func__ << ": Bad PN frame, p_mcb=" << p_mcb
<< ", bd_addr=" << p_mcb->bd_addr;
break;
}
osi_free(p_buf);
rfc_process_pn(p_mcb, is_command, p_rx_frame);
return;
case RFCOMM_MX_TEST:
if (!length) break;
p_rx_frame->u.test.p_data = p_data;
p_rx_frame->u.test.data_len = length;
p_buf->offset += 2;
p_buf->len -= 2;
if (is_command)
rfc_send_test(p_mcb, false, p_buf);
else
rfc_process_test_rsp(p_mcb, p_buf);
return;
case RFCOMM_MX_FCON:
if (length != RFCOMM_MX_FCON_LEN) break;
osi_free(p_buf);
rfc_process_fcon(p_mcb, is_command);
return;
case RFCOMM_MX_FCOFF:
if (length != RFCOMM_MX_FCOFF_LEN) break;
osi_free(p_buf);
rfc_process_fcoff(p_mcb, is_command);
return;
case RFCOMM_MX_MSC:
if (length != RFCOMM_MX_MSC_LEN_WITH_BREAK &&
length != RFCOMM_MX_MSC_LEN_NO_BREAK) {
RFCOMM_TRACE_ERROR("%s: Illegal MX MSC Frame len:%d", __func__, length);
android_errorWriteLog(0x534e4554, "111937065");
osi_free(p_buf);
return;
}
ea = *p_data & RFCOMM_EA;
cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR;
p_rx_frame->dlci = *p_data++ >> RFCOMM_SHIFT_DLCI;
if (!ea || !cr || !p_rx_frame->dlci ||
!RFCOMM_VALID_DLCI(p_rx_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad MSC frame");
break;
}
p_rx_frame->u.msc.signals = *p_data++;
if (mx_len == RFCOMM_MX_MSC_LEN_WITH_BREAK) {
p_rx_frame->u.msc.break_present =
*p_data & RFCOMM_MSC_BREAK_PRESENT_MASK;
p_rx_frame->u.msc.break_duration =
(*p_data & RFCOMM_MSC_BREAK_MASK) >> RFCOMM_MSC_SHIFT_BREAK;
} else {
p_rx_frame->u.msc.break_present = false;
p_rx_frame->u.msc.break_duration = 0;
}
osi_free(p_buf);
rfc_process_msc(p_mcb, is_command, p_rx_frame);
return;
case RFCOMM_MX_NSC:
if ((length != RFCOMM_MX_NSC_LEN) || !is_command) break;
p_rx_frame->u.nsc.ea = *p_data & RFCOMM_EA;
p_rx_frame->u.nsc.cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR;
p_rx_frame->u.nsc.type = *p_data++ >> RFCOMM_SHIFT_DLCI;
osi_free(p_buf);
rfc_process_nsc(p_mcb, p_rx_frame);
return;
case RFCOMM_MX_RPN:
if ((length != RFCOMM_MX_RPN_REQ_LEN) && (length != RFCOMM_MX_RPN_LEN))
break;
ea = *p_data & RFCOMM_EA;
cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR;
p_rx_frame->dlci = *p_data++ >> RFCOMM_SHIFT_DLCI;
if (!ea || !cr || !p_rx_frame->dlci ||
!RFCOMM_VALID_DLCI(p_rx_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad RPN frame");
break;
}
p_rx_frame->u.rpn.is_request = (length == RFCOMM_MX_RPN_REQ_LEN);
if (!p_rx_frame->u.rpn.is_request) {
p_rx_frame->u.rpn.baud_rate = *p_data++;
p_rx_frame->u.rpn.byte_size =
(*p_data >> RFCOMM_RPN_BITS_SHIFT) & RFCOMM_RPN_BITS_MASK;
p_rx_frame->u.rpn.stop_bits =
(*p_data >> RFCOMM_RPN_STOP_BITS_SHIFT) & RFCOMM_RPN_STOP_BITS_MASK;
p_rx_frame->u.rpn.parity =
(*p_data >> RFCOMM_RPN_PARITY_SHIFT) & RFCOMM_RPN_PARITY_MASK;
p_rx_frame->u.rpn.parity_type =
(*p_data++ >> RFCOMM_RPN_PARITY_TYPE_SHIFT) &
RFCOMM_RPN_PARITY_TYPE_MASK;
p_rx_frame->u.rpn.fc_type = *p_data++ & RFCOMM_FC_MASK;
p_rx_frame->u.rpn.xon_char = *p_data++;
p_rx_frame->u.rpn.xoff_char = *p_data++;
p_rx_frame->u.rpn.param_mask =
(*p_data + (*(p_data + 1) << 8)) & RFCOMM_RPN_PM_MASK;
}
osi_free(p_buf);
rfc_process_rpn(p_mcb, is_command, p_rx_frame->u.rpn.is_request,
p_rx_frame);
return;
case RFCOMM_MX_RLS:
if (length != RFCOMM_MX_RLS_LEN) break;
ea = *p_data & RFCOMM_EA;
cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR;
p_rx_frame->dlci = *p_data++ >> RFCOMM_SHIFT_DLCI;
p_rx_frame->u.rls.line_status = (*p_data & ~0x01);
if (!ea || !cr || !p_rx_frame->dlci ||
!RFCOMM_VALID_DLCI(p_rx_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad RPN frame");
break;
}
osi_free(p_buf);
rfc_process_rls(p_mcb, is_command, p_rx_frame);
return;
}
osi_free(p_buf);
if (is_command) rfc_send_nsc(p_mcb);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,109 |
linux | 20e0fa98b751facf9a1101edaefbc19c82616a68 | static void nfs4_set_cached_acl(struct inode *inode, struct nfs4_cached_acl *acl)
{
struct nfs_inode *nfsi = NFS_I(inode);
spin_lock(&inode->i_lock);
kfree(nfsi->nfs4_acl);
nfsi->nfs4_acl = acl;
spin_unlock(&inode->i_lock);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,131 |
FFmpeg | 8001e9f7d17e90b4b0898ba64e3b8bbd716c513c | static int get_siz(Jpeg2000DecoderContext *s)
{
int i;
int ncomponents;
uint32_t log2_chroma_wh = 0;
const enum AVPixelFormat *possible_fmts = NULL;
int possible_fmts_nb = 0;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR_INVALIDDATA;
s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
s->width = bytestream2_get_be32u(&s->g); // Width
s->height = bytestream2_get_be32u(&s->g); // Height
s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
ncomponents = bytestream2_get_be16u(&s->g); // CSiz
if (s->image_offset_x || s->image_offset_y) {
avpriv_request_sample(s->avctx, "Support for image offsets");
return AVERROR_PATCHWELCOME;
}
if (ncomponents <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
s->ncomponents);
return AVERROR_INVALIDDATA;
}
if (ncomponents > 4) {
avpriv_request_sample(s->avctx, "Support for %d components",
s->ncomponents);
return AVERROR_PATCHWELCOME;
}
s->ncomponents = ncomponents;
if (s->tile_width <= 0 || s->tile_height <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
s->tile_width, s->tile_height);
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR_INVALIDDATA;
for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
|| !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
return AVERROR_INVALIDDATA;
}
log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(EINVAL);
}
s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
if (!s->tile) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
/* compute image size with reduction factor */
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
possible_fmts = xyz_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
} else {
switch (s->colour_space) {
case 16:
possible_fmts = rgb_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
break;
case 17:
possible_fmts = gray_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
break;
case 18:
possible_fmts = yuv_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
break;
default:
possible_fmts = all_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
break;
}
}
for (i = 0; i < possible_fmts_nb; ++i) {
if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
s->avctx->pix_fmt = possible_fmts[i];
break;
}
}
if (i == possible_fmts_nb) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown pix_fmt, profile: %d, colour_space: %d, "
"components: %d, precision: %d, "
"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
s->avctx->profile, s->colour_space, ncomponents, s->precision,
ncomponents > 2 ? s->cdx[1] : 0,
ncomponents > 2 ? s->cdy[1] : 0,
ncomponents > 2 ? s->cdx[2] : 0,
ncomponents > 2 ? s->cdy[2] : 0);
return AVERROR_PATCHWELCOME;
}
s->avctx->bits_per_raw_sample = s->precision;
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,843 |
linux | 7f821fc9c77a9b01fe7b1d6e72717b33d8d64142 | void giveup_fpu_maybe_transactional(struct task_struct *tsk)
{
/*
* If we are saving the current thread's registers, and the
* thread is in a transactional state, set the TIF_RESTORE_TM
* bit so that we know to restore the registers before
* returning to userspace.
*/
if (tsk == current && tsk->thread.regs &&
MSR_TM_ACTIVE(tsk->thread.regs->msr) &&
!test_thread_flag(TIF_RESTORE_TM)) {
tsk->thread.ckpt_regs.msr = tsk->thread.regs->msr;
set_thread_flag(TIF_RESTORE_TM);
}
giveup_fpu(tsk);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,442 |
linux | fb73974172ffaaf57a7c42f35424d9aece1a5af6 | static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
u8 port_num)
{
struct common_audit_data ad;
int err;
u32 sid = 0;
struct ib_security_struct *sec = ib_sec;
struct lsm_ibendport_audit ibendport;
err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
&sid);
if (err)
return err;
ad.type = LSM_AUDIT_DATA_IBENDPORT;
strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
ibendport.port = port_num;
ad.u.ibendport = &ibendport;
return avc_has_perm(&selinux_state,
sec->sid, sid,
SECCLASS_INFINIBAND_ENDPORT,
INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,186 |
WavPack | 4bc05fc490b66ef2d45b1de26abf1455b486b0dc | static uint32_t __inline read_code (Bitstream *bs, uint32_t maxcode)
{
unsigned long local_sr;
uint32_t extras, code;
int bitcount;
if (maxcode < 2)
return maxcode ? getbit (bs) : 0;
bitcount = count_bits (maxcode);
#ifdef USE_BITMASK_TABLES
extras = bitset [bitcount] - maxcode - 1;
#else
extras = (1 << bitcount) - maxcode - 1;
#endif
local_sr = bs->sr;
while (bs->bc < bitcount) {
if (++(bs->ptr) == bs->end)
bs->wrap (bs);
local_sr |= (long)*(bs->ptr) << bs->bc;
bs->bc += sizeof (*(bs->ptr)) * 8;
}
#ifdef USE_BITMASK_TABLES
if ((code = local_sr & bitmask [bitcount - 1]) >= extras)
#else
if ((code = local_sr & ((1 << (bitcount - 1)) - 1)) >= extras)
#endif
code = (code << 1) - extras + ((local_sr >> (bitcount - 1)) & 1);
else
bitcount--;
if (sizeof (local_sr) < 8 && bs->bc > sizeof (local_sr) * 8) {
bs->bc -= bitcount;
bs->sr = *(bs->ptr) >> (sizeof (*(bs->ptr)) * 8 - bs->bc);
}
else {
bs->bc -= bitcount;
bs->sr = local_sr >> bitcount;
}
return code;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,329 |
linux-2.6 | fdff73f094e7220602cc3f8959c7230517976412 | static int verify_reserved_gdb(struct super_block *sb,
struct buffer_head *primary)
{
const ext4_fsblk_t blk = primary->b_blocknr;
const ext4_group_t end = EXT4_SB(sb)->s_groups_count;
unsigned three = 1;
unsigned five = 5;
unsigned seven = 7;
unsigned grp;
__le32 *p = (__le32 *)primary->b_data;
int gdbackups = 0;
while ((grp = ext4_list_backups(sb, &three, &five, &seven)) < end) {
if (le32_to_cpu(*p++) !=
grp * EXT4_BLOCKS_PER_GROUP(sb) + blk){
ext4_warning(sb, __func__,
"reserved GDT %llu"
" missing grp %d (%llu)",
blk, grp,
grp *
(ext4_fsblk_t)EXT4_BLOCKS_PER_GROUP(sb) +
blk);
return -EINVAL;
}
if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb))
return -EFBIG;
}
return gdbackups;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,267 |
krb5 | 102bb6ebf20f9174130c85c3b052ae104e5073ec | krb5_recvauth(krb5_context context, krb5_auth_context *auth_context, krb5_pointer fd, char *appl_version, krb5_principal server, krb5_int32 flags, krb5_keytab keytab, krb5_ticket **ticket)
{
return recvauth_common (context, auth_context, fd, appl_version,
server, flags, keytab, ticket, 0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,989 |
poppler | b1026b5978c385328f2a15a2185c599a563edf91 | FilterStream::FilterStream(Stream *strA) {
str = strA;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,481 |
cups | 49fa4983f25b64ec29d548ffa3b9782426007df3 | add_job(cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer, /* I - Destination printer */
mime_type_t *filetype) /* I - First print file type, if any */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr, /* Current attribute */
*auth_info; /* auth-info attribute */
const char *mandatory; /* Current mandatory job attribute */
const char *val; /* Default option value */
int priority; /* Job priority */
cupsd_job_t *job; /* Current job */
char job_uri[HTTP_MAX_URI]; /* Job URI */
int kbytes; /* Size of print file */
int i; /* Looping var */
int lowerpagerange; /* Page range bound */
int exact; /* Did we have an exact match? */
ipp_attribute_t *media_col, /* media-col attribute */
*media_margin; /* media-*-margin attribute */
ipp_t *unsup_col; /* media-col in unsupported response */
static const char * const readonly[] =/* List of read-only attributes */
{
"date-time-at-completed",
"date-time-at-creation",
"date-time-at-processing",
"job-detailed-status-messages",
"job-document-access-errors",
"job-id",
"job-impressions-completed",
"job-k-octets-completed",
"job-media-sheets-completed",
"job-pages-completed",
"job-printer-up-time",
"job-printer-uri",
"job-state",
"job-state-message",
"job-state-reasons",
"job-uri",
"number-of-documents",
"number-of-intervening-jobs",
"output-device-assigned",
"time-at-completed",
"time-at-creation",
"time-at-processing"
};
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))",
con, con->number, printer, printer->name,
filetype, filetype ? filetype->super : "none",
filetype ? filetype->type : "none");
/*
* Check remote printing to non-shared printer...
*/
if (!printer->shared &&
_cups_strcasecmp(con->http->hostname, "localhost") &&
_cups_strcasecmp(con->http->hostname, ServerName))
{
send_ipp_status(con, IPP_NOT_AUTHORIZED,
_("The printer or class is not shared."));
return (NULL);
}
/*
* Check policy...
*/
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return (NULL);
}
else if (printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
!con->username[0])
{
send_http_error(con, HTTP_UNAUTHORIZED, printer);
return (NULL);
}
#ifdef HAVE_SSL
else if (auth_info && !con->http->tls &&
!httpAddrLocalhost(con->http->hostaddr))
{
/*
* Require encryption of auth-info over non-local connections...
*/
send_http_error(con, HTTP_UPGRADE_REQUIRED, printer);
return (NULL);
}
#endif /* HAVE_SSL */
/*
* See if the printer is accepting jobs...
*/
if (!printer->accepting)
{
send_ipp_status(con, IPP_NOT_ACCEPTING,
_("Destination \"%s\" is not accepting jobs."),
printer->name);
return (NULL);
}
/*
* Validate job template attributes; for now just document-format,
* copies, job-sheets, number-up, page-ranges, mandatory attributes, and
* media...
*/
for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++)
{
if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL)
{
ippDeleteAttribute(con->request, attr);
if (StrictConformance)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]);
return (NULL);
}
cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]);
}
}
if (printer->pc)
{
for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory);
mandatory;
mandatory = (char *)cupsArrayNext(printer->pc->mandatory))
{
if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO))
{
/*
* Missing a required attribute...
*/
send_ipp_status(con, IPP_CONFLICT,
_("The \"%s\" attribute is required for print jobs."),
mandatory);
return (NULL);
}
}
}
if (filetype && printer->filetypes &&
!cupsArrayFind(printer->filetypes, filetype))
{
char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* MIME media type string */
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported format \"%s\"."), mimetype);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
return (NULL);
}
if ((attr = ippFindAttribute(con->request, "copies",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"copies", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "job-sheets",
IPP_TAG_ZERO)) != NULL)
{
if (attr->value_tag != IPP_TAG_KEYWORD &&
attr->value_tag != IPP_TAG_NAME)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type."));
return (NULL);
}
if (attr->num_values > 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Too many job-sheets values (%d > 2)."),
attr->num_values);
return (NULL);
}
for (i = 0; i < attr->num_values; i ++)
if (strcmp(attr->values[i].string.text, "none") &&
!cupsdFindBanner(attr->values[i].string.text))
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."),
attr->values[i].string.text);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "number-up",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer != 1 &&
attr->values[0].integer != 2 &&
attr->values[0].integer != 4 &&
attr->values[0].integer != 6 &&
attr->values[0].integer != 9 &&
attr->values[0].integer != 16)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"number-up", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "page-ranges",
IPP_TAG_RANGE)) != NULL)
{
for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++)
{
if (attr->values[i].range.lower < lowerpagerange ||
attr->values[i].range.lower > attr->values[i].range.upper)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad page-ranges values %d-%d."),
attr->values[i].range.lower,
attr->values[i].range.upper);
return (NULL);
}
lowerpagerange = attr->values[i].range.upper + 1;
}
}
/*
* Do media selection as needed...
*/
if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) &&
!ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) &&
_ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact))
{
if (!exact &&
(media_col = ippFindAttribute(con->request, "media-col",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins."));
unsup_col = ippNew();
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-bottom-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-bottom-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-left-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-left-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-right-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-right-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-top-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-top-margin", media_margin->values[0].integer);
ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col",
unsup_col);
ippDelete(unsup_col);
}
}
/*
* Make sure we aren't over our limit...
*/
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
cupsdCleanJobs();
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs."));
return (NULL);
}
if ((i = check_quotas(con, printer)) < 0)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached."));
return (NULL);
}
else if (i == 0)
{
send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print."));
return (NULL);
}
/*
* Create the job and set things up...
*/
if ((attr = ippFindAttribute(con->request, "job-priority",
IPP_TAG_INTEGER)) != NULL)
priority = attr->values[0].integer;
else
{
if ((val = cupsGetOption("job-priority", printer->num_options,
printer->options)) != NULL)
priority = atoi(val);
else
priority = 50;
ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority",
priority);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL)
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled");
else if ((attr->value_tag != IPP_TAG_NAME &&
attr->value_tag != IPP_TAG_NAMELANG) ||
attr->num_values != 1)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Bad job-name value: Wrong type or count."));
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
else if (!ippValidateAttribute(attr))
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"),
cupsLastErrorString());
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
if ((job = cupsdAddJob(priority, printer->name)) == NULL)
{
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("Unable to add job for destination \"%s\"."),
printer->name);
return (NULL);
}
job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE);
job->attrs = con->request;
job->dirty = 1;
con->request = ippNewRequest(job->attrs->request.op.operation_id);
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
add_job_uuid(job);
apply_printer_defaults(printer, job);
attr = ippFindAttribute(job->attrs, "requesting-user-name", IPP_TAG_NAME);
if (con->username[0])
{
cupsdSetString(&job->username, con->username);
if (attr)
ippSetString(job->attrs, &attr, 0, con->username);
}
else if (attr)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"add_job: requesting-user-name=\"%s\"",
attr->values[0].string.text);
cupsdSetString(&job->username, attr->values[0].string.text);
}
else
cupsdSetString(&job->username, "anonymous");
if (!attr)
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-user-name", NULL, job->username);
else
{
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
ippSetName(job->attrs, &attr, "job-originating-user-name");
}
if (con->username[0] || auth_info)
{
save_auth_info(con, job, auth_info);
/*
* Remove the auth-info attribute from the attribute data...
*/
if (auth_info)
ippDeleteAttribute(job->attrs, auth_info);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL)
cupsdSetString(&(job->name), attr->values[0].string.text);
if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name",
IPP_TAG_ZERO)) != NULL)
{
/*
* Request contains a job-originating-host-name attribute; validate it...
*/
if (attr->value_tag != IPP_TAG_NAME ||
attr->num_values != 1 ||
strcmp(con->http->hostname, "localhost"))
{
/*
* Can't override the value if we aren't connected via localhost.
* Also, we can only have 1 value and it must be a name value.
*/
ippDeleteAttribute(job->attrs, attr);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname);
}
else
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
}
else
{
/*
* No job-originating-host-name attribute, so use the hostname from
* the connection...
*/
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-host-name", NULL, con->http->hostname);
}
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed");
ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL)));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing");
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed");
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing");
/*
* Add remaining job attributes...
*/
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM,
"job-state", IPP_JOB_STOPPED);
job->state_value = (ipp_jstate_t)job->state->values[0].integer;
job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-state-reasons", NULL, "job-incoming");
job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0);
job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-media-sheets-completed", 0);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL,
printer->uri);
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer = 0;
else
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0);
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr)
{
if ((val = cupsGetOption("job-hold-until", printer->num_options,
printer->options)) == NULL)
val = "no-hold";
attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-hold-until", NULL, val);
}
if (printer->holding_new_jobs)
{
/*
* Hold all new jobs on this printer...
*/
if (attr && strcmp(attr->values[0].string.text, "no-hold"))
cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0);
else
cupsdSetJobHoldUntil(job, "indefinite", 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create");
}
else if (attr && strcmp(attr->values[0].string.text, "no-hold"))
{
/*
* Hold job until specified time...
*/
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
}
else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB)
{
job->hold_until = time(NULL) + MultipleOperationTimeout;
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
}
else
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification)
{
/*
* Add job sheets options...
*/
if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Adding default job-sheets values \"%s,%s\"...",
printer->job_sheets[0], printer->job_sheets[1]);
attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets",
2, NULL, NULL);
ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]);
ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]);
}
job->job_sheets = attr;
/*
* Enforce classification level if set...
*/
if (Classification)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Classification=\"%s\", ClassifyOverride=%d",
Classification ? Classification : "(null)",
ClassifyOverride);
if (ClassifyOverride)
{
if (!strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
!strcmp(attr->values[1].string.text, "none")))
{
/*
* Force the leading banner to have the classification on it...
*/
ippSetString(job->attrs, &attr, 0, Classification);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,none\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
else if (attr->num_values == 2 &&
strcmp(attr->values[0].string.text,
attr->values[1].string.text) &&
strcmp(attr->values[0].string.text, "none") &&
strcmp(attr->values[1].string.text, "none"))
{
/*
* Can't put two different security markings on the same document!
*/
ippSetString(job->attrs, &attr, 1, attr->values[0].string.text);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
else if (strcmp(attr->values[0].string.text, Classification) &&
strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
(strcmp(attr->values[1].string.text, Classification) &&
strcmp(attr->values[1].string.text, "none"))))
{
if (attr->num_values == 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s,%s\",fffff "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
}
else if (strcmp(attr->values[0].string.text, Classification) &&
(attr->num_values == 1 ||
strcmp(attr->values[1].string.text, Classification)))
{
/*
* Force the banner to have the classification on it...
*/
if (attr->num_values > 1 &&
!strcmp(attr->values[0].string.text, attr->values[1].string.text))
{
ippSetString(job->attrs, &attr, 0, Classification);
ippSetString(job->attrs, &attr, 1, Classification);
}
else
{
if (attr->num_values == 1 ||
strcmp(attr->values[0].string.text, "none"))
ippSetString(job->attrs, &attr, 0, Classification);
if (attr->num_values > 1 &&
strcmp(attr->values[1].string.text, "none"))
ippSetString(job->attrs, &attr, 1, Classification);
}
if (attr->num_values > 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
}
/*
* See if we need to add the starting sheet...
*/
if (!(printer->type & CUPS_PRINTER_REMOTE))
{
cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".",
attr->values[0].string.text);
if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0)
{
cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
"Aborting job because the start banner could not be "
"copied.");
return (NULL);
}
cupsdUpdateQuota(printer, job->username, 0, kbytes);
}
}
else if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) != NULL)
job->job_sheets = attr;
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, "");
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons",
NULL, job->reasons->values[0].string.text);
con->response->request.status.status_code = IPP_OK;
/*
* Add any job subscriptions...
*/
add_job_subscriptions(con, job);
/*
* Set all but the first two attributes to the job attributes group...
*/
for (attr = job->attrs->attrs->next->next; attr; attr = attr->next)
attr->group_tag = IPP_TAG_JOB;
/*
* Fire the "job created" event...
*/
cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created.");
/*
* Return the new job...
*/
return (job);
}
| 1 | CVE-2017-18248 | 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. | 734 |
dbus | 9a6bce9b615abca6068348c1606ba8eaf13d9ae0 | my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error)
{
int len;
int i;
len = g_strv_length ((char**) in);
*out = g_new0 (char *, len + 1);
for (i = 0; i < len; i++)
{
(*out)[i] = g_ascii_strup (in[i], -1);
}
(*out)[i] = NULL;
return TRUE;
}
| 1 | CVE-2010-1172 | 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 | 3,901 |
Android | 0f177948ae2640bfe4d70f8e4248e106406b3b0a | void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) {
if (!mIsBackup) {
return;
}
sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */);
memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size());
}
| 1 | CVE-2016-6720 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 3,252 |
libxfont | d11ee5886e9d9ec610051a206b135a4cdc1e09a0 | BufCompressedClose (BufFilePtr f, int doClose)
{
CompressedFile *file;
BufFilePtr raw;
file = (CompressedFile *) f->private;
raw = file->file;
free (file);
BufFileClose (raw, doClose);
return 1;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,698 |
Chrome | 9b99a43fc119a2533a87e2357cad8f603779a7b9 | void WebGL2RenderingContextBase::texSubImage3D(GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLenum type,
GLintptr offset) {
if (isContextLost())
return;
if (!ValidateTexture3DBinding("texSubImage3D", target))
return;
if (!bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D",
"no bound PIXEL_UNPACK_BUFFER");
return;
}
if (!ValidateTexFunc("texSubImage3D", kTexSubImage, kSourceUnpackBuffer,
target, level, 0, width, height, depth, 0, format, type,
xoffset, yoffset, zoffset))
return;
if (!ValidateValueFitNonNegInt32("texSubImage3D", "offset", offset))
return;
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width,
height, depth, format, type,
reinterpret_cast<const void*>(offset));
}
| 1 | CVE-2018-6038 | 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,802 |
Chrome | adca986a53b31b6da4cb22f8e755f6856daea89a | InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
return GetRenderManager()->interstitial_page();
}
| 1 | CVE-2017-5104 | 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. | 7,594 |
php-src | ede59c8feb4b80e1b94e4abdaa0711051e2912ab |
private int
mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
int rv, oneed_separator;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, m) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu)\n", m->type, m->flag, offset, o, nbytes);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) %
off;
break;
}
} else
offset = (short)((p->hs[0]<<8)|
(p->hs[1]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) %
off;
break;
}
} else
offset = (short)((p->hs[1]<<8)|
(p->hs[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
}
switch (cvt_flip(m->in_type, flip)) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
break;
case FILE_INDIRECT:
if (offset == 0)
return 0;
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
recursion_level, BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, m->desc, offset) == -1) {
if (rbuf) {
efree(rbuf);
}
return -1;
}
if (file_printf(ms, "%s", rbuf) == -1) {
if (rbuf) {
efree(rbuf);
}
return -1;
}
}
if (rbuf) {
efree(rbuf);
}
return rv;
case FILE_USE:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
default:
break;
}
if (!mconvert(ms, m, flip))
return 0; | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,257 |
mongo | 035cf2afc04988b22cb67f4ebfd77e9b344cb6e0 | static int enableRawMode(void) {
#ifdef _WIN32
if (!console_in) {
console_in = GetStdHandle(STD_INPUT_HANDLE);
console_out = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(console_in, &oldMode);
SetConsoleMode(console_in,
oldMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT));
}
return 0;
#else
struct termios raw;
if (!isatty(0))
goto fatal;
if (!atexit_registered) {
atexit(linenoiseAtExit);
atexit_registered = 1;
}
if (tcgetattr(0, &orig_termios) == -1)
goto fatal;
raw = orig_termios; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
// this is wrong, we don't want raw output, it turns newlines into straight linefeeds
// raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - echoing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */
if (tcsetattr(0, TCSADRAIN, &raw) < 0)
goto fatal;
rawmode = 1;
return 0;
fatal:
errno = ENOTTY;
return -1;
#endif
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,071 |
ImageMagick6 | bb812022d0bc12107db215c981cab0b1ccd73d91 | WandExport MagickBooleanType MogrifyImageCommand(ImageInfo *image_info,
int argc,char **argv,char **wand_unused(metadata),ExceptionInfo *exception)
{
#define DestroyMogrify() \
{ \
if (format != (char *) NULL) \
format=DestroyString(format); \
if (path != (char *) NULL) \
path=DestroyString(path); \
DestroyImageStack(); \
for (i=0; i < (ssize_t) argc; i++) \
argv[i]=DestroyString(argv[i]); \
argv=(char **) RelinquishMagickMemory(argv); \
}
#define ThrowMogrifyException(asperity,tag,option) \
{ \
(void) ThrowMagickException(exception,GetMagickModule(),asperity,tag,"`%s'", \
option); \
DestroyMogrify(); \
return(MagickFalse); \
}
#define ThrowMogrifyInvalidArgumentException(option,argument) \
{ \
(void) ThrowMagickException(exception,GetMagickModule(),OptionError, \
"InvalidArgument","`%s': %s",argument,option); \
DestroyMogrify(); \
return(MagickFalse); \
}
char
*format,
*option,
*path;
Image
*image;
ImageStack
image_stack[MaxImageStackDepth+1];
MagickBooleanType
global_colormap;
MagickBooleanType
fire,
pend,
respect_parenthesis;
MagickStatusType
status;
register ssize_t
i;
ssize_t
j,
k;
wand_unreferenced(metadata);
/*
Set defaults.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(exception != (ExceptionInfo *) NULL);
if (argc == 2)
{
option=argv[1];
if ((LocaleCompare("version",option+1) == 0) ||
(LocaleCompare("-version",option+1) == 0))
{
ListMagickVersion(stdout);
return(MagickTrue);
}
}
if (argc < 2)
return(MogrifyUsage());
format=(char *) NULL;
path=(char *) NULL;
global_colormap=MagickFalse;
k=0;
j=1;
NewImageStack();
option=(char *) NULL;
pend=MagickFalse;
respect_parenthesis=MagickFalse;
status=MagickTrue;
/*
Parse command line.
*/
ReadCommandlLine(argc,&argv);
status=ExpandFilenames(&argc,&argv);
if (status == MagickFalse)
ThrowMogrifyException(ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
for (i=1; i < (ssize_t) argc; i++)
{
option=argv[i];
if (LocaleCompare(option,"(") == 0)
{
FireImageStack(MagickFalse,MagickTrue,pend);
if (k == MaxImageStackDepth)
ThrowMogrifyException(OptionError,"ParenthesisNestedTooDeeply",
option);
PushImageStack();
continue;
}
if (LocaleCompare(option,")") == 0)
{
FireImageStack(MagickFalse,MagickTrue,MagickTrue);
if (k == 0)
ThrowMogrifyException(OptionError,"UnableToParseExpression",option);
PopImageStack();
continue;
}
if (IsCommandOption(option) == MagickFalse)
{
char
backup_filename[MaxTextExtent],
*filename;
Image
*images;
struct stat
properties;
/*
Option is a file name: begin by reading image from specified file.
*/
FireImageStack(MagickFalse,MagickFalse,pend);
filename=argv[i];
if ((LocaleCompare(filename,"--") == 0) && (i < (ssize_t) (argc-1)))
filename=argv[++i];
(void) SetImageOption(image_info,"filename",filename);
(void) CopyMagickString(image_info->filename,filename,MaxTextExtent);
images=ReadImages(image_info,exception);
status&=(images != (Image *) NULL) &&
(exception->severity < ErrorException);
if (images == (Image *) NULL)
continue;
properties=(*GetBlobProperties(images));
if (format != (char *) NULL)
(void) CopyMagickString(images->filename,images->magick_filename,
MaxTextExtent);
if (path != (char *) NULL)
{
GetPathComponent(option,TailPath,filename);
(void) FormatLocaleString(images->filename,MaxTextExtent,"%s%c%s",
path,*DirectorySeparator,filename);
}
if (format != (char *) NULL)
AppendImageFormat(format,images->filename);
AppendImageStack(images);
FinalizeImageSettings(image_info,image,MagickFalse);
if (global_colormap != MagickFalse)
{
QuantizeInfo
*quantize_info;
quantize_info=AcquireQuantizeInfo(image_info);
(void) RemapImages(quantize_info,images,(Image *) NULL);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
*backup_filename='\0';
if ((LocaleCompare(image->filename,"-") != 0) &&
(IsPathWritable(image->filename) != MagickFalse))
{
register ssize_t
i;
/*
Rename image file as backup.
*/
(void) CopyMagickString(backup_filename,image->filename,
MaxTextExtent);
for (i=0; i < 6; i++)
{
(void) ConcatenateMagickString(backup_filename,"~",MaxTextExtent);
if (IsPathAccessible(backup_filename) == MagickFalse)
break;
}
if ((IsPathAccessible(backup_filename) != MagickFalse) ||
(rename_utf8(image->filename,backup_filename) != 0))
*backup_filename='\0';
}
/*
Write transmogrified image to disk.
*/
image_info->synchronize=MagickTrue;
status&=WriteImages(image_info,image,image->filename,exception);
if (status != MagickFalse)
{
#if defined(MAGICKCORE_HAVE_UTIME)
{
MagickBooleanType
preserve_timestamp;
preserve_timestamp=IsStringTrue(GetImageOption(image_info,
"preserve-timestamp"));
if (preserve_timestamp != MagickFalse)
{
struct utimbuf
timestamp;
timestamp.actime=properties.st_atime;
timestamp.modtime=properties.st_mtime;
(void) utime(image->filename,×tamp);
}
}
#endif
if (*backup_filename != '\0')
(void) remove_utf8(backup_filename);
}
RemoveAllImageStack();
continue;
}
pend=image != (Image *) NULL ? MagickTrue : MagickFalse;
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("adaptive-blur",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("adaptive-resize",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("adaptive-sharpen",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("affine",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("alpha",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
type=ParseCommandOption(MagickAlphaOptions,MagickFalse,argv[i]);
if (type < 0)
ThrowMogrifyException(OptionError,"UnrecognizedAlphaChannelType",
argv[i]);
break;
}
if (LocaleCompare("annotate",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
i++;
break;
}
if (LocaleCompare("antialias",option+1) == 0)
break;
if (LocaleCompare("append",option+1) == 0)
break;
if (LocaleCompare("attenuate",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("authenticate",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("auto-gamma",option+1) == 0)
break;
if (LocaleCompare("auto-level",option+1) == 0)
break;
if (LocaleCompare("auto-orient",option+1) == 0)
break;
if (LocaleCompare("average",option+1) == 0)
break;
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'b':
{
if (LocaleCompare("background",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("bias",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("black-point-compensation",option+1) == 0)
break;
if (LocaleCompare("black-threshold",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("blue-primary",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("blue-shift",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("blur",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("border",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("bordercolor",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("box",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("brightness-contrast",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'c':
{
if (LocaleCompare("cache",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("canny",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("caption",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("channel",option+1) == 0)
{
ssize_t
channel;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
channel=ParseChannelOption(argv[i]);
if (channel < 0)
ThrowMogrifyException(OptionError,"UnrecognizedChannelType",
argv[i]);
break;
}
if (LocaleCompare("cdl",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("charcoal",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("chop",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("clamp",option+1) == 0)
break;
if (LocaleCompare("clip",option+1) == 0)
break;
if (LocaleCompare("clip-mask",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("clut",option+1) == 0)
break;
if (LocaleCompare("coalesce",option+1) == 0)
break;
if (LocaleCompare("colorize",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("color-matrix",option+1) == 0)
{
KernelInfo
*kernel_info;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
kernel_info=AcquireKernelInfo(argv[i]);
if (kernel_info == (KernelInfo *) NULL)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
kernel_info=DestroyKernelInfo(kernel_info);
break;
}
if (LocaleCompare("colors",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("colorspace",option+1) == 0)
{
ssize_t
colorspace;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,
argv[i]);
if (colorspace < 0)
ThrowMogrifyException(OptionError,"UnrecognizedColorspace",
argv[i]);
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
if (*option == '-')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("comment",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("compare",option+1) == 0)
break;
if (LocaleCompare("complex",option+1) == 0)
{
ssize_t
op;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickComplexOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedComplexOperator",
argv[i]);
break;
}
if (LocaleCompare("composite",option+1) == 0)
break;
if (LocaleCompare("compress",option+1) == 0)
{
ssize_t
compress;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
compress=ParseCommandOption(MagickCompressOptions,MagickFalse,
argv[i]);
if (compress < 0)
ThrowMogrifyException(OptionError,"UnrecognizedImageCompression",
argv[i]);
break;
}
if (LocaleCompare("concurrent",option+1) == 0)
break;
if (LocaleCompare("connected-components",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("contrast",option+1) == 0)
break;
if (LocaleCompare("contrast-stretch",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("convolve",option+1) == 0)
{
KernelInfo
*kernel_info;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
kernel_info=AcquireKernelInfo(argv[i]);
if (kernel_info == (KernelInfo *) NULL)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
kernel_info=DestroyKernelInfo(kernel_info);
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("crop",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("cycle",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'd':
{
if (LocaleCompare("decipher",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("deconstruct",option+1) == 0)
break;
if (LocaleCompare("debug",option+1) == 0)
{
ssize_t
event;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
event=ParseCommandOption(MagickLogEventOptions,MagickFalse,argv[i]);
if (event < 0)
ThrowMogrifyException(OptionError,"UnrecognizedEventType",
argv[i]);
(void) SetLogEventMask(argv[i]);
break;
}
if (LocaleCompare("define",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (*option == '+')
{
const char
*define;
define=GetImageOption(image_info,argv[i]);
if (define == (const char *) NULL)
ThrowMogrifyException(OptionError,"NoSuchOption",argv[i]);
break;
}
break;
}
if (LocaleCompare("delay",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("density",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("depth",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("deskew",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("despeckle",option+1) == 0)
break;
if (LocaleCompare("dft",option+1) == 0)
break;
if (LocaleCompare("direction",option+1) == 0)
{
ssize_t
direction;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,
argv[i]);
if (direction < 0)
ThrowMogrifyException(OptionError,"UnrecognizedDirectionType",
argv[i]);
break;
}
if (LocaleCompare("display",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("dispose",option+1) == 0)
{
ssize_t
dispose;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
argv[i]);
if (dispose < 0)
ThrowMogrifyException(OptionError,"UnrecognizedDisposeMethod",
argv[i]);
break;
}
if (LocaleCompare("distort",option+1) == 0)
{
ssize_t
op;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickDistortOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedDistortMethod",
argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("dither",option+1) == 0)
{
ssize_t
method;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
method=ParseCommandOption(MagickDitherOptions,MagickFalse,argv[i]);
if (method < 0)
ThrowMogrifyException(OptionError,"UnrecognizedDitherMethod",
argv[i]);
break;
}
if (LocaleCompare("draw",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("duration",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'e':
{
if (LocaleCompare("edge",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("emboss",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("encipher",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("encoding",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("endian",option+1) == 0)
{
ssize_t
endian;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,argv[i]);
if (endian < 0)
ThrowMogrifyException(OptionError,"UnrecognizedEndianType",
argv[i]);
break;
}
if (LocaleCompare("enhance",option+1) == 0)
break;
if (LocaleCompare("equalize",option+1) == 0)
break;
if (LocaleCompare("evaluate",option+1) == 0)
{
ssize_t
op;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedEvaluateOperator",
argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
ssize_t
op;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedEvaluateOperator",
argv[i]);
break;
}
if (LocaleCompare("extent",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("extract",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'f':
{
if (LocaleCompare("family",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("features",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("fill",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("filter",option+1) == 0)
{
ssize_t
filter;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
filter=ParseCommandOption(MagickFilterOptions,MagickFalse,argv[i]);
if (filter < 0)
ThrowMogrifyException(OptionError,"UnrecognizedImageFilter",
argv[i]);
break;
}
if (LocaleCompare("flatten",option+1) == 0)
break;
if (LocaleCompare("flip",option+1) == 0)
break;
if (LocaleCompare("flop",option+1) == 0)
break;
if (LocaleCompare("floodfill",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("font",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("format",option+1) == 0)
{
(void) CopyMagickString(argv[i]+1,"sans",MaxTextExtent);
(void) CloneString(&format,(char *) NULL);
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
(void) CloneString(&format,argv[i]);
(void) CopyMagickString(image_info->filename,format,MaxTextExtent);
(void) ConcatenateMagickString(image_info->filename,":",
MaxTextExtent);
(void) SetImageInfo(image_info,0,exception);
if (*image_info->magick == '\0')
ThrowMogrifyException(OptionError,"UnrecognizedImageFormat",
format);
break;
}
if (LocaleCompare("frame",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("function",option+1) == 0)
{
ssize_t
op;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickFunctionOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedFunction",argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("fuzz",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'g':
{
if (LocaleCompare("gamma",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if ((LocaleCompare("gaussian-blur",option+1) == 0) ||
(LocaleCompare("gaussian",option+1) == 0))
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("geometry",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("gravity",option+1) == 0)
{
ssize_t
gravity;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,
argv[i]);
if (gravity < 0)
ThrowMogrifyException(OptionError,"UnrecognizedGravityType",
argv[i]);
break;
}
if (LocaleCompare("grayscale",option+1) == 0)
{
ssize_t
method;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
method=ParseCommandOption(MagickPixelIntensityOptions,MagickFalse,
argv[i]);
if (method < 0)
ThrowMogrifyException(OptionError,"UnrecognizedIntensityMethod",
argv[i]);
break;
}
if (LocaleCompare("green-primary",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
break;
if (LocaleCompare("hough-lines",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if ((LocaleCompare("help",option+1) == 0) ||
(LocaleCompare("-help",option+1) == 0))
return(MogrifyUsage());
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'i':
{
if (LocaleCompare("identify",option+1) == 0)
break;
if (LocaleCompare("idft",option+1) == 0)
break;
if (LocaleCompare("implode",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("intensity",option+1) == 0)
{
ssize_t
intensity;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,argv[i]);
if (intensity < 0)
ThrowMogrifyException(OptionError,
"UnrecognizedPixelIntensityMethod",argv[i]);
break;
}
if (LocaleCompare("intent",option+1) == 0)
{
ssize_t
intent;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
intent=ParseCommandOption(MagickIntentOptions,MagickFalse,argv[i]);
if (intent < 0)
ThrowMogrifyException(OptionError,"UnrecognizedIntentType",
argv[i]);
break;
}
if (LocaleCompare("interlace",option+1) == 0)
{
ssize_t
interlace;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
interlace=ParseCommandOption(MagickInterlaceOptions,MagickFalse,
argv[i]);
if (interlace < 0)
ThrowMogrifyException(OptionError,"UnrecognizedInterlaceType",
argv[i]);
break;
}
if (LocaleCompare("interline-spacing",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("interpolate",option+1) == 0)
{
ssize_t
interpolate;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse,
argv[i]);
if (interpolate < 0)
ThrowMogrifyException(OptionError,"UnrecognizedInterpolateMethod",
argv[i]);
break;
}
if (LocaleCompare("interword-spacing",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'k':
{
if (LocaleCompare("kerning",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("kuwahara",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'l':
{
if (LocaleCompare("label",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("lat",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
}
if (LocaleCompare("layers",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
type=ParseCommandOption(MagickLayerOptions,MagickFalse,argv[i]);
if (type < 0)
ThrowMogrifyException(OptionError,"UnrecognizedLayerMethod",
argv[i]);
break;
}
if (LocaleCompare("level",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("level-colors",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("linewidth",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("limit",option+1) == 0)
{
char
*p;
double
value;
ssize_t
resource;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
resource=ParseCommandOption(MagickResourceOptions,MagickFalse,
argv[i]);
if (resource < 0)
ThrowMogrifyException(OptionError,"UnrecognizedResourceType",
argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
value=StringToDouble(argv[i],&p);
(void) value;
if ((p == argv[i]) && (LocaleCompare("unlimited",argv[i]) != 0))
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("liquid-rescale",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("list",option+1) == 0)
{
ssize_t
list;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
list=ParseCommandOption(MagickListOptions,MagickFalse,argv[i]);
if (list < 0)
ThrowMogrifyException(OptionError,"UnrecognizedListType",argv[i]);
status=MogrifyImageInfo(image_info,(int) (i-j+1),(const char **)
argv+j,exception);
return(status == 0 ? MagickFalse : MagickTrue);
}
if (LocaleCompare("local-contrast",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("log",option+1) == 0)
{
if (*option == '+')
break;
i++;
if ((i == (ssize_t) argc) ||
(strchr(argv[i],'%') == (char *) NULL))
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("loop",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'm':
{
if (LocaleCompare("magnify",option+1) == 0)
break;
if (LocaleCompare("map",option+1) == 0)
{
global_colormap=(*option == '+') ? MagickTrue : MagickFalse;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("mask",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("matte",option+1) == 0)
break;
if (LocaleCompare("mattecolor",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("metric",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
type=ParseCommandOption(MagickMetricOptions,MagickTrue,argv[i]);
if (type < 0)
ThrowMogrifyException(OptionError,"UnrecognizedMetricType",
argv[i]);
break;
}
if (LocaleCompare("maximum",option+1) == 0)
break;
if (LocaleCompare("mean-shift",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("median",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("minimum",option+1) == 0)
break;
if (LocaleCompare("modulate",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("mode",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("monitor",option+1) == 0)
break;
if (LocaleCompare("monochrome",option+1) == 0)
break;
if (LocaleCompare("morph",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("morphology",option+1) == 0)
{
char
token[MaxTextExtent];
KernelInfo
*kernel_info;
ssize_t
op;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
GetNextToken(argv[i],(const char **) NULL,MaxTextExtent,token);
op=ParseCommandOption(MagickMorphologyOptions,MagickFalse,token);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedMorphologyMethod",
token);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
kernel_info=AcquireKernelInfo(argv[i]);
if (kernel_info == (KernelInfo *) NULL)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
kernel_info=DestroyKernelInfo(kernel_info);
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
break;
if (LocaleCompare("motion-blur",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'n':
{
if (LocaleCompare("negate",option+1) == 0)
break;
if (LocaleCompare("noise",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (*option == '+')
{
ssize_t
noise;
noise=ParseCommandOption(MagickNoiseOptions,MagickFalse,argv[i]);
if (noise < 0)
ThrowMogrifyException(OptionError,"UnrecognizedNoiseType",
argv[i]);
break;
}
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("noop",option+1) == 0)
break;
if (LocaleCompare("normalize",option+1) == 0)
break;
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'o':
{
if (LocaleCompare("opaque",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("ordered-dither",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("orient",option+1) == 0)
{
ssize_t
orientation;
orientation=UndefinedOrientation;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
orientation=ParseCommandOption(MagickOrientationOptions,MagickFalse,
argv[i]);
if (orientation < 0)
ThrowMogrifyException(OptionError,"UnrecognizedImageOrientation",
argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'p':
{
if (LocaleCompare("page",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("paint",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("path",option+1) == 0)
{
(void) CloneString(&path,(char *) NULL);
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
(void) CloneString(&path,argv[i]);
break;
}
if (LocaleCompare("perceptible",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("pointsize",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("polaroid",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("poly",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("posterize",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("precision",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("print",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("process",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("profile",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'q':
{
if (LocaleCompare("quality",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("quantize",option+1) == 0)
{
ssize_t
colorspace;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,
argv[i]);
if (colorspace < 0)
ThrowMogrifyException(OptionError,"UnrecognizedColorspace",
argv[i]);
break;
}
if (LocaleCompare("quiet",option+1) == 0)
break;
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'r':
{
if (LocaleCompare("radial-blur",option+1) == 0 ||
LocaleCompare("rotational-blur",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("raise",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("random-threshold",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("recolor",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("red-primary",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
}
if (LocaleCompare("regard-warnings",option+1) == 0)
break;
if (LocaleCompare("region",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("remap",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("render",option+1) == 0)
break;
if (LocaleCompare("repage",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("resample",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("resize",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleNCompare("respect-parentheses",option+1,17) == 0)
{
respect_parenthesis=(*option == '-') ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("reverse",option+1) == 0)
break;
if (LocaleCompare("roll",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("rotate",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 's':
{
if (LocaleCompare("sample",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("sampling-factor",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("scale",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("scene",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("seed",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("segment",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("selective-blur",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("separate",option+1) == 0)
break;
if (LocaleCompare("sepia-tone",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("set",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("shade",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("shadow",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("sharpen",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("shave",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("shear",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("sigmoidal-contrast",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("size",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("sketch",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("smush",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
i++;
break;
}
if (LocaleCompare("solarize",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("sparse-color",option+1) == 0)
{
ssize_t
op;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickSparseColorOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedSparseColorMethod",
argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("splice",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("spread",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("statistic",option+1) == 0)
{
ssize_t
op;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
op=ParseCommandOption(MagickStatisticOptions,MagickFalse,argv[i]);
if (op < 0)
ThrowMogrifyException(OptionError,"UnrecognizedStatisticType",
argv[i]);
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("stretch",option+1) == 0)
{
ssize_t
stretch;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,argv[i]);
if (stretch < 0)
ThrowMogrifyException(OptionError,"UnrecognizedStyleType",
argv[i]);
break;
}
if (LocaleCompare("strip",option+1) == 0)
break;
if (LocaleCompare("stroke",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("strokewidth",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("style",option+1) == 0)
{
ssize_t
style;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
style=ParseCommandOption(MagickStyleOptions,MagickFalse,argv[i]);
if (style < 0)
ThrowMogrifyException(OptionError,"UnrecognizedStyleType",
argv[i]);
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("swirl",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("synchronize",option+1) == 0)
break;
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 't':
{
if (LocaleCompare("taint",option+1) == 0)
break;
if (LocaleCompare("texture",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("tile",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("tile-offset",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("tint",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("transform",option+1) == 0)
break;
if (LocaleCompare("transpose",option+1) == 0)
break;
if (LocaleCompare("transverse",option+1) == 0)
break;
if (LocaleCompare("threshold",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("thumbnail",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("transparent",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("transparent-color",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("treedepth",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("trim",option+1) == 0)
break;
if (LocaleCompare("type",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
type=ParseCommandOption(MagickTypeOptions,MagickFalse,argv[i]);
if (type < 0)
ThrowMogrifyException(OptionError,"UnrecognizedImageType",
argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'u':
{
if (LocaleCompare("undercolor",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("unique-colors",option+1) == 0)
break;
if (LocaleCompare("units",option+1) == 0)
{
ssize_t
units;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,
argv[i]);
if (units < 0)
ThrowMogrifyException(OptionError,"UnrecognizedUnitsType",
argv[i]);
break;
}
if (LocaleCompare("unsharp",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'v':
{
if (LocaleCompare("verbose",option+1) == 0)
{
image_info->verbose=(*option == '-') ? MagickTrue : MagickFalse;
break;
}
if ((LocaleCompare("version",option+1) == 0) ||
(LocaleCompare("-version",option+1) == 0))
{
ListMagickVersion(stdout);
break;
}
if (LocaleCompare("view",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("vignette",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("virtual-pixel",option+1) == 0)
{
ssize_t
method;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
method=ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,
argv[i]);
if (method < 0)
ThrowMogrifyException(OptionError,
"UnrecognizedVirtualPixelMethod",argv[i]);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case 'w':
{
if (LocaleCompare("wave",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("wavelet-denoise",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("weight",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
if (LocaleCompare("white-point",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("white-threshold",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
if (IsGeometry(argv[i]) == MagickFalse)
ThrowMogrifyInvalidArgumentException(option,argv[i]);
break;
}
if (LocaleCompare("write",option+1) == 0)
{
i++;
if (i == (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingArgument",option);
break;
}
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
case '?':
break;
default:
ThrowMogrifyException(OptionError,"UnrecognizedOption",option)
}
fire=(GetCommandOptionFlags(MagickCommandOptions,MagickFalse,option) &
FireOptionFlag) == 0 ? MagickFalse : MagickTrue;
if (fire != MagickFalse)
FireImageStack(MagickFalse,MagickTrue,MagickTrue);
}
if (k != 0)
ThrowMogrifyException(OptionError,"UnbalancedParenthesis",argv[i]);
if (i != (ssize_t) argc)
ThrowMogrifyException(OptionError,"MissingAnImageFilename",argv[i]);
DestroyMogrify();
return(status != 0 ? MagickTrue : MagickFalse);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,080 |
openssl | 43a7033a010feaf72c79d39df65ca733fb9dcd4c | ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_ITEM *it)
{
ASN1_TLC c;
ASN1_VALUE *ptmpval = NULL;
if (pval == NULL)
pval = &ptmpval;
asn1_tlc_clear_nc(&c);
if (ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0)
return *pval;
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,041 |
wolfMQTT | 84d4b53122e0fa0280c7872350b89d5777dabbb2 | MqttProp* MqttClient_PropsAdd(MqttProp **head)
{
return MqttProps_Add(head);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,663 |
irssi | e32e9d63c67ab95ef0576154680a6c52334b97af | static char *theme_format_expand_abstract(THEME_REC *theme, const char **formatp,
theme_rm_col *last_fg, theme_rm_col *last_bg, int flags,
GTree *block_list)
{
GString *str;
const char *p, *format;
char *abstract, *data, *ret;
theme_rm_col default_fg, default_bg;
int len;
format = *formatp;
default_fg = *last_fg;
default_bg = *last_bg;
/* get abstract name first */
p = format;
while (*p != '\0' && *p != ' ' &&
*p != '{' && *p != '}') p++;
if (*p == '\0' || p == format)
return NULL; /* error */
len = (int) (p-format);
abstract = g_strndup(format, len);
/* skip the following space, if there's any more spaces they're
treated as arguments */
if (*p == ' ') {
len++;
if ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) {
*formatp = p;
g_free(abstract);
return NULL;
}
}
*formatp = format+len;
if (block_list == NULL) {
block_list = g_tree_new_full((GCompareDataFunc) g_strcmp0, NULL, g_free, NULL);
} else {
g_tree_ref(block_list);
}
/* get the abstract data */
data = g_hash_table_lookup(theme->abstracts, abstract);
if (data == NULL || g_tree_lookup(block_list, abstract) != NULL) {
/* unknown abstract, just display the data */
data = "$0-";
g_free(abstract);
} else {
g_tree_insert(block_list, abstract, abstract);
}
abstract = g_strdup(data);
/* we'll need to get the data part. it may contain
more abstracts, they are _NOT_ expanded. */
data = theme_format_expand_get(theme, formatp);
len = strlen(data);
if (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') {
/* ends with $<digit> .. this breaks things if next
character is digit or '-' */
char digit, *tmp;
tmp = data;
digit = tmp[len-1];
tmp[len-1] = '\0';
data = g_strdup_printf("%s{%c}", tmp, digit);
g_free(tmp);
}
ret = parse_special_string(abstract, NULL, NULL, data, NULL,
PARSE_FLAG_ONLY_ARGS);
g_free(abstract);
g_free(data);
str = g_string_new(NULL);
p = ret;
while (*p != '\0') {
if (*p == '\\') {
int chr;
p++;
chr = expand_escape(&p);
g_string_append_c(str, chr != -1 ? chr : *p);
} else
g_string_append_c(str, *p);
p++;
}
g_free(ret);
abstract = str->str;
g_string_free(str, FALSE);
/* abstract may itself contain abstracts or replaces */
p = abstract;
ret = theme_format_expand_data_rec(theme, &p, default_fg, default_bg, last_fg, last_bg,
flags | EXPAND_FLAG_LASTCOLOR_ARG, block_list);
g_free(abstract);
g_tree_unref(block_list);
return ret;
} | 1 | CVE-2018-7051 | 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,130 |
linux | 6062a8dc0517bce23e3c2f7d2fea5e22411269a3 | SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
unsigned, nsops, const struct timespec __user *, timeout)
{
int error = -EINVAL;
struct sem_array *sma;
struct sembuf fast_sops[SEMOPM_FAST];
struct sembuf* sops = fast_sops, *sop;
struct sem_undo *un;
int undos = 0, alter = 0, max;
struct sem_queue queue;
unsigned long jiffies_left = 0;
struct ipc_namespace *ns;
struct list_head tasks;
ns = current->nsproxy->ipc_ns;
if (nsops < 1 || semid < 0)
return -EINVAL;
if (nsops > ns->sc_semopm)
return -E2BIG;
if(nsops > SEMOPM_FAST) {
sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
if(sops==NULL)
return -ENOMEM;
}
if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
error=-EFAULT;
goto out_free;
}
if (timeout) {
struct timespec _timeout;
if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
error = -EFAULT;
goto out_free;
}
if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
_timeout.tv_nsec >= 1000000000L) {
error = -EINVAL;
goto out_free;
}
jiffies_left = timespec_to_jiffies(&_timeout);
}
max = 0;
for (sop = sops; sop < sops + nsops; sop++) {
if (sop->sem_num >= max)
max = sop->sem_num;
if (sop->sem_flg & SEM_UNDO)
undos = 1;
if (sop->sem_op != 0)
alter = 1;
}
if (undos) {
un = find_alloc_undo(ns, semid);
if (IS_ERR(un)) {
error = PTR_ERR(un);
goto out_free;
}
} else
un = NULL;
INIT_LIST_HEAD(&tasks);
rcu_read_lock();
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
if (un)
rcu_read_unlock();
error = PTR_ERR(sma);
goto out_free;
}
error = -EFBIG;
if (max >= sma->sem_nsems) {
rcu_read_unlock();
goto out_wakeup;
}
error = -EACCES;
if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
rcu_read_unlock();
goto out_wakeup;
}
error = security_sem_semop(sma, sops, nsops, alter);
if (error) {
rcu_read_unlock();
goto out_wakeup;
}
/*
* semid identifiers are not unique - find_alloc_undo may have
* allocated an undo structure, it was invalidated by an RMID
* and now a new array with received the same id. Check and fail.
* This case can be detected checking un->semid. The existence of
* "un" itself is guaranteed by rcu.
*/
error = -EIDRM;
ipc_lock_object(&sma->sem_perm);
if (un) {
if (un->semid == -1) {
rcu_read_unlock();
goto out_unlock_free;
} else {
/*
* rcu lock can be released, "un" cannot disappear:
* - sem_lock is acquired, thus IPC_RMID is
* impossible.
* - exit_sem is impossible, it always operates on
* current (or a dead task).
*/
rcu_read_unlock();
}
}
error = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current));
if (error <= 0) {
if (alter && error == 0)
do_smart_update(sma, sops, nsops, 1, &tasks);
goto out_unlock_free;
}
/* We need to sleep on this operation, so we put the current
* task into the pending queue and go to sleep.
*/
queue.sops = sops;
queue.nsops = nsops;
queue.undo = un;
queue.pid = task_tgid_vnr(current);
queue.alter = alter;
if (nsops == 1) {
struct sem *curr;
curr = &sma->sem_base[sops->sem_num];
if (alter)
list_add_tail(&queue.list, &curr->sem_pending);
else
list_add(&queue.list, &curr->sem_pending);
} else {
if (alter)
list_add_tail(&queue.list, &sma->sem_pending);
else
list_add(&queue.list, &sma->sem_pending);
sma->complex_count++;
}
queue.status = -EINTR;
queue.sleeper = current;
sleep_again:
current->state = TASK_INTERRUPTIBLE;
sem_unlock(sma);
if (timeout)
jiffies_left = schedule_timeout(jiffies_left);
else
schedule();
error = get_queue_result(&queue);
if (error != -EINTR) {
/* fast path: update_queue already obtained all requested
* resources.
* Perform a smp_mb(): User space could assume that semop()
* is a memory barrier: Without the mb(), the cpu could
* speculatively read in user space stale data that was
* overwritten by the previous owner of the semaphore.
*/
smp_mb();
goto out_free;
}
sma = sem_obtain_lock(ns, semid);
/*
* Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing.
*/
error = get_queue_result(&queue);
/*
* Array removed? If yes, leave without sem_unlock().
*/
if (IS_ERR(sma)) {
goto out_free;
}
/*
* If queue.status != -EINTR we are woken up by another process.
* Leave without unlink_queue(), but with sem_unlock().
*/
if (error != -EINTR) {
goto out_unlock_free;
}
/*
* If an interrupt occurred we have to clean up the queue
*/
if (timeout && jiffies_left == 0)
error = -EAGAIN;
/*
* If the wakeup was spurious, just retry
*/
if (error == -EINTR && !signal_pending(current))
goto sleep_again;
unlink_queue(sma, &queue);
out_unlock_free:
sem_unlock(sma);
out_wakeup:
wake_up_sem_queue_do(&tasks);
out_free:
if(sops != fast_sops)
kfree(sops);
return error;
}
| 1 | CVE-2013-4483 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 5,836 |
Chrome | f084d7007f67809ef116ee6b11f251bf3c9ed895 | static void willRemoveChildren(ContainerNode* container)
{
NodeVector children;
getChildNodes(container, children);
container->document().nodeChildrenWillBeRemoved(container);
ChildListMutationScope mutation(container);
for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
Node* child = it->get();
mutation.willRemoveChild(child);
child->notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
}
ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
}
| 1 | CVE-2013-6625 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 689 |
ImageMagick | 97aa7d7cfd2027f6ba7ce42caf8b798541b9cdc6 | static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format[MaxTextExtent],
keyword[MaxTextExtent],
tag[MaxTextExtent],
value[MaxTextExtent];
double
gamma;
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
ssize_t
count,
y;
unsigned char
*end,
pixel[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
image->columns=0;
image->rows=0;
*format='\0';
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
while (isgraph(c) && (image->columns == 0) && (image->rows == 0))
{
if (c == (int) '#')
{
char
*comment;
register char
*p;
size_t
length;
/*
Read comment-- any text between # and end-of-line.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if ((c == EOF) || (c == (int) '\n'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) == MagickFalse)
c=ReadBlobByte(image);
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
}
if (LocaleCompare(keyword,"Y") == 0)
value_expected=MagickTrue;
if (value_expected == MagickFalse)
continue;
p=value;
while ((c != '\n') && (c != '\0') && (c != EOF))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"format") == 0)
{
(void) CopyMagickString(format,value,MaxTextExtent);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"primaries") == 0)
{
float
chromaticity[6],
white_point[2];
if (sscanf(value,"%g %g %g %g %g %g %g %g",&chromaticity[0],
&chromaticity[1],&chromaticity[2],&chromaticity[3],
&chromaticity[4],&chromaticity[5],&white_point[0],
&white_point[1]) == 8)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
image->chromaticity.white_point.x=white_point[0],
image->chromaticity.white_point.y=white_point[1];
}
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'Y':
case 'y':
{
char
target[] = "Y";
if (strcmp(keyword,target) == 0)
{
int
height,
width;
if (sscanf(value,"%d +X %d",&height,&width) == 2)
{
image->columns=(size_t) width;
image->rows=(size_t) height;
}
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
default:
{
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
}
}
if ((image->columns == 0) && (image->rows == 0))
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) &&
(LocaleCompare(format,"32-bit_rle_xyze") != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) SetImageColorspace(image,RGBColorspace,exception);
if (LocaleCompare(format,"32-bit_rle_xyze") == 0)
(void) SetImageColorspace(image,XYZColorspace,exception);
image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
NoCompression : RLECompression;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Read RGBE (red+green+blue+exponent) pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
if (image->compression != RLECompression)
{
count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
else
{
count=ReadBlob(image,4*sizeof(*pixel),pixel);
if (count != 4)
break;
if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
{
(void) memcpy(pixels,pixel,4*sizeof(*pixel));
count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
image->compression=NoCompression;
}
else
{
p=pixels;
for (i=0; i < 4; i++)
{
end=&pixels[(i+1)*image->columns];
while (p < end)
{
count=ReadBlob(image,2*sizeof(*pixel),pixel);
if (count < 1)
break;
if (pixel[0] > 128)
{
count=(ssize_t) pixel[0]-128;
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
while (count-- > 0)
*p++=pixel[1];
}
else
{
count=(ssize_t) pixel[0];
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
*p++=pixel[1];
if (--count > 0)
{
count=ReadBlob(image,(size_t) count*sizeof(*p),p);
if (count < 1)
break;
p+=count;
}
}
}
}
}
}
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->compression == RLECompression)
{
pixel[0]=pixels[x];
pixel[1]=pixels[x+image->columns];
pixel[2]=pixels[x+2*image->columns];
pixel[3]=pixels[x+3*image->columns];
}
else
{
pixel[0]=pixels[i++];
pixel[1]=pixels[i++];
pixel[2]=pixels[i++];
pixel[3]=pixels[i++];
}
SetPixelRed(image,0,q);
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
if (pixel[3] != 0)
{
gamma=pow(2.0,pixel[3]-(128.0+8.0));
SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q);
SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q);
SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,981 |
libmodbus | b4ef4c17d618eba0adccc4c7d9e9a1ef809fc9b6 | static int write_single(modbus_t *ctx, int function, int addr, const uint16_t value)
{
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx, function, addr, (int) value, req);
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
/* Used by write_bit and write_register */
uint8_t rsp[MAX_MESSAGE_LENGTH];
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
}
return rc;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,277 |
linux | 8fff105e13041e49b82f92eef034f363a6b1c071 | validate_group(struct perf_event *event)
{
struct perf_event *sibling, *leader = event->group_leader;
struct pmu_hw_events fake_pmu;
DECLARE_BITMAP(fake_used_mask, ARMPMU_MAX_HWEVENTS);
/*
* Initialise the fake PMU. We only need to populate the
* used_mask for the purposes of validation.
*/
memset(fake_used_mask, 0, sizeof(fake_used_mask));
fake_pmu.used_mask = fake_used_mask;
if (!validate_event(&fake_pmu, leader))
return -EINVAL;
list_for_each_entry(sibling, &leader->sibling_list, group_entry) {
if (!validate_event(&fake_pmu, sibling))
return -EINVAL;
}
if (!validate_event(&fake_pmu, event))
return -EINVAL;
return 0;
}
| 1 | CVE-2015-8955 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 2,017 |
libtiff | 3ca657a8793dd011bf869695d72ad31c779c3cc1 | horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
}
| 1 | CVE-2016-9535 | 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). | 844 |
libmobi | eafc415bc6067e72577f70d6dd5acbf057ce6e6f | MOBI_RET mobi_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) {
int pos = *decoded_size;
char mod = 'i';
char dir = '<';
char olddir;
unsigned char c;
while ((c = *rule++)) {
if (c <= 4) {
mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */
olddir = dir;
dir = (c & 2) ? '<' : '>'; /* left, right */
if (olddir != dir && olddir) {
pos = (c & 2) ? *decoded_size : 0;
}
}
else if (c > 10 && c < 20) {
if (dir == '>') {
pos = *decoded_size;
}
pos -= c - 10;
dir = 0;
if (pos < 0 || pos > *decoded_size) {
debug_print("Position setting failed (%s)\n", decoded);
return MOBI_DATA_CORRUPT;
}
}
else {
if (mod == 'i') {
const unsigned char *s = decoded + pos;
unsigned char *d = decoded + pos + 1;
const int l = *decoded_size - pos;
if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {
debug_print("Out of buffer in %s at pos: %i\n", decoded, pos);
return MOBI_DATA_CORRUPT;
}
memmove(d, s, (size_t) l);
decoded[pos] = c;
(*decoded_size)++;
if (dir == '>') { pos++; }
} else {
if (dir == '<') { pos--; }
const unsigned char *s = decoded + pos + 1;
unsigned char *d = decoded + pos;
const int l = *decoded_size - pos;
if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {
debug_print("Out of buffer in %s at pos: %i\n", decoded, pos);
return MOBI_DATA_CORRUPT;
}
if (decoded[pos] != c) {
debug_print("Character mismatch in %s at pos: %i (%c != %c)\n", decoded, pos, decoded[pos], c);
return MOBI_DATA_CORRUPT;
}
memmove(d, s, (size_t) l);
(*decoded_size)--;
}
}
}
return MOBI_SUCCESS;
} | 1 | CVE-2022-1533 | 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). | 6,815 |
tensorflow | 290bb05c80c327ed74fae1d089f1001b1e2a4ef7 | void Compute(OpKernelContext* c) override {
const Tensor& tensor = c->input(0);
Summary s;
Summary::Value* v = s.add_value();
v->set_node_name(c->op_kernel().name());
if (tensor.dtype() == DT_STRING) {
// tensor_util.makeNdarray doesn't work for strings in tensor_content
tensor.AsProtoField(v->mutable_tensor());
} else {
tensor.AsProtoTensorContent(v->mutable_tensor());
}
Tensor* summary_tensor = nullptr;
OP_REQUIRES_OK(c, c->allocate_output(0, TensorShape({}), &summary_tensor));
CHECK(SerializeToTString(s, &summary_tensor->scalar<tstring>()()));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,057 |
libtiff | 48780b4fcc425cddc4ef8ffdf536f96a0d1b313b | DECLAREContigPutFunc(putagreytile)
{
int samplesperpixel = img->samplesperpixel;
uint32** BWmap = img->BWmap;
(void) y;
while (h-- > 0) {
for (x = w; x-- > 0;)
{
*cp++ = BWmap[*pp][0] & (*(pp+1) << 24 | ~A1);
pp += samplesperpixel;
}
cp += toskew;
pp += fromskew;
}
} | 1 | CVE-2017-7592 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 6,147 |
linux | 263b4509ec4d47e0da3e753f85a39ea12d1eff24 | nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
if (pnfs_mark_request_commit(req, lseg, cinfo))
return;
nfs_request_add_commit_list(req, &cinfo->mds->list, cinfo);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,021 |
linux | 129a72a0d3c8e139a04512325384fe5ac119e74d | static int em_fxsave(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
size_t size;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->ops->get_fpu(ctxt);
rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
ctxt->ops->put_fpu(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)
size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]);
else
size = offsetof(struct fxregs_state, xmm_space[0]);
return segmented_write(ctxt, ctxt->memop.addr.mem, &fx_state, size);
}
| 1 | CVE-2017-2584 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 3,071 |
linux | ce40cd3fc7fa40a6119e5fe6c0f2bc0eb4541009 | static inline u32 kvm_apic_get_reg(struct kvm_lapic *apic, int reg_off)
{
return *((u32 *) (apic->regs + reg_off));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,131 |
ImageMagick | cc4ac341f29fa368da6ef01c207deaf8c61f6a2e | static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y,
static MagickBooleanType InsertRow(Image *image,ssize_t bpp,unsigned char *p,
ssize_t y,ExceptionInfo *exception)
{
int
bit;
Quantum
index;
register Quantum
*q;
ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
break;
}
case 2: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
break;
}
case 4: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x0f,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
break;
}
case 8: /* Convert PseudoColor scanline. */
{
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
}
break;
case 24: /* Convert DirectColor scanline. */
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
break;
}
if (!SyncAuthenticPixels(image,exception))
return(MagickFalse);
return(MagickTrue);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,393 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | unsigned long ContentEncoding::GetCompressionCount() const {
const ptrdiff_t count = compression_entries_end_ - compression_entries_;
assert(count >= 0);
return static_cast<unsigned long>(count);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,726 |
tty | 15b3cd8ef46ad1b100e0d3c7e38774f330726820 | int con_get_unimap(struct vc_data *vc, ushort ct, ushort __user *uct, struct unipair __user *list)
{
int i, j, k, ret = 0;
ushort ect;
u16 **p1, *p2;
struct uni_pagedir *p;
struct unipair *unilist;
unilist = kvmalloc_array(ct, sizeof(struct unipair), GFP_KERNEL);
if (!unilist)
return -ENOMEM;
console_lock();
ect = 0;
if (*vc->vc_uni_pagedir_loc) {
p = *vc->vc_uni_pagedir_loc;
for (i = 0; i < 32; i++) {
p1 = p->uni_pgdir[i];
if (p1)
for (j = 0; j < 32; j++) {
p2 = *(p1++);
if (p2)
for (k = 0; k < 64; k++, p2++) {
if (*p2 >= MAX_GLYPH)
continue;
if (ect < ct) {
unilist[ect].unicode =
(i<<11)+(j<<6)+k;
unilist[ect].fontpos = *p2;
}
ect++;
}
}
}
}
console_unlock();
if (copy_to_user(list, unilist, min(ect, ct) * sizeof(struct unipair)))
ret = -EFAULT;
put_user(ect, uct);
kvfree(unilist);
return ret ? ret : (ect <= ct) ? 0 : -ENOMEM;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,613 |
ImageMagick | f6e9d0d9955e85bdd7540b251cd50d598dacc5e6 | static Image *ReadTTFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
buffer[MaxTextExtent],
*text;
const char
*Text = (char *)
"abcdefghijklmnopqrstuvwxyz\n"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
"0123456789.:,;(*!?}^)#${%^&-+@\n";
const TypeInfo
*type_info;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
PixelPacket
background_color;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
image->columns=800;
image->rows=480;
type_info=GetTypeInfo(image_info->filename,exception);
if ((type_info != (const TypeInfo *) NULL) &&
(type_info->glyphs != (char *) NULL))
(void) CopyMagickString(image->filename,type_info->glyphs,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Color canvas with background color
*/
background_color=image_info->background_color;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=background_color;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent);
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
/*
Prepare drawing commands
*/
y=20;
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->font=AcquireString(image->filename);
ConcatenateString(&draw_info->primitive,"push graphic-context\n");
(void) FormatLocaleString(buffer,MaxTextExtent," viewbox 0 0 %.20g %.20g\n",
(double) image->columns,(double) image->rows);
ConcatenateString(&draw_info->primitive,buffer);
ConcatenateString(&draw_info->primitive," font-size 18\n");
(void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '",(double) y);
ConcatenateString(&draw_info->primitive,buffer);
text=EscapeString(Text,'"');
ConcatenateString(&draw_info->primitive,text);
text=DestroyString(text);
(void) FormatLocaleString(buffer,MaxTextExtent,"'\n");
ConcatenateString(&draw_info->primitive,buffer);
y+=20*(ssize_t) MultilineCensus((char *) Text)+20;
for (i=12; i <= 72; i+=6)
{
y+=i+12;
ConcatenateString(&draw_info->primitive," font-size 18\n");
(void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '%.20g'\n",
(double) y,(double) i);
ConcatenateString(&draw_info->primitive,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent," font-size %.20g\n",
(double) i);
ConcatenateString(&draw_info->primitive,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent," text 50,%.20g "
"'That which does not destroy me, only makes me stronger.'\n",(double) y);
ConcatenateString(&draw_info->primitive,buffer);
if (i >= 24)
i+=6;
}
ConcatenateString(&draw_info->primitive,"pop graphic-context");
(void) DrawImage(image,draw_info);
/*
Relinquish resources.
*/
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 1 | CVE-2016-10066 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 5,005 |
php-src | c4cca4c20e75359c9a13a1f9a36cb7b4e9601d29 | */
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i], strlen(atts[i]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} | 1 | CVE-2016-7418 | 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,823 |
FFmpeg | 18f94df8af04f2c02a25a7dec512289feff6517f | static int32_t decode_rice(GetBitContext *gb, unsigned int k)
{
int max = get_bits_left(gb) - k;
int q = get_unary(gb, 0, max);
int r = k ? get_bits1(gb) : !(q & 1);
if (k > 1) {
q <<= (k - 1);
q += get_bits_long(gb, k - 1);
} else if (!k) {
q >>= 1;
}
return r ? q : ~q;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,069 |
FFmpeg | 189ff4219644532bdfa7bab28dfedaee4d6d4021 | static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
seg = current_segment(v);
/* load/update Media Initialization Section, if any */
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
/* Push init section out first before first actual segment */
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,068 |
linux | 6acb47d1a318e5b3b7115354ebc4ea060c59d3a1 | static int __serdes_write_mcb_s1g(struct regmap *regmap, u8 macro, u32 op)
{
unsigned int regval;
regmap_write(regmap, HSIO_MCB_S1G_ADDR_CFG, op |
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_ADDR(BIT(macro)));
return regmap_read_poll_timeout(regmap, HSIO_MCB_S1G_ADDR_CFG, regval,
(regval & op) != op, 100,
MCB_S1G_CFG_TIMEOUT * 1000);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,931 |
qemu | defac5e2fbddf8423a354ff0454283a2115e1367 | static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)
{
FDrive *cur_drv;
uint8_t kh, kt, ks;
SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
cur_drv = get_cur_drv(fdctrl);
kt = fdctrl->fifo[2];
kh = fdctrl->fifo[3];
ks = fdctrl->fifo[4];
FLOPPY_DPRINTF("Start transfer at %d %d %02x %02x (%d)\n",
GET_CUR_DRV(fdctrl), kh, kt, ks,
fd_sector_calc(kh, kt, ks, cur_drv->last_sect,
NUM_SIDES(cur_drv)));
switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
case 2:
/* sect too big */
fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
fdctrl->fifo[3] = kt;
fdctrl->fifo[4] = kh;
fdctrl->fifo[5] = ks;
return;
case 3:
/* track too big */
fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
fdctrl->fifo[3] = kt;
fdctrl->fifo[4] = kh;
fdctrl->fifo[5] = ks;
return;
case 4:
/* No seek enabled */
fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
fdctrl->fifo[3] = kt;
fdctrl->fifo[4] = kh;
fdctrl->fifo[5] = ks;
return;
case 1:
fdctrl->status0 |= FD_SR0_SEEK;
break;
default:
break;
}
/* Check the data rate. If the programmed data rate does not match
* the currently inserted medium, the operation has to fail. */
if ((fdctrl->dsr & FD_DSR_DRATEMASK) != cur_drv->media_rate) {
FLOPPY_DPRINTF("data rate mismatch (fdc=%d, media=%d)\n",
fdctrl->dsr & FD_DSR_DRATEMASK, cur_drv->media_rate);
fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);
fdctrl->fifo[3] = kt;
fdctrl->fifo[4] = kh;
fdctrl->fifo[5] = ks;
return;
}
/* Set the FIFO state */
fdctrl->data_dir = direction;
fdctrl->data_pos = 0;
assert(fdctrl->msr & FD_MSR_CMDBUSY);
if (fdctrl->fifo[0] & 0x80)
fdctrl->data_state |= FD_STATE_MULTI;
else
fdctrl->data_state &= ~FD_STATE_MULTI;
if (fdctrl->fifo[5] == 0) {
fdctrl->data_len = fdctrl->fifo[8];
} else {
int tmp;
fdctrl->data_len = 128 << (fdctrl->fifo[5] > 7 ? 7 : fdctrl->fifo[5]);
tmp = (fdctrl->fifo[6] - ks + 1);
if (fdctrl->fifo[0] & 0x80)
tmp += fdctrl->fifo[6];
fdctrl->data_len *= tmp;
}
fdctrl->eot = fdctrl->fifo[6];
if (fdctrl->dor & FD_DOR_DMAEN) {
/* DMA transfer is enabled. */
IsaDmaClass *k = ISADMA_GET_CLASS(fdctrl->dma);
FLOPPY_DPRINTF("direction=%d (%d - %d)\n",
direction, (128 << fdctrl->fifo[5]) *
(cur_drv->last_sect - ks + 1), fdctrl->data_len);
/* No access is allowed until DMA transfer has completed */
fdctrl->msr &= ~FD_MSR_RQM;
if (direction != FD_DIR_VERIFY) {
/*
* Now, we just have to wait for the DMA controller to
* recall us...
*/
k->hold_DREQ(fdctrl->dma, fdctrl->dma_chann);
k->schedule(fdctrl->dma);
} else {
/* Start transfer */
fdctrl_transfer_handler(fdctrl, fdctrl->dma_chann, 0,
fdctrl->data_len);
}
return;
}
FLOPPY_DPRINTF("start non-DMA transfer\n");
fdctrl->msr |= FD_MSR_NONDMA | FD_MSR_RQM;
if (direction != FD_DIR_WRITE)
fdctrl->msr |= FD_MSR_DIO;
/* IO based transfer: calculate len */
fdctrl_raise_irq(fdctrl);
} | 1 | CVE-2021-3507 | 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). | 9,617 |
Chrome | e741149a6b7872a2bf1f2b6cc0a56e836592fb77 | xsltCurrentFunction(xmlXPathParserContextPtr ctxt, int nargs){
xsltTransformContextPtr tctxt;
if (nargs != 0) {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"current() : function uses no argument\n");
ctxt->error = XPATH_INVALID_ARITY;
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
if (tctxt == NULL) {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"current() : internal error tctxt == NULL\n");
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
} else {
valuePush(ctxt, xmlXPathNewNodeSet(tctxt->node)); /* current */
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,488 |
linux | cb222aed03d798fc074be55e59d9a112338ee784 | static unsigned int input_estimate_events_per_packet(struct input_dev *dev)
{
int mt_slots;
int i;
unsigned int events;
if (dev->mt) {
mt_slots = dev->mt->num_slots;
} else if (test_bit(ABS_MT_TRACKING_ID, dev->absbit)) {
mt_slots = dev->absinfo[ABS_MT_TRACKING_ID].maximum -
dev->absinfo[ABS_MT_TRACKING_ID].minimum + 1,
mt_slots = clamp(mt_slots, 2, 32);
} else if (test_bit(ABS_MT_POSITION_X, dev->absbit)) {
mt_slots = 2;
} else {
mt_slots = 0;
}
events = mt_slots + 1; /* count SYN_MT_REPORT and SYN_REPORT */
if (test_bit(EV_ABS, dev->evbit))
for_each_set_bit(i, dev->absbit, ABS_CNT)
events += input_is_mt_axis(i) ? mt_slots : 1;
if (test_bit(EV_REL, dev->evbit))
events += bitmap_weight(dev->relbit, REL_CNT);
/* Make room for KEY and MSC events */
events += 7;
return events;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,479 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.