The software uses external input to construct a pathname that
should be within a restricted directory, but it does not properly sanitize
absolute path sequences such as "/abs/path" that can resolve to a location that
is outside of that directory.
Extended Description
This allows attackers to traverse the file system to access files or
directories that are outside of the restricted directory.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Demonstrative Examples
In the example below, the path to a dictionary file is read from a
system property and used to initialize a File object without having been
sanitized. Ideally, the path should be resolved relative to some kind of
application or user home directory.
Acceptance of Extraneous Untrusted Data With Trusted Data
Status: Draft
Weakness ID: 349 (Weakness Base)
Description
Summary
The software, when processing trusted data, accepts any
untrusted data that is also included with the trusted data, treating the
untrusted data as if it were trusted.
Improper administration of the permissions to the users of a
system can result in unintended access to sensitive files.
Alternate Terms
Authorization
The terms "authorization" and "access control" seem to be used
interchangeable.
Time of Introduction
Architecture and Design
Implementation
Operation
Potential Mitigations
Very carefully manage the setting, management and handling of
privileges. Explicitly manage trust zones in the software.
Architecture and Design
Ensure that appropriate compartmentalization is built into the system
design and that the compartmentalization serves to allow for and further
reinforce privilege separation functionality. Architects and designers
should rely on the principle of least privilege to decide when it is
appropriate to use and to drop system privileges.
Background Details
An access control list (ACL) represents who/what has permissions to a
given object. Different operating systems implement (ACLs) in different
ways. In UNIX, there are three types of permissions: read, write, and
execute. Users are divided into three classes for file access: owner, group
owner, and all other users where each class has a separate set of rights. In
Windows NT, there are four basic types of permissions for files: "No
access", "Read access", "Change access", and "Full control". Windows NT
extends the concept of three types of users in UNIX to include a list of
users and groups along with their associated permissions. A user can create
an object (file) and assign specified permissions to that object.
The name of this item implies that it is a category for general access
control / authorization issues, although the description is limited to
permissions.
This item needs more work. Possible sub-categories include:
The system's access control functionality does not prevent one
user from gaining access to another user's records by modifying the key value
identifying the record.
Extended Description
Retrieval of a user record occurs in the system based on some key value
that is under user control. The key would typically identify a user related
record stored in the system and would be used to lookup that record for
presentation to the user. It is likely that an attacker would have to be an
authenticated user in the system. However, the authorization process would
not properly check the data access operation to ensure that the
authenticated user performing the operation has sufficient entitlements to
perform the requested data access, hence bypassing any other authorization
checks present in the system. One manifestation of this weakness would be if
a system used sequential or otherwise easily guessable session ids that
would allow one user to easily switch to another user's session and
view/modify their data.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Common Consequences
Access control checks for specific user data or functionality can be
bypassed.
Horizontal escalation of privilege is possible (one user can
view/modify information of another user)
Vertical escalation of privilege is possible if the user controlled
key is actually an admin flag allowing to gain administrative
access
Likelihood of Exploit
High
Enabling Factors for Exploitation
The key used internally in the system to identify the user record can be
externally controlled. For example attackers can look at places where user
specific data is retrieved (e.g. search screens) and determine whether the
key for the item being looked up is controllable externally. The key may be
a hidden field in the HTML form field, might be passed as a URL parameter or
as an unencrypted cookie variable, then in each of these cases it will be
possible to tamper with the key value.
Potential Mitigations
Make sure that the key that is used in the lookup of a specific user's
record is not controllable externally by the user or that any tampering
can be detected.
Use encryption in order to make it more difficult to guess other
legitimate values of the key or associate a digital signature with the
key so that the server can verify that there has been no tampering..
Ensure that access control mechanisms cannot be bypassed by ensuring
that the user has sufficient privilege to access the record that is
being requested given his authenticated identity on each and every data
access.
Access Control Bypass Through User-Controlled SQL Primary Key
Status: Incomplete
Weakness ID: 566 (Weakness Variant)
Description
Summary
Without proper access control, executing a SQL statement that
contains a user-controlled primary key can allow an attacker to view
unauthorized records.
Time of Introduction
Architecture and Design
Implementation
Demonstrative Examples
The following code uses a parameterized statement, which escapes
metacharacters and prevents SQL injection vulnerabilities, to construct and
execute a SQL query that searches for an invoice matching the specified
identifier [1]. The identifier is selected from a list of all invoices
associated with the current authenticated user.
...
conn = new SqlConnection(_ConnectionString);
conn.Open();
int16 id = System.Convert.ToInt16(invoiceID.Text);
SqlCommand query = new SqlCommand( "SELECT * FROM invoices WHERE
id = @id", conn);
The problem is that the developer has failed to consider all of the
possible values of id. Although the interface generates a list of
invoice identifiers that belong to the current user, an attacker can
bypass this interface to request any desired invoice. Because the code
in this example does not check to ensure that the user has permission to
access the requested invoice, it will display any invoice, even if it
does not belong to the current user.
Potential Mitigations
Assume all input is malicious. Use a standard input validation
mechanism to validate all input for length, type, syntax, and business
rules before accepting the data. Use an "accept known good" validation
strategy.
Use a parametized query AND make sure that the accepted values conform
to the business rules. Construct your SQL statement accordingly.
Other Notes
Database access control errors occur when: 1. Data enters a program from
an untrusted source. 2. The data is used to specify the value of a primary
key in a SQL query.
Access to Critical Private Variable via Public Method
Status: Incomplete
Weakness ID: 767 (Weakness Variant)
Description
Summary
The software defines a public method that reads or modifies a
private variable.
Extended Description
If an attacker modifies the variable to contain unexpected values, this
could violate assumptions from other parts of the code. Additionally, if an
attacker can read the private variable, it may expose sensitive information
or make it easier to launch further attacks.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C++
C#
Java
Likelihood of Exploit
Low to Medium
Demonstrative Examples
Example 1:
The following example declares a critical variable to be private,
and then allows the variable to be modified by public methods.
C++ Example:
private: float price;
public: void changePrice(float newPrice) {
price = newPrice;
}
Example 2:
The following example could be used to implement a user forum where
a single user (UID) can switch between multiple profiles (PID).
Java Example:
public class Client {
private int UID;
public int PID;
private String userName;
public Client(String userName){
PID = getDefaultProfileID();
UID = mapUserNametoUID( userName );
this.userName = userName;
}
public void setPID(int ID) {
UID = ID;
}
}
The programmer implemented setPID with the intention of modifying the
PID variable, but due to a typo. accidentally specified the critical
variable UID instead. If the program allows profile IDs to be between 1
and 10, but a UID of 1 means the user is treated as an admin, then a
user could gain administrative privileges as a result of this
typo.
Potential Mitigations
Implementation
Use class accessor and mutator methods appropriately. Perform
validation when accepting data from a public method that is intended to
modify a critical private variable. Also be sure that appropriate access
controls are being applied when a public method interfaces with critical
data.
This entry is closely associated with access control for public methods.
If the public methods are restricted with proper access controls, then the
information in the private variable will not be exposed to unexpected
parties. There may be chaining or composite relationships between improper
access controls and this weakness.
Pre-design: Use a language or compiler that performs automatic bounds
checking.
Architecture and Design
Use an abstraction library to abstract away risky APIs. Not a complete
solution.
Pre-design through Build: Compiler-based canary mechanisms such as
StackGuard, ProPolice, and Microsoft Visual Studio /GS flag. Unless this
provides automatic bounds checking, it is not a complete
solution.
Operational: Use OS-level preventative functionality. Not a complete
solution.
Other Notes
Data-structure sentinels are often used to mark structure of the data
structure. A common example of this is the null character at the end of
strings. Another common example is linked lists which may contain a sentinel
to mark the end of the list. It is, of course dangerous, to allow this type
of control data to be easily accessible. Therefore, it is important to
protect from the addition or modification outside of some wrapper interface
which provides safety. By adding a sentinel, one potentially could cause
data to be truncated early.
An algorithm in a product has an inefficient worst-case
computational complexity that may be detrimental to system performance and can
be triggered by an attacker, typically using crafted manipulations that ensure
that the worst case is being reached.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Common Consequences
The typical consequence is CPU consumption, but memory consumption and
consumption of other resources can also occur.
Product allows attackers to cause multiple copies
of a program to be loaded more quickly than the program can detect that
other copies are running, then exit. This type of error should probably have
its own category, where teardown takes more time than
initialization.
Allocation of File Descriptors or Handles Without Limits or Throttling
Status: Incomplete
Weakness ID: 774 (Weakness Variant)
Description
Summary
The software allocates file descriptors or handles on behalf of
an actor without imposing any restrictions on how many descriptors can be
allocated, in violation of the intended security policy for that
actor.
Extended Description
This can cause the software to consume all available file descriptors or
handles, which can prevent other processes from performing critical file
processing operations.
Time of Introduction
Architecture and Design
Implementation
Common Consequences
Availability
When allocating resources without limits, an attacker could prevent
all other processes from accessing the same type of resource.
Likelihood of Exploit
Medium to High
Potential Mitigations
Implementation
For system resources, consider using the getrlimit() function included
in the sys/resources library in order to determine how many resources
are currently allowed to be opened for the process.
When the current levels get close to the maximum that is defined for
the application (see CWE-770), then limit the allocation of further
resources to privileged users; alternately, begin releasing resources
for less-privileged users. While this mitigation may protect the system
from attack, it will not necessarily stop attackers from adversely
impacting other users.
C Example:
#include <sys/resource.h>
...
int return_value;
struct rlimit rlp;
...
return_value = getrlimit(RLIMIT_NOFILE, &rlp);
Operation
Use resource-limiting settings provided by the operating system or
environment. For example, setrlimit() can be used to set limits for
certain types of resources. However, this is not available on all
operating systems.
Ensure that your application performs the appropriate error checks and
error handling in case resources become unavailable (CWE-703).
Vulnerability theory is largely about how behaviors and resources
interact. "Resource exhaustion" can be regarded as either a consequence or
an attack, depending on the perspective. This entry is an attempt to reflect
one of the underlying weaknesses that enable these attacks (or consequences)
to take place.
Allocation of Resources Without Limits or Throttling
Status: Incomplete
Weakness ID: 770 (Weakness Base)
Description
Summary
The software allocates a reusable resource or group of
resources on behalf of an actor without imposing any restrictions on how many
resources can be allocated, in violation of the intended security policy for
that actor.
Time of Introduction
Architecture and Design
Implementation
Common Consequences
Availability
When allocating resources without limits, an attacker could prevent
all other processes from accessing the same type of resource.
Likelihood of Exploit
Medium to High
Potential Mitigations
Architecture and Design
Limit the amount of resources that are accessible to unprivileged
users. Set per-user limits for resources. Allow the system administrator
to define these limits. Be careful to avoid CWE-410.
Implementation
For system resources, consider using the getrlimit() function included
in the sys/resources library in order to determine how many files are
currently allowed to be opened for the process.
C Example:
#include <sys/resource.h>
...
int return_value;
struct rlimit rlp;
...
return_value = getrlimit(RLIMIT_NOFILE, &rlp);
Operation
Use resource-limiting settings provided by the operating system or
environment. For example, setrlimit() can be used to set limits for
certain types of resources. However, this is not available on all
operating systems.
Ensure that your application performs the appropriate error checks and
error handling in case resources become unavailable (CWE-703).
Vulnerability theory is largely about how behaviors and resources
interact. "Resource exhaustion" can be regarded as either a consequence or
an attack, depending on the perspective. This entry is an attempt to reflect
one of the underlying weaknesses that enable these attacks (or consequences)
to take place.
Maintenance Notes
"Resource exhaustion" (CWE-400) is currently treated as a weakness,
although it is more like a category of weaknesses that all have the same
type of consequence. While this entry treats CWE-400 as a parent in view
1000, the relationship is probably more appropriately described as a
chain.
The code contains a control flow path that does not reflect the
algorithm that the path is intended to implement, leading to incorrect behavior
any time this path is navigated.
Extended Description
This weakness captures cases in which a particular code segment is always
incorrect with respect to the algorithm that it is implementing. For
example, if a C programmer intends to include multiple statements in a
single block but does not include the enclosing braces (CWE-483), then the
logic is always incorrect. This issue is in contrast to most weaknesses in
which the code usually behaves correctly, except when it is externally
manipulated in malicious ways.
Time of Introduction
Architecture and Design
Implementation
Operation
Other Notes
This issue typically appears in rarely-tested code, since the
"always-incorrect" nature will be detected as a bug during normal
usage.
This node could possibly be split into lower-level nodes. "Early Return"
is for returning control to the caller too soon (e.g., CWE-584). "Excess
Return" is when control is returned too far up the call stack (CWE-600,
CWE-395). "Improper control limitation" occurs when the product maintains
control at a lower level of execution, when control should be returned
"further" up the call stack (CWE-455). "Incorrect syntax" covers code that's
"just plain wrong" such as CWE-484 and CWE-483.
Software operating in a MAC OS environment, where .DS_Store is
in effect, must carefully manage hard links, otherwise an attacker may be able
to leverage a hard link from .DS_Store to overwrite arbitrary files and gain
privileges.
The Finder in Mac OS X and earlier allows local
users to overwrite arbitrary files and gain privileges by creating a hard
link from the .DS_Store file to an arbitrary
file.
This entry, which originated from PLOVER, probably stems from a common
manipulation that is used to exploit symlink and hard link following
weaknesses, like /etc/passwd is often used for UNIX-based exploits. As such,
it is probably too low-level for inclusion in CWE.
The software does not sufficiently delimit the arguments being
passed to a component in another control sphere, allowing alternate arguments to
be provided, leading to potentially security-relevant
changes.
Argument injection vulnerability in TellMe 1.2 and
earlier allows remote attackers to modify command line arguments for the
Whois program and obtain sensitive information via "--" style options in the
q_Host parameter.
Beagle before 0.2.5 can produce certain insecure
command lines to launch external helper applications while indexing, which
allows attackers to execute arbitrary commands. NOTE: it is not immediately
clear whether this issue involves argument injection, shell metacharacters,
or other issues.
Argument injection vulnerability in Internet
Explorer 6 for Windows XP SP2 allows user-assisted remote attackers to
modify command line arguments to an invoked mail client via " (double quote)
characters in a mailto: scheme handler, as demonstrated by launching
Microsoft Outlook with an arbitrary filename as an attachment. NOTE: it is
not clear whether this issue is implementation-specific or a problem in the
Microsoft API.
Argument injection vulnerability in Mozilla
Firefox 1.0.6 allows user-assisted remote attackers to modify command line
arguments to an invoked mail client via " (double quote) characters in a
mailto: scheme handler, as demonstrated by launching Microsoft Outlook with
an arbitrary filename as an attachment. NOTE: it is not clear whether this
issue is implementation-specific or a problem in the Microsoft
API.
Argument injection vulnerability in Avant Browser
10.1 Build 17 allows user-assisted remote attackers to modify command line
arguments to an invoked mail client via " (double quote) characters in a
mailto: scheme handler, as demonstrated by launching Microsoft Outlook with
an arbitrary filename as an attachment. NOTE: it is not clear whether this
issue is implementation-specific or a problem in the Microsoft
API.
Argument injection vulnerability in the URI
handler in Skype 2.0.*.104 and 2.5.*.0 through 2.5.*.78 for Windows allows
remote authorized attackers to download arbitrary files via a URL that
contains certain command-line switches.
Argument injection vulnerability in WinSCP 3.8.1
build 328 allows remote attackers to upload or download arbitrary files via
encoded spaces and double-quote characters in a scp or sftp
URI.
Argument injection vulnerability in the Windows
Object Packager (packager.exe) in Microsoft Windows XP SP1 and SP2 and
Server 2003 SP1 and earlier allows remote user-assisted attackers to execute
arbitrary commands via a crafted file with a "/" (slash) character in the
filename of the Command Line property, followed by a valid file extension,
which causes the command before the slash to be executed, aka "Object
Packager Dialogue Spoofing Vulnerability."
Argument injection vulnerability in HyperAccess
8.4 allows user-assisted remote attackers to execute arbitrary vbscript and
commands via the /r option in a telnet:// URI, which is configured to use
hawin32.exe.
Argument injection vulnerability in the telnet
daemon (in.telnetd) in Solaris 10 and 11 (SunOS 5.10 and 5.11) misinterprets
certain client "-f" sequences as valid requests for the login program to
skip authentication, which allows remote attackers to log into certain
accounts, as demonstrated by the bin account.
Potential Mitigations
Avoid using user-controlled input in command arguments.
Assume all input is malicious. Use an appropriate combination of black
lists and white lists to ensure only valid and expected input is
processed by the system.
Other Notes
At one layer of abstraction, this can overlap other weaknesses that have
whitespace problems, e.g. injection of javascript into attributes of HTML
tags.
Fault: unquoted special characters, input restriction error, unquoted
special terms, whitespace
Weakness Ordinalities
Primary(where the weakness
exists independent of other weaknesses)
The program declares an array public, final, and static, which
is not sufficient to prevent the array's contents from being
modified.
Extended Description
Because arrays are mutable objects, the final constraint requires that the
array object itself be assigned only once, but makes no guarantees about the
values of the array elements. Since the array is public, a malicious program
can change the values stored in the array. As such, in most cases an array
declared public, final and static is a bug.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
Demonstrative Examples
The following Java Applet code mistakenly declares an array public,
final and static.
Java Example:
public final class urlTool extends Applet {
public final static URL[] urls;
...
}
Potential Mitigations
In most situations the array should be made private.
Background Details
Mobile code, in this case a Java Applet, is code that is transmitted
across a network and executed on a remote machine. Because mobile code
developers have little if any control of the environment in which their code
will execute, special security concerns become relevant. One of the biggest
environmental threats results from the risk that the mobile code will run
side-by-side with other, potentially malicious, mobile code. Because all of
the popular web browsers execute code from multiple sources together in the
same JVM, many of the security guidelines for mobile code are focused on
preventing manipulation of your objects' state and behavior by adversaries
who have access to the same virtual machine where your program is
running.
Weakness Ordinalities
Primary(where the weakness
exists independent of other weaknesses)
Debugging messages help attackers learn about the system and
plan a form of attack.
Extended Description
ASP .NET applications can be configured to produce debug binaries. These
binaries give detailed debugging messages and should not be used in
production environments.
Time of Introduction
Implementation
Operation
Applicable Platforms
Languages
.NET
Demonstrative Examples
The file web.config contains the debug mode setting. Setting debug
to "true" will let the browser display debugging information.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
/>
...
</system.web>
</configuration>
Change the debug mode to false when the application is deployed into
production.
Potential Mitigations
Avoid releasing debug binaries into the production environment. Change
the debug mode to false when the application is deployed into production
(See demonstrative example).
Other Notes
The debug attribute of the <compilation> tag defines whether
compiled binaries should include debugging information. The use of debug
binaries causes an application to provide as much information about itself
as possible to the user. Debug binaries are meant to be used in a
development or testing environment and can pose a security risk if they are
deployed to production. Attackers can leverage the additional information
they gain from debugging output to mount attacks targeted on the framework,
database, or other resources used by the application.
ASP.NET Misconfiguration: Missing Custom Error Page
Status: Draft
Weakness ID: 12 (Weakness Variant)
Description
Summary
An ASP .NET application must enable custom error pages in order
to prevent attackers from mining information from the framework's built-in
responses.
Time of Introduction
Implementation
Operation
Applicable Platforms
Languages
.NET
Common Consequences
Confidentiality
Default error pages gives detailed information about the error that
occurred, and should not be used in production environments.
Demonstrative Examples
Example 1:
Custom error message mode is turned off. An ASP.NET error message
with detailed stack trace and platform versions will be
returned.
ASP.NET Example:
<customErrors ... mode="Off" />
Example 2:
Custom error message mode for remote user only. No defaultRedirect
error page is specified. The local user on the web server will see a
detailed stack trace. For remote users, an ASP.NET error message with the
server customError configuration setting and the platform version will be
returned.
ASP.NET Example:
<customErrors mode="RemoteOnly" />
Potential Mitigations
Handle exceptions appropriately in source code. The best practice is
to use a custom error message. Make sure that the mode attribute is set
to "RemoteOnly" in the web.config file as shown in the following
example.
<customErrors mode="RemoteOnly" />
The mode attribute of the <customErrors> tag in the
Web.config file defines whether custom or default error pages are used.
It should be configured to use a custom page as follows:
Do not attempt to process an error or attempt to mask it.
Verify return values are correct and do not supply sensitive
information about the system.
ASP .NET applications should be configured to use custom error pages
instead of the framework default page.
Other Notes
The mode attribute of the <customErrors> tag defines whether
custom or default error pages are used. Attackers can leverage the
additional information provided by a default error page to mount attacks
targeted on the framework, database, or other resources used by the
application.
ASP.NET Misconfiguration: Not Using Input Validation Framework
Status: Draft
Weakness ID: 554 (Weakness Variant)
Description
Summary
The ASP.NET application does not use an input validation
framework.
Extended Description
Unchecked input is the leading cause of vulnerabilities in ASP.NET
applications. Unchecked input leads to cross-site scripting, process
control, and SQL injection vulnerabilities, among others.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
.NET
Potential Mitigations
Use the ASP.NET validation framework to check all program input before
it is processed by the application. Example uses of the validation
framework include checking to ensure that: - Phone number fields contain
only valid characters in phone numbers - Boolean values are only "T" or
"F" - Free-form strings are of a reasonable length and composition
Other Notes
In certain versions of ASP.Net, there is an input validation error that
allows a malicious user to input some ASCII characters in a special Unicode
encoding in the range ff00 to ff60. When the response encoding is not
Unicode, these characters are decoded to their ASCII values, and this way
can be used to launch cross site scripting attacks. The relevant Unicode
strings are %uff1c, which is decoded to <, and %uff1e, which is
decoded to >.
ASP.NET Misconfiguration: Password in Configuration File
Status: Draft
Weakness ID: 13 (Weakness Variant)
Description
Summary
Storing a plaintext password in a configuration file allows
anyone who can read the file access to the password-protected resource making
them an easy target for attackers.
Time of Introduction
Architecture and Design
Implementation
Demonstrative Examples
The following connectionString has clear text
credentials.
ASP.NET Misconfiguration: Use of Identity Impersonation
Status: Incomplete
Weakness ID: 556 (Weakness Variant)
Description
Summary
Configuring an ASP.NET application to run with impersonated
credentials may give the application unnecessary
privileges.
Extended Description
The use of impersonated credentials allows an ASP.NET application to run
with either the privileges of the client on whose behalf it is executing or
with arbitrary privileges granted in its configuration.
The code uses an operator for assignment when the intention was
to perform a comparison.
Extended Description
In many languages the compare statement is very close in appearance to the
assignment statement and are often confused.
Time of Introduction
Implementation
Applicable Platforms
Languages
C
C++
Java
.NET
Likelihood of Exploit
Low
Demonstrative Examples
Example 1:
The following C/C++ and C# examples attempt to validate an int input
parameter against the integer value 100. However, the expression to be
evaluated in the if statement uses the assignment operator "=" rather than
the comparison operator "==". The result of using the assignment operator
instead of the comparison operator causes the int variable to be reassigned
locally and the expression in the if statement will always evaluate to the
value on the right hand side of the expression. This will result in the
input value not being properly validated, which can cause unexpected
results.
C/C# Example:
int isValid(int value) {
if (value=100) {
printf("Value is valid\n");
return(1);
}
printf("Value is not valid\n");
return(0);
}
C# Example:
bool isValid(int value) {
if (value=100) {
Console.WriteLine("Value is valid.");
return true;
}
Console.WriteLine("Value is not valid.");
return false;
}
Example 2:
In this example, we show how assigning instead of comparing can
impact code when values are being passed by reference instead of by value.
Consider a scenario in which a string is being processed from user input.
Assume the string has already been formatted such that different user inputs
are concatenated with the colon character. When the processString function
is called, the test for the colon character will result in an insertion of
the colon character instead, adding new input separators. Since the string
was passed by reference, the data sentinels will be inserted in the original
string (CWE-464), and further processing of the inputs will be altered,
possibly malformed..
C Example:
void processString (char *str) {
int i;
for(i=0; i<strlen(str); i++) {
if (isalnum(str[i])){
processChar(str[i]);
}
else if (str[i] = ':') {
movingToNewInput();}
}
}
}
Example 3:
The following Java example attempts to perform some processing based
on the boolean value of the input parameter. However, the expression to be
evaluated in the if statement uses the assignment operator "=" rather than
the comparison operator "==". As with the previous examples, the variable
will be reassigned locally and the expression in the if statement will
evaluate to true and unintended processing may occur.
Java Example:
public void checkValid(boolean isValid) {
if (isValid = true) {
System.out.println("Performing processing");
doSomethingImportant();
}
else {
System.out.println("Not Valid, do not perform
processing");
return;
}
}
While most Java compilers will catch the use of an assignment operator
when a comparison operator is required, for boolean variables in Java
the use of the assignment operator within an expression is allowed. If
possible, try to avoid using comparison operators on boolean variables
in java. Instead, let the values of the variables stand for themselves,
as in the following code.
Java Example:
public void checkValid(boolean isValid) {
if (isValid) {
System.out.println("Performing processing");
doSomethingImportant();
}
else {
System.out.println("Not Valid, do not perform
processing");
return;
}
}
Alternatively, to test for false, just use the boolean NOT
operator.
Java Example:
public void checkValid(boolean isValid) {
if (!isValid) {
System.out.println("Not Valid, do not perform
processing");
return;
}
System.out.println("Performing processing");
doSomethingImportant();
}
Example 4:
C Example:
void called(int foo){
if (foo=1) printf("foo\n");
}
int main() {
called(2);
return 0;
}
Potential Mitigations
Pre-design: Through Build: Many IDEs and static analysis products will
detect this problem.
Implementation
Place constants on the left. If one attempts to assign a constant with
a variable, the compiler will of course produce an error.
Other Notes
This bug is generally as a result of a typo and usually should cause
obvious problems with program execution. If the comparison is in an if
statement, the if statement will always return the value of the right-hand
side variable.
The software sets a pointer to a specific address other than
NULL or 0.
Extended Description
If the pointer is set to a specific address, that address will probably
not be valid in all environments or platforms.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C
C++
C#
Assembly
Demonstrative Examples
C Example:
int (*pt2Function) (float, char, char)=0x08040000;
int result2 = (*pt2Function) (12, 'a', 'b');
// Here we can inject code to execute.
Potential Mitigations
Implementation
Never set a pointer to a fixed address.
Other Notes
Consequence: Integrity: If one executes code at a known location, one
might be able to inject code there beforehand.
Consequence: Confidentiality: The data at a known pointer location can be
easily read.
Most often, this issue will only result in a crash, but in circumstances
where a user can influence the data at which the pointer points to, it may
result in code execution. At best, using fixed addresses is not
portable.
Weakness Ordinalities
Primary(where the weakness
exists independent of other weaknesses)
Software that fails to appropriately monitor or control
resource consumption can lead to adverse system
performance.
Extended Description
This situation is amplified if the software allows malicious users or
attackers to consume more resources than their access level permits.
Exploiting such a weakness can lead to asymmetric resource consumption,
aiding in amplification attacks against the system or the network.
Time of Introduction
Operation
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Potential Mitigations
An application must make resources available to a client commensurate
with the client's access level.
An application must, at all times, keep track of allocated resources
and meter their usage appropriately.
Other Notes
There are probably several sub-types besides these.
Sometimes this is a factor in "flood" attacks, but other types of
amplification exist.
The software performs authentication based on the name of a
resource being accessed, or the name of the actor performing the access, but it
does not properly check all possible names for that resource or
actor.
Bypass of authentication for files using "\"
(backslash) or "%5C" (encoded backslash).
Potential Mitigations
Architecture and Design
Avoid making decisions based on names of resources (e.g. files) if
those resources can have alternate names.
Implementation
Assume all input is malicious. Use a standard input validation
mechanism to validate all input for length, type, syntax, and business
rules before accepting the data to be diplayed or stored. Use an "accept
known good" validation strategy. Input (specifically, unexpected CRLFs)
that is not appropriate should not be processed into HTTP
headers.
Architecture and Design
Use and specify a strong output encoding (such as ISO 8859-1 or UTF
8).
Do not rely exclusively on blacklist validation to detect malicious
input or to encode output. There are too many variants to encode a
character, so you're likely to miss some variants.
Inputs should be decoded and canonicalized to the application's
current internal representation before being validated. Make sure that
your application does not decode the same input twice. Such errors could
be used to bypass whitelist schemes by introducing dangerous inputs
after they have been checked.
Other Notes
"Alternate name" itself is a rather general class of data-driven
manipulation.
The authentication scheme or implementation uses key data
elements that are assumed to be immutable, but can be controlled or modified by
the attacker.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Demonstrative Examples
In the following example, an "authenticated" cookie is used to
determine whether or not a user should be granted access to a system. Of
course, modifying the value of a cookie on the client-side is trivial, but
many developers assume that cookies are essentially immutable.
Java Example:
boolean authenticated = new
Boolean(getCookieValue("authenticated")).booleanValue();
A capture-replay flaw exists when the design of the software
makes it possible for a malicious user to sniff network traffic and bypass
authentication by replaying it to the server in question to the same effect as
the original message (or with minor changes).
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Common Consequences
Authorization
Messages sent with a capture-relay attack allow access to resources
which are not otherwise accessible without proper authentication.
Likelihood of Exploit
High
Demonstrative Examples
C/C++ Example:
unsigned char *simple_digest(char *alg,char *buf,unsigned int len,
int *olen) {
const EVP_MD *m; EVP_MD_CTX ctx;
unsigned char *ret;
OpenSSL_add_all_digests();
if (!(m = EVP_get_digestbyname(alg))) return NULL;
if (!(ret = (unsigned char*)malloc(EVP_MAX_MD_SIZE))) return
NULL;
Utilize some sequence or time stamping functionality along with a
checksum which takes this into account in order to ensure that messages
can be parsed only once.
Other Notes
Capture-replay attacks are common and can be difficult to defeat without
cryptography. They are a subset of network injection attacks that rely
listening in on previously sent valid commands, then changing them slightly
if necessary and resending the same commands to the server. Since any
attacker who can listen to traffic can see sequence numbers, it is necessary
to sign messages with some kind of cryptography to ensure that sequence
numbers are not simply doctored along with content.
The authentication algorithm is sound, but the implemented
mechanism can be bypassed as the result of a separate weakness that is primary
to the authentication error.
The password is not properly checked, which allows
remote attackers to bypass access controls by sending a 1-byte password that
matches the first character of the real password.
This attack-focused weakness is caused by improperly
implemented authentication schemes that are subject to spoofing
attacks.
Time of Introduction
Architecture and Design
Implementation
Demonstrative Examples
Here, an authentication mechanism implemented in Java relies on an
IP address for source validation. If an attacker is able to spoof the IP,
however, he may be able to bypass such an authentication
mechanism.
Java Example:
String sourceIP = request.getRemoteAddr();
if (sourceIP != null &&
sourceIP.equals(APPROVED_IP)) {
Authentication Bypass Using an Alternate Path or Channel
Status: Incomplete
Weakness ID: 288 (Weakness Base)
Description
Summary
A product requires authentication, but the product has an
alternate path or channel that does not require authentication.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Modes of Introduction
This is often seen in web applications that assume that access to a
particular CGI program can only be obtained through a "front" screen, when
the supporting programs are directly accessible. But this problem is not
just in web apps.
Funnel all access through a single choke point to simplify how users
can access a resource. For every access, perform a check to determine if
the user has permissions to access the resource.
Authentication Bypass: OpenSSL CTX Object Modified after SSL Objects are Created
Status: Draft
Weakness ID: 593 (Weakness Variant)
Description
Summary
The software modifies the SSL context after connection creation
has begun.
Time of Introduction
Architecture and Design
Implementation
Common Consequences
Authentication
No authentication takes place in this process, bypassing an assumed
protection of encryption.
Confidentiality
The encrypted communication between a user and a trusted host may be
subject to a "man in the middle" sniffing attack.
Demonstrative Examples
C Example:
#define CERT "secret.pem"
#define CERT2 "secret2.pem"
int main(){
SSL_CTX *ctx;
SSL *ssl;
init_OpenSSL();
seed_prng();
ctx = SSL_CTX_new(SSLv23_method());
if (SSL_CTX_use_certificate_chain_file(ctx, CERT) != 1)
int_error("Error loading certificate from file");
if (SSL_CTX_use_PrivateKey_file(ctx, CERT, SSL_FILETYPE_PEM)
!= 1)
int_error("Error loading private key from file");
if (!(ssl = SSL_new(ctx)))
int_error("Error creating an SSL context");
if ( SSL_CTX_set_default_passwd_cb(ctx, "new default password"
!= 1))
int_error("Doing something which is dangerous to do
anyways");
if (!(ssl2 = SSL_new(ctx)))
int_error("Error creating an SSL context");
}
Potential Mitigations
Architecture and Design
Use a language which provides a cryptography framework at a higher
level of abstraction.
Implementation
Most SSL_CTX functions have SSL counterparts that act on SSL-type
objects.
Other Notes
Applications should set up an SSL_CTX completely, before creating SSL
objects from it. If one did modify the SSL_CTX object after creating objects
from it, there is the possibility that older SSL objects created from that
context could all be affected by that change.
Linux kernel 2.2 and above allow promiscuous mode
using a different method than previous versions, and ifconfig is not aware
of the new method (alternate path property).
chain: Code was ported from a case-sensitive Unix
platform to a case-insensitive Windows platform where filetype handlers
treat .jsp and .JSP as different extensions. JSP source code may be read
because .JSP defaults to the filetype "text".
A behavioral discrepancy information leak occurs when the
product's actions indicate important differences based on (1) the internal state
of the product or (2) differences from other products in the same
class.
Extended Description
For example, attacks such as OS fingerprinting rely heavily on both
behavioral and response discrepancies.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Potential Mitigations
Compartmentalize your 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.
The software allows a condition where buffers are written to
using buffer access mechanisms such as indexes or pointers that reference memory
locations prior to the targeted buffer.
Extended Description
This typically occurs when indexes are negative numbers or when pointer
arithmetic results in a position before the beginning of the valid memory
location. This can occur when a negative number is used as an offset, or if
the pointer or its index is decremented to a position before the
buffer.
Alternate Terms
buffer underrun
Some prominent vendors and researchers use the term "buffer underrun".
"Buffer underflow" is more commonly used, although both terms are also
sometimes used to describe a buffer under-read (CWE-127).
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C
C++
Common Consequences
Availability
Out of bounds memory access will very likely result in the corruption
of relevant memory, and perhaps instructions, possibly leading to a
crash.
Access Control
If the corrupted memory can be effectively controlled, it may be
possible to execute arbitrary code. If the corrupted memory is data
rather than instructions, the system will continue to function with
improper changes, possibly in violation of an implicit or explicit
policy. The consequences would only be limited by how the affected data
is used, such as an adjacent memory location that is used to specify
whether the user has special privileges.
Other
When the consequence is arbitrary code execution, this can often be
used to subvert any other security service.
Likelihood of Exploit
Medium
Demonstrative Examples
The following is an example of code that may result in a buffer
underwrite, if find() returns a negative value to indicate that ch is not
found in srcBuf:
Buffer underflow from an all-whitespace string,
which causes a counter to be decremented before the buffer while looking for
a non-whitespace character.
This could be resultant from several errors, including a bad offset or an
array index that decrements before the beginning of the buffer (see
CWE-129).
Research Gaps
Much attention has been paid to buffer overflows, but "underflows"
sometimes exist in products that are relatively free of overflows, so it is
likely that this variant has been under-studied.
Causal Nature
Explicit(an explicit
weakness resulting from behavior of the
developer)
Taxonomy Mappings
Mapped Taxonomy Name
Mapped Node Name
PLOVER
UNDER - Boundary beginning violation ('buffer
underflow'?)
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Status: Incomplete
Compound Element ID: 120 (Compound Element Base: Composite)
Description
Summary
The program copies an input buffer to an output buffer without
verifying that the size of the input buffer is less than the size of the output
buffer, leading to a buffer overflow.
Extended Description
A buffer overflow condition exists when a program attempts to put more
data in a buffer than it can hold, or when a program attempts to put data in
a memory area outside of the boundaries of a buffer. The simplest type of
error, and the most common cause of buffer overflows, is the "classic" case
in which the program copies the buffer without checking its length at all.
Other variants exist, but the existence of a classic overflow strongly
suggests that the programmer is not considering even the most basic of
security protections.
Alternate Terms
buffer overrun
Some prominent vendors and researchers use the term "buffer overrun,"
but most people use "buffer overflow."
Unbounded Transfer
Terminology Notes
Many issues that are now called "buffer overflows" are substantively
different than the "classic" overflow, including entirely different bug
types that rely on overflow exploit techniques, such as integer signedness
errors, integer overflows, and format string bugs. This imprecise
terminology can make it difficult to determine which variant is being
reported.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C
C++
Common Consequences
Availability
Buffer overflows generally lead to crashes. Other attacks leading to
lack of availability are possible, including putting the program into an
infinite loop.
Integrity
Access control (instruction processing): Buffer overflows often can be
used to execute arbitrary code, which is usually outside the scope of a
program's implicit security policy.
Integrity
When the consequence is arbitrary code execution, this can often be
used to subvert any other security service.
By replacing a valid cookie value with an
extremely long string of characters, an attacker may overflow the
application's buffers.
Potential Mitigations
Architecture and Design
Use an abstraction library to abstract away risky APIs. Examples
include the Safe C String Library (SafeStr) by Viega, and the Strsafe.h
library from Microsoft. This is not a complete solution, since many
buffer overflows are not related to strings.
Architecture and Design
Use the <strsafe.h> library. This library has buffer
overflow safe functions that will help with the detection of buffer
overflows.
Build and Compilation
Use automatic buffer overflow detection mechanisms that are offered by
certain compilers or compiler extensions. Examples include StackGuard,
ProPolice and the Microsoft Visual Studio /GS flag. This is not
necessarily a complete solution, since these canary-based 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.
Implementation
Programmers should adhere to the following rules when allocating and
managing their applications memory: Double check that your buffer is as
large as you specify. 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 calling this function in a loop and
make sure you are not in danger of writing past the allocated space.
Truncate all input strings to a reasonable length before passing them to
the copy and concatenation functions
Operation
Use a feature like Address Space Layout Randomization (ASLR). This is
not a complete solution. However, it forces the attacker to guess an
unknown value that changes every program execution.
Operation
Use a CPU and operating system that offers Data Execution Protection
(NX) or its equivalent. 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.
Other Notes
Most mitigating technologies at the compiler or OS level to date address
only a subset of buffer overflow problems and rarely provide complete
protection against even that subset. It is more common to make the workload
of an attacker much higher -- for example, by leaving
Weakness Ordinalities
Resultant(where the weakness
is typically related to the presence of some other
weaknesses)
Primary(where the weakness
exists independent of other weaknesses)
At the code level, stack-based and heap-based overflows do not differ
significantly, so there usually is not a need to distinguish them. From the
attacker perspective, they can be quite different, since different
techniques are required to exploit them.
Affected Resources
Memory
Functional Areas
Memory Management
Causal Nature
Explicit(an explicit
weakness resulting from behavior of the
developer)
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
PLOVER
Unbounded Transfer ('classic overflow')
7 Pernicious Kingdoms
Buffer Overflow
CLASP
Buffer overflow
OWASP Top Ten 2004
A1
CWE More Specific
Unvalidated Input
OWASP Top Ten 2004
A5
CWE More Specific
Buffer Overflows
CERT C Secure Coding
STR35-C
Do not copy data from an unbounded source to a fixed-length
array
A weakness where the code path includes a Buffer Write Operation such
that:
1. the expected size of the buffer is greater than the actual size of
the buffer where expected size is equal to the sum of the size of the
data item and the position in the buffer
Where Buffer Write Operation is a statement that writes a data item of a
certain size into a buffer at a certain position and at a certain
index
The software uses an API function that does not exist on all
versions of the target platform. This could cause portability problems or
inconsistencies that allow denial of service or other
consequences.
Extended Description
Some functions that offer security features supported by the OS are not
available on all versions of the OS in common use. Likewise, functions are
often deprecated or made obsolete for security reasons and should not be
used.
Time of Introduction
Architecture and Design
Implementation
Potential Mitigations
Implementation
Always test your code on any platform on which it is targeted to run
on.
Pre-design through build: Test your code on the newest and oldest
platform on which it is targeted to run on.
Other Notes
Consequence: Pre-design through build: It is important to develop a system
to test for this set of functions.
The program calls a thread's run() method instead of calling
start(), which causes the code to run in the thread of the caller instead of the
callee.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
Demonstrative Examples
The following excerpt from a Java program mistakenly calls run()
instead of start().
Java Example:
Thread thr = new Thread() {
public void run() {
...
}
};
thr.run();
Potential Mitigations
Use the start() method instead of the run() method.
Other Notes
In most cases a direct call to a Thread object's run() method is a bug.
The programmer intended to begin a new thread of control, but accidentally
called run() instead of start(), so the run() method will execute in the
caller's thread of control.
CERT C Secure Coding Section 01 - Preprocessor (PRE)
Status: Incomplete
Category ID: 735 (Category)
Description
Summary
Weaknesses in this category are related to rules in the
preprocessor section of the CERT C Secure Coding Standard. Since not all rules
map to specific weaknesses, this category may be incomplete.
CERT C Secure Coding Section 02 - Declarations and Initialization (DCL)
Status: Incomplete
Category ID: 736 (Category)
Description
Summary
Weaknesses in this category are related to rules in the
declarations and initialization section of the CERT C Secure Coding Standard.
Since not all rules map to specific weaknesses, this category may be incomplete.
CERT C Secure Coding Section 03 - Expressions (EXP)
Status: Incomplete
Category ID: 737 (Category)
Description
Summary
Weaknesses in this category are related to rules in the
expressions section of the CERT C Secure Coding Standard. Since not all rules
map to specific weaknesses, this category may be incomplete.
Weaknesses in this category are related to rules in the
integers section of the CERT C Secure Coding Standard. Since not all rules map
to specific weaknesses, this category may be incomplete.