The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize 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
Common Consequences
Scope
Effect
Confidentiality
Integrity
Technical Impact: Read files or
directories; Modify files or
directories
Demonstrative Examples
Example 1
In the example below, the path to a dictionary file is read from a
system property and used to initialize a File object.
However, the path is not validated or modified to prevent it from
containing absolute path sequences before creating the File object. This
allows anyone who can control the system property to determine what file
is used. Ideally, the path should be resolved relative to some kind of
application or user home directory.
Acceptance of Extraneous Untrusted Data With Trusted Data
Definition in a New Window
Weakness ID: 349 (Weakness Base)
Status: Draft
Description
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.
Access to Critical Private Variable via Public Method
Definition in a New Window
Weakness ID: 767 (Weakness Variant)
Status: Incomplete
Description
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
Common Consequences
Scope
Effect
Integrity
Other
Technical Impact: Modify application
data; Other
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.
(Bad Code)
Example
Language: C++
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).
(Bad Code)
Example
Language: Java
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
Phase: 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.
The accidental addition of a data-structure sentinel can cause serious programming logic problems.
Extended Description
Data-structure sentinels are often used to mark the structure of data. A common example of this is the null character at the end of strings or a special sentinel to mark the end of a linked list. It is dangerous to allow this type of control data to be easily accessible. Therefore, it is important to protect from the addition or modification of sentinels.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C
C++
Common Consequences
Scope
Effect
Integrity
Technical Impact: Modify application
data
Generally this error will cause the data structure to not work
properly by truncating the data.
Likelihood of Exploit
High to Very High
Demonstrative Examples
Example 1
The following example assigns some character values to a list of
characters and prints them each individually, and then as a string. The
third character value is intended to be an integer taken from user input and
converted to an int.
The first print statement will print each character separated by a
space. However, if a non-integer is read from stdin by getc, then atoi
will not make a conversion and return 0. When foo is printed as a
string, the 0 at character foo[2] will act as a NULL terminator and
foo[3] will never be printed.
Potential Mitigations
Phases: Implementation; Architecture and Design
Encapsulate the user from interacting with data sentinels. Validate
user input to verify that sentinels are not present.
Phase: Implementation
Proper error checking can reduce the risk of inadvertently introducing
sentinel values into data. For example, if a parsing function fails or
encounters an error, it might return a value that is the same as the
sentinel.
Phase: Requirements
Use a language or compiler that performs automatic bounds
checking.
Phase: Architecture and Design
Use an abstraction library to abstract away risky APIs. This is not a
complete solution.
Phase: Build and Compilation
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.
Phase: Operation
Use OS-level preventative functionality. This is not a complete
solution.
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.
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
Definition in a New Window
Weakness ID: 774 (Weakness Variant)
Status: Incomplete
Description
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.
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
Phase: 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.
Phase: 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
Definition in a New Window
Weakness ID: 770 (Weakness Base)
Status: Incomplete
Description
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.
When allocating resources without limits, an attacker could prevent
other systems, applications, or processes from accessing the same type
of resource.
Likelihood of Exploit
Medium to High
Detection Methods
Manual Static Analysis
Manual static analysis can be useful for finding this weakness, but it
might not achieve desired code coverage within limited time constraints.
If denial-of-service is not considered a significant risk, or if there
is strong emphasis on consequences such as code execution, then manual
analysis may not focus on this weakness at all.
Fuzzing
While fuzzing is typically geared toward finding low-level
implementation bugs, it can inadvertently find uncontrolled resource
allocation problems. This can occur when the fuzzer generates a large
number of test cases but does not restart the targeted software in
between test cases. If an individual test case produces a crash, but it
does not do so reliably, then an inability to limit resource allocation
may be the cause.
When the allocation is directly affected by numeric inputs, then
fuzzing may produce indications of this weakness.
Effectiveness: Opportunistic
Automated Dynamic Analysis
Certain automated dynamic analysis techniques may be effective in
producing side effects of uncontrolled resource allocation problems,
especially with resources such as processes, memory, and connections.
The technique may involve generating a large number of requests to the
software within a short time frame. Manual analysis is likely required
to interpret the results.
Automated Static Analysis
Specialized configuration or tuning may be required to train automated
tools to recognize this weakness.
Automated static analysis typically has limited utility in recognizing
unlimited allocation problems, except for the missing release of
program-independent system resources such as files, sockets, and
processes, or unchecked arguments to memory. For system resources,
automated static analysis may be able to detect circumstances in which
resources are not released after they have expired, or if too much of a
resource is requested at once, as can occur with memory. Automated
analysis of configuration files may be able to detect settings that do
not specify a maximum value.
Automated static analysis tools will not be appropriate for detecting
exhaustion of custom resources, such as an intended security policy in
which a bulletin board user is only allowed to make a limited number of
posts per day.
Demonstrative Examples
Example 1
This code allocates a socket and forks each time it receives a new
connection.
(Bad Code)
Example Languages: C and C++
sock=socket(AF_INET, SOCK_STREAM, 0);
while (1) {
newsock=accept(sock, ...);
printf("A connection has been accepted\n");
pid = fork();
}
The program does not track how many connections have been made, and it
does not limit the number of connections. Because forking is a
relatively expensive operation, an attacker would be able to cause the
system to run out of CPU, processes, or memory by making a large number
of connections. Alternatively, an attacker could consume all available
connections, preventing others from accessing the system
remotely.
Example 2
In the following example a server socket connection is used to
accept a request to store data on the local file system using a specified
filename. The method openSocketConnection establishes a server socket to
accept requests from a client. When a client establishes a connection to
this service the getNextMessage method is first used to retrieve from the
socket the name of the file to store the data, the openFileToWrite method
will validate the filename and open a file to write to on the local file
system. The getNextMessage is then used within a while loop to continuously
read data from the socket and output the data to the file until there is no
longer any data from the socket.
(Bad Code)
Example Languages: C and C++
int writeDataFromSocketToFile(char *host, int port)
{
char filename[FILENAME_SIZE];
char buffer[BUFFER_SIZE];
int socket = openSocketConnection(host, port);
if (socket < 0) {
printf("Unable to open socket connection");
return(FAIL);
}
if (getNextMessage(socket, filename, FILENAME_SIZE) > 0)
{
if (openFileToWrite(filename) > 0) {
while (getNextMessage(socket, buffer, BUFFER_SIZE)
> 0){
if (!(writeToFile(buffer) > 0))
break;
}
}
closeFile();
}
closeSocket(socket);
}
This example creates a situation where data can be dumped to a file on
the local file system without any limits on the size of the file. This
could potentially exhaust file or disk resources and/or limit other
clients' ability to access the service.
Example 3
In the following example, the processMessage method receives a two
dimensional character array containing the message to be processed. The
two-dimensional character array contains the length of the message in the
first character array and the message body in the second character array.
The getMessageLength method retrieves the integer value of the length from
the first character array. After validating that the message length is
greater than zero, the body character array pointer points to the start of
the second character array of the two-dimensional character array and memory
is allocated for the new body character array.
(Bad Code)
Example Languages: C and C++
/* process message accepts a two-dimensional character array of
the form [length][body] containing the message to be processed
*/
int processMessage(char **message)
{
char *body;
int length = getMessageLength(message[0]);
if (length > 0) {
body = &message[1][0];
processMessageBody(body);
return(SUCCESS);
}
else {
printf("Unable to process message; invalid message
length");
return(FAIL);
}
}
This example creates a situation where the length of the body
character array can be very large and will consume excessive memory,
exhausting system resources. This can be avoided by restricting the
length of the second character array with a maximum length check
Also, consider changing the type from 'int' to 'unsigned int', so that you are always guaranteed that the number is positive. This might not be possible if the protocol specifically requires allowing negative values, or if you cannot control the return value from getMessageLength(), but it could simplify the check to ensure the input is positive, and eliminate other errors such as signed-to-unsigned conversion errors (CWE-195) that may occur elsewhere in the code.
(Good Code)
Example Languages: C and C++
unsigned int length = getMessageLength(message[0]);
if ((length > 0) && (length < MAX_LENGTH))
{...}
Example 4
In the following example, a server object creates a server socket
and accepts client connections to the socket. For every client connection to
the socket a separate thread object is generated using the
ClientSocketThread class that handles request made by the client through the
socket.
(Bad Code)
Example
Language: Java
public void acceptConnections() {
try {
ServerSocket serverSocket = new
ServerSocket(SERVER_PORT);
int counter = 0;
boolean hasConnections = true;
while (hasConnections) {
Socket client = serverSocket.accept();
Thread t = new Thread(new
ClientSocketThread(client));
In this example there is no limit to the number of client connections
and client threads that are created. Allowing an unlimited number of
client connections and threads could potentially overwhelm the system
and system resources.
The server should limit the number of client connections and the
client threads that are created. This can be easily done by creating a
thread pool object that limits the number of threads that are
generated.
(Good Code)
Example
Language: Java
public static final int SERVER_PORT = 4444;
public static final int MAX_CONNECTIONS = 10;
...
public void acceptConnections() {
try {
ServerSocket serverSocket = new
ServerSocket(SERVER_PORT);
int counter = 0;
boolean hasConnections = true;
while (hasConnections) {
hasConnections = checkForMoreConnections();
Socket client = serverSocket.accept();
Thread t = new Thread(new
ClientSocketThread(client));
ExecutorService pool =
Executors.newFixedThreadPool(MAX_CONNECTIONS);
pool.execute(t);
}
serverSocket.close();
} catch (IOException ex) {...}
}
Example 5
An unnamed web site allowed a user to purchase tickets for an event.
A menu option allowed the user to purchase up to 10 tickets, but the back
end did not restrict the actual number of tickets that could be
purchased.
CMS does not restrict the number of searches that
can occur simultaneously, leading to resource
exhaustion.
Potential Mitigations
Phase: Requirements
Clearly specify the minimum and maximum expectations for capabilities,
and dictate which behaviors are acceptable when resource allocation
reaches limits.
Phase: 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.
Phase: Architecture and Design
Design throttling mechanisms into the system architecture. The best
protection is to limit the amount of resources that an unauthorized user
can cause to be expended. A strong authentication and access control
model will help prevent such attacks from occurring in the first place,
and it will help the administrator to identify who is committing the
abuse. The login application should be protected against DoS attacks as
much as possible. Limiting the database access, perhaps by caching
result sets, can help minimize the resources expended. To further limit
the potential for a DoS attack, consider tracking the rate of requests
received from users and blocking requests that exceed a defined rate
threshold.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input
validation strategy, i.e., use a whitelist 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. Do not rely exclusively on looking for malicious or malformed
inputs (i.e., do not rely on a blacklist). However, blacklists can be
useful for detecting potential attacks or determining which inputs are
so malformed that they should be rejected outright.
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 you are
expecting colors such as "red" or "blue."
This will only be applicable to cases where user input can influence
the size or frequency of resource allocations.
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: Architecture and Design
Mitigation of resource exhaustion attacks requires that the target
system either:
recognizes the attack and denies that user further access for a
given amount of time, typically by using increasing time
delays
uniformly throttles all requests in order to make it more
difficult to consume resources more quickly than they can again be
freed.
The first of these solutions is an issue in itself though, since it
may allow attackers to prevent the use of the system by a particular
valid user. If the attacker impersonates the valid user, he may be able
to prevent the user from accessing the server in question.
The second solution can be difficult to effectively institute -- and
even when properly done, it does not provide a full solution. It simply
requires more resources on the part of the attacker.
Phase: Architecture and Design
Ensure that protocols have specific limits of scale placed on
them.
Phases: Architecture and Design; Implementation
If the program must fail, ensure that it fails gracefully (fails
closed). There may be a temptation to simply let the program fail poorly
in cases such as low memory conditions, but an attacker may be able to
assert control before the software has fully exited. Alternately, an
uncontrolled failure could cause cascading problems with other
downstream components; for example, the program could send a signal to a
downstream process so the process immediately knows that a problem has
occurred and has a better chance of recovery.
Ensure that all failures in resource allocation place the system into
a safe posture.
Phase: Implementation
For system resources when using C, 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.
Phase: 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.
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
CERT Java Secure Coding
FIO06-J
Close resources when they are no longer
needed
CERT Java Secure Coding
SER12-J
Avoid memory and resource leaks during
serialization
CERT Java Secure Coding
MSC11-J
Do not assume infinite heap space
CERT C++ Secure Coding
MEM12-CPP
Do not assume infinite heap space
CERT C++ Secure Coding
FIO42-CPP
Ensure files are properly closed when they are no longer
needed
Joao Antunes, Nuno Ferreira Neves
and Paulo Verissimo. "Detection and Prediction of Resource-Exhaustion
Vulnerabilities". Proceedings of the IEEE International Symposium on
Software Reliability Engineering (ISSRE). November 2008. <http://homepages.di.fc.ul.pt/~nuno/PAPERS/ISSRE08.pdf>.
[REF-11] M. Howard and
D. LeBlanc. "Writing Secure Code". Chapter 17, "Protecting Against Denial of Service Attacks"
Page 517. 2nd Edition. Microsoft. 2002.
"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 incorrectbehavior 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
Modes of Introduction
This issue typically appears in rarely-tested code, since the
"always-incorrect" nature will be detected as a bug during normal
usage.
Do not place a semicolon on the same line as an if, for, or
while statement
Maintenance Notes
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.
Time of Introduction
Architecture and Design
Implementation
Operation
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Confidentiality
Integrity
Technical Impact: Read files or
directories; Modify files or
directories
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.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Confidentiality
Integrity
Availability
Other
Technical Impact: Execute unauthorized code or
commands; Alter execution
logic; Read application
data; Modify application
data
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.
Language interpreter's mail function accepts another argument that is concatenated to a string used in a dangerous popen() call. Since there is no neutralization of this argument, both OS Command Injection (CWE-78) and Argument Injection (CWE-88) are possible.
Potential Mitigations
Phase: Architecture and Design
Strategy: Input Validation
Understand all the potential areas where untrusted inputs can enter
your software: parameters or arguments, cookies, anything read from the
network, environment variables, request headers as well as content, URL
components, e-mail, files, databases, and any external systems that
provide data to the application. Perform input validation at
well-defined interfaces.
Phase: Architecture and Design
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input
validation strategy (i.e., use a whitelist). Reject any input that does
not strictly conform to specifications, or transform it into something
that does. Use a blacklist to reject any unexpected inputs and detect
potential attacks.
Phase: Architecture and Design
Do not rely exclusively on blacklist validation to detect malicious input or to encode output (CWE-184). There are too many ways to encode the same character, so you're likely to miss some variants.
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 whitelist 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.
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: Testing
Use automated static analysis tools that target this type of weakness.
Many modern techniques use data flow analysis to minimize the number of
false positives. This is not a perfect solution, since 100% accuracy and
coverage are not feasible.
Phase: Testing
Use dynamic tools and techniques that interact with the software using
large test suites with many diverse inputs, such as fuzz testing
(fuzzing), robustness testing, and fault injection. The software's
operation may slow down, but it should not become unstable, crash, or
generate incorrect results.
Weakness Ordinalities
Ordinality
Description
Primary
(where
the weakness exists independent of other weaknesses)
At one layer of abstraction, this can overlap other weaknesses that have
whitespace problems, e.g. injection of javascript into attributes of HTML
tags.
Affected Resources
System Process
Causal Nature
Explicit
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
PLOVER
Argument Injection or Modification
CERT C Secure Coding
ENV03-C
Sanitize the environment when invoking external
programs
CERT C Secure Coding
ENV04-C
Do not call system() if you do not need a command
processor
CERT C Secure Coding
STR02-C
Sanitize data passed to complex subsystems
WASC
30
Mail Command Injection
CERT C++ Secure Coding
STR02-CPP
Sanitize data passed to complex subsystems
CERT C++ Secure Coding
ENV03-CPP
Sanitize the environment when invoking external
programs
CERT C++ Secure Coding
ENV04-CPP
Do not call system() if you do not need a command
processor
ASP.NET Misconfiguration: Not Using Input Validation Framework
Definition in a New Window
Weakness ID: 554 (Weakness Variant)
Status: Draft
Description
Description Summary
The ASP.NET application does not use an input validation framework.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
.NET
Common Consequences
Scope
Effect
Integrity
Technical Impact: Unexpected state
Unchecked input leads to cross-site scripting, process control, and
SQL injection vulnerabilities, among others.
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
ASP.NET Misconfiguration: Password in Configuration File
Definition in a New Window
Weakness ID: 13 (Weakness Variant)
Status: Draft
Description
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
Common Consequences
Scope
Effect
Access Control
Technical Impact: Gain privileges / assume
identity
Demonstrative Examples
Example 1
The following connectionString has clear text
credentials.
Software that does not 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.
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
Phase: Architecture and Design
Avoid making decisions based on names of resources (e.g. files) if
those resources can have alternate names.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input
validation strategy, i.e., use a whitelist 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
(i.e., do not rely on a blacklist). A blacklist 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, blacklists can be useful for detecting potential
attacks or determining which inputs are so malformed that they should be
rejected outright.
Phase: Architecture and Design
Use and specify a strong output encoding (such as ISO 8859-1 or UTF
8).
Phase: Implementation
Strategy: Input Validation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass whitelist validation schemes by introducing dangerous inputs after they have been checked.
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
Common Consequences
Scope
Effect
Access Control
Technical Impact: Bypass protection
mechanism
Demonstrative Examples
Example 1
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.
(Bad Code)
Example
Language: Java
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).
Extended Description
Capture-replay attacks are common and can be difficult to defeat without cryptography. They are a subset of network injection attacks that rely on observing previously-sent valid commands, then changing them slightly if necessary and resending the same commands to the server.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Access Control
Technical Impact: Gain privileges / assume
identity
Messages sent with a capture-relay attack allow access to resources
which are not otherwise accessible without proper authentication.
product authentication succeeds if user-provided
MD5 hash matches the hash in its database; this can be subjected to replay
attacks.
Potential Mitigations
Phase: Architecture and Design
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.
Phase: Architecture and Design
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
Common Consequences
Scope
Effect
Access Control
Technical Impact: Bypass protection
mechanism; Gain privileges / assume
identity
Demonstrative Examples
Example 1
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.
(Bad Code)
Example
Language: Java
String sourceIP = request.getRemoteAddr();
if (sourceIP != null && sourceIP.equals(APPROVED_IP))
{
Authentication Bypass Using an Alternate Path or Channel
Definition in a New Window
Weakness ID: 288 (Weakness Base)
Status: Incomplete
Description
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.
User can avoid lockouts by using an API instead of
the GUI to conduct brute force password
guessing.
Potential Mitigations
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
Definition in a New Window
Weakness ID: 593 (Weakness Variant)
Status: Draft
Description
Description Summary
The software modifies the SSL context after connection creation has begun.
Extended Description
If the program modifies the SSL_CTX object after creating SSL objects from it, there is the possibility that older SSL objects created from the original context could all be affected by that change.
Time of Introduction
Architecture and Design
Implementation
Common Consequences
Scope
Effect
Access Control
Technical Impact: Bypass protection
mechanism
No authentication takes place in this process, bypassing an assumed
protection of encryption.
Confidentiality
Technical Impact: Read application
data
The encrypted communication between a user and a trusted host may be
subject to a "man in the middle" sniffing attack.
Demonstrative Examples
Example 1
(Bad Code)
Example
Language: C
#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
Phase: Architecture and Design
Use a language which provides a cryptography framework at a higher
level of abstraction.
Phase: Implementation
Most SSL_CTX functions have SSL counterparts that act on SSL-type
objects.
Phase: Implementation
Applications should set up an SSL_CTX completely, before creating SSL
objects from it.
The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.
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 read/modify their data.
Alternate Terms
Horizontal Authorization:
"Horizontal Authorization" is used to describe situations in which two
users have the same privilege level, but must be prevented from
accessing each other's resources. This is fairly common when using
key-based access to resources in a multi-user context.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
Language-independent
Common Consequences
Scope
Effect
Access Control
Technical Impact: Bypass protection
mechanism
Access control checks for specific user data or functionality can be
bypassed.
Access Control
Technical Impact: Gain privileges / assume
identity
Horizontal escalation of privilege is possible (one user can
view/modify information of another user).
Access Control
Technical Impact: Gain privileges / assume
identity
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
Phase: Architecture and Design
For each and every data access, ensure that the user has sufficient
privilege to access the record that is being requested.
Phases: Architecture and Design; Implementation
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.
Phase: Architecture and Design
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.
Authorization Bypass Through User-Controlled SQL Primary Key
Definition in a New Window
Weakness ID: 566 (Weakness Variant)
Status: Incomplete
Description
Description Summary
The software uses a database table that includes records that should not be accessible to an actor, but it executes a SQL statement with a primary key that can be controlled by that actor.
Extended Description
When a user can set a primary key to any value, then the user can modify the key to point to unauthorized records.
Database access control errors occur when:
Data enters a program from an untrusted source.
The data is used to specify the value of a primary key in a SQL query.
The untrusted source does not have the permissions to be able to access all rows in the associated table.
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.
(Bad Code)
Example
Language: C#
...
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 not considered 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
Phase: 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. Use an "accept known good" validation
strategy.
Phase: Implementation
Use a parameterized query AND make sure that the accepted values
conform to the business rules. Construct your SQL statement
accordingly.
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".
The software writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.
Extended Description
This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used.
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).
Out of bounds memory access will very likely result in the corruption
of relevant memory, and perhaps instructions, possibly leading to a
crash.
Integrity
Confidentiality
Availability
Access Control
Other
Technical Impact: Execute unauthorized code or
commands; Modify memory; Bypass protection
mechanism; Other
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.
Access Control
Other
Technical Impact: Bypass protection
mechanism; 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
Example 1
In the following C/C++ example, a utility function is used to trim
trailing whitespace from a character string. The function copies the input
string to a local character string and uses a while statement to remove the
trailing whitespace by moving backward through the string and overwriting
whitespace with a NUL character.
(Bad Code)
Example Languages: C and C++
char* trimTrailingWhitespace(char *strMessage, int length)
{
char *retMessage;
char *message = malloc(sizeof(char)*(length+1));
// copy input string to a temporary string
char message[length+1];
int index;
for (index = 0; index < length; index++) {
message[index] = strMessage[index];
}
message[index] = '\0';
// trim trailing whitespace
int len = index-1;
while (isspace(message[len])) {
message[len] = '\0';
len--;
}
// return string without trailing whitespace
retMessage = message;
return retMessage;
}
However, this function can cause a buffer underwrite if the input
character string contains all whitespace. On some systems the while
statement will move backwards past the beginning of a character string
and will call the isspace() function on an address outside of the bounds
of the local buffer.
Example 2
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
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
PLOVER
UNDER - Boundary beginning violation ('buffer
underflow'?)
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
Common Consequences
Scope
Effect
Other
Technical Impact: Quality degradation
Potential Mitigations
Phase: 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.
Phase: Testing
Develop a system to test for API functions that are not portable.
Channel Accessible by Non-Endpoint ('Man-in-the-Middle')
Definition in a New Window
Weakness ID: 300 (Weakness Class)
Status: Draft
Description
Description Summary
The product does not adequately verify the identity of actors at both ends of a communication channel, or does not adequately ensure the integrity of the channel, in a way that allows the channel to be accessed or influenced by an actor that is not an endpoint.
Extended Description
In order to establish secure communication between two parties, it is often important to adequately verify the identity of entities at each end of the communication channel. Inadequate or inconsistent verification may result in insufficient or incorrect identification of either communicating entity. This can have negative consequences such as misplaced trust in the entity at the other end of the channel. An attacker can leverage this by interposing between the communicating entities and masquerading as the original entity. In the absence of sufficient verification of identity, such an attacker can eavesdrop and potentially modify the communication between the original entities.
In the Java snippet below, data is sent over an unencrypted channel
to a remote server. By eavesdropping on the communication channel or posing
as the endpoint, an attacker would be able to read all of the transmitted
data.
(Bad Code)
Example
Language: Java
Socket sock;
PrintWriter out;
try {
sock = new Socket(REMOTE_HOST, REMOTE_PORT);
out = new PrintWriter(echoSocket.getOutputStream(),
true);
// Write data to remote host via socket output
stream.
...
}
Potential Mitigations
Always fully authenticate both ends of any communications
channel.
Adhere to the principle of complete mediation.
A certificate binds an identity to a cryptographic key to authenticate
a communicating party. Often, the certificate takes the encrypted form
of the hash of the identity of the subject, the public key, and
information such as time of issue or expiration using the issuer's
private key. The certificate can be validated by deciphering the
certificate with the issuer's public key. See also X.509 certificate
signature chains and the PGP certification structure.
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere, when the information should be encrypted or otherwise protected.
Extended Description
Because the information is stored in cleartext, attackers could potentially read it.