CWE nodes in this view (graph) are associated with the OWASP Top Ten, as
released in 2004, and as required for compliance with PCI DSS version
1.1.
View Metrics
CWEs in this view
Total CWEs
Total
126
out of
791
Views
0
out of
22
Categories
16
out of
106
Weaknesses
107
out of
651
Compound_Elements
3
out of
12
View Audience
Stakeholder
Description
Developers
This view outlines the most important issues as identified by the
OWASP Top Ten (2004 version), providing a good starting point for web
application developers who want to code more securely, as well as
complying with PCI DSS 1.1.
Software Customers
This view outlines the most important issues as identified by the
OWASP Top Ten, providing customers with a way of asking their software
developers to follow minimum expectations for secure code, in compliance
with PCI-DSS 1.1.
Educators
Since the OWASP Top Ten covers the most frequently encountered issues,
this view can be used by educators as training material for students.
However, the 2007 version (CWE-629) might be more appropriate.
CWE relationships for this view were obtained by examining the OWASP
document and mapping to any items that were specifically mentioned within
the text of a category. As a result, this mapping is not complete with
respect to all of CWE. In addition, some concepts were mentioned in multiple
Top Ten items, which caused them to be mapped to multiple CWE categories.
For example, SQL injection is mentioned in both A1 (CWE-722) and A6
(CWE-727) categories.
Some parts of CWE are not fully fleshed out in terms of weaknesses. When
these areas were mentioned in the Top Ten, category nodes were mapped,
although general mapping practice would usually favor mapping only to
weaknesses.
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
interchangeably.
Time of Introduction
Architecture and Design
Implementation
Operation
Potential Mitigations
ID
Phase
Description
1
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
Scope
Effect
Access Control
Access control checks for specific user data or functionality can be
bypassed.
Access Control
Horizontal escalation of privilege is possible (one user can
view/modify information of another user)
Integrity
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
Description
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.
ASP.NET Misconfiguration: Use of Identity Impersonation
Definition in a New Window
Weakness ID: 556 (Weakness Variant)
Status: Incomplete
Description
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.
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
Common Consequences
Scope
Effect
Availability
Sometimes this is a factor in "flood" attacks, but other types of
amplification exist.
Potential Mitigations
Phase
Description
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.
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
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)
Java
boolean authenticated = new
Boolean(getCookieValue("authenticated")).booleanValue();
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Definition in a New Window
Compound Element ID: 120 (Compound Element Base: Composite)
Status: Incomplete
Description
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
Scope
Effect
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
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
Phase
Description
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.
Build and Compilation
Operation
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 good practice to
implement strategies to increase the workload of an attacker, such as
leaving the attacker to guess an unknown value that changes every
program execution.
Weakness Ordinalities
Ordinality
Description
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
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
Certificates should be carefully managed and checked to assure
that data are encrypted with the intended owner's public
key.
Applicable Platforms
Languages
All
Background Details
A certificate is a token that associates an identity (principle) to a
cryptographic key. Certificates can be used to check if a public key belongs
to the assumed owner.
The software is composed of a server that relies on the client
to implement a mechanism that is intended to protect the
server.
Extended Description
When the server relies on protection mechanisms placed on the client side,
an attacker can modify the client-side behavior to bypass the protection
mechanisms resulting in potentially unexpected interactions between the
client and server. The consequences will vary, depending on what the
mechanisms are trying to protect.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Architectural Paradigms
Client-Server: (Sometimes)
Common Consequences
Scope
Effect
Integrity
Client-side validation checks can be easily bypassed, allowing
malformed or unexpected input to pass into the application, potentially
as trusted data. This may lead to unexpected states, behaviors and
possibly a resulting crash.
Access Control
Client-side checks for authentication can be easily bypassed, allowing
clients to escalate their access levels and perform unintended
actions.
Likelihood of Exploit
Medium
Enabling Factors for Exploitation
Consider a product that consists of two or more processes or nodes that
must interact closely, such as a client/server model. If the product uses
protection schemes in the client in order to defend from attacks against the
server, and the server does not use the same schemes, then an attacker could
modify the client in a way that bypasses those schemes. This is a
fundamental design flaw that is primary to many weaknesses.
Demonstrative Examples
Example 1
This example contains client-side code that checks if the user
authenticated successfully before sending a command. The server-side code
performs the authentication in one step, and executes the command in a
separate step.
CLIENT-SIDE (client.pl)
(Good Code)
Perl
$server = "server.example.com";
$username = AskForUserName();
$password = AskForPassword();
$address = AskForAddress();
$sock = OpenSocket($server, 1234);
writeSocket($sock, "AUTH $username $password\n");
$resp = readSocket($sock);
if ($resp eq "success") {
# username/pass is valid, go ahead and update the info!
writeSocket($sock, "FAILURE -- address is
malformed\n");
}
}
The server accepts 2 commands, "AUTH" which authenticates the user,
and "CHANGE-ADDRESS" which updates the address field for the username.
The client performs the authentication and only sends a CHANGE-ADDRESS
for that user if the authentication succeeds. Because the client has
already performed the authentication, the server assumes that the
username in the CHANGE-ADDRESS is the same as the authenticated user. An
attacker could modify the client by removing the code that sends the
"AUTH" command and simply executing the CHANGE-ADDRESS.
client allows server to modify client's
configuration and overwrite arbitrary files.
Potential Mitigations
Phase
Description
Architecture and Design
For any security checks that are performed on the client side, ensure
that these checks are duplicated on the server side. Attackers can
bypass the client-side checks by modifying values after the checks have
been performed, or by changing the client to remove the client-side
checks entirely. Then, these modified values would be submitted to the
server.
Even though client-side checks provide minimal benefits with respect
to server-side security, they are still useful. First, they can support
intrusion detection. If the server receives input that should have been
rejected by the client, then it may be an indication of an attack.
Second, client-side error-checking can provide helpful feedback to the
user about the expectations for valid input. Third, there may be a
reduction in server-side processing time for accidental input errors,
although this is typically a small savings.
Architecture and Design
If some degree of trust is required between the two entities, then use
integrity checking and strong authentication to ensure that the inputs
are coming from a trusted source. Design the product so that this trust
is managed in a centralized fashion, especially if there are complex or
numerous communication channels, in order to reduce the risks that the
implementer will mistakenly omit a check in a single code path.
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.
Testing
Use tools and techniques that require manual (human) analysis, such as
penetration testing, threat modeling, and interactive tools that allow
the tester to record and modify an active session. These may be more
effective than strictly automated techniques. This is especially the
case with weaknesses that are related to design and business
rules.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)
Server-side enforcement of client-side security is conceptually likely to
occur, but some architectures might have these strong dependencies as part
of legitimate behavior, such as thin clients.
updated Relationships, Other Notes, Taxonomy Mappings,
Weakness Ordinalities
2009-01-12
CWE Content Team
MITRE
Internal
updated Demonstrative Examples, Description,
Likelihood of Exploit, Name, Observed Examples, Other Notes,
Potential Mitigations, Relationships, Research Gaps,
Time of Introduction
2009-03-10
CWE Content Team
MITRE
Internal
updated Potential Mitigations
2009-05-27
CWE Content Team
MITRE
Internal
updated Demonstrative Examples
2009-07-27
CWE Content Team
MITRE
Internal
updated Related Attack Patterns,
Relationships
2009-10-29
CWE Content Team
MITRE
Internal
updated Applicable Platforms, Common Consequences,
Description
chain: HTTP server protects against ".." but
allows "." variants such as "////./../.../". If the server removes "/.."
sequences, the result would collapse into an unsafe value "////../"
(CWE-182).
MFV. Regular expression intended to protect
against directory traversal reduces ".../...//" to
"../".
Potential Mitigations
Phase
Description
Avoid making decisions based on names of resources (e.g. files) if
those resources can have alternate names.
Architecture and Design
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 displayed or stored. Use an
"accept known good" validation strategy.
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; 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.
Canonicalize the name to match that of the file system's
representation of the name. This can sometimes be achieved with an
available API (e.g. in Win32 the GetFullPathName function).
Sensitive memory is cleared according to the source code, but
compiler optimizations leave the memory untouched when it is not read from
again, aka "dead store removal."
Extended Description
This compiler optimization error occurs when:
1. Secret data are stored in memory.
2. The secret data are scrubbed from memory by overwriting its
contents.
3. The source code is compiled using an optimizing compiler, which
identifies and removes the function that overwrites the contents as a
dead store because the memory is not used subsequently.
Time of Introduction
Implementation
Build and Compilation
Applicable Platforms
Languages
C
C++
Detection Factors
Black Box:
This specific weakness is impossible to detect using black box
methods. While an analyst could examine memory to see that it has not
been scrubbed, an analysis of the executable would not be successful.
This is because the compiler has already removed the relevant code. Only
the source code shows whether the programmer intended to clear the
memory or not, so this weakness is indistinguishable from others.
White Box:
This weakness is only detectable using white box methods (see black
box detection factor). Careful analysis is required to determine if the
code is likely to be removed by the compiler.
Demonstrative Examples
Example 1
The following code reads a password from the user, uses the password
to connect to a back-end mainframe and then attempts to scrub the password
from memory using memset().
(Bad Code)
C
void GetData(char *MFAddr) {
char pwd[64];
if (GetPasswordFromUser(pwd, sizeof(pwd))) {
if (ConnectToMainframe(MFAddr, pwd)) {
// Interaction with mainframe
}
}
memset(pwd, 0, sizeof(pwd));
}
The code in the example will behave correctly if it is executed
verbatim, but if the code is compiled using an optimizing compiler, such
as Microsoft Visual C++ .NET or GCC 3.x, then the call to memset() will
be removed as a dead store because the buffer pwd is not used after its
value is overwritten [18]. Because the buffer pwd contains a sensitive
value, the application may be vulnerable to attack if the data are left
memory resident. If attackers are able to access the correct region of
memory, they may use the recovered password to gain control of the
system. It is common practice to overwrite sensitive data manipulated in
memory, such as passwords or cryptographic keys, in order to prevent
attackers from learning system secrets. However, with the advent of
optimizing compilers, programs do not always behave as their source code
alone would suggest. In the example, the compiler interprets the call to
memset() as dead code because the memory being written to is not
subsequently used, despite the fact that there is clearly a security
motivation for the operation to occur. The problem here is that many
compilers, and in fact many programming languages, do not take this and
other security concerns into consideration in their efforts to improve
efficiency. Attackers typically exploit this type of vulnerability by
using a core dump or runtime mechanism to access the memory used by a
particular application and recover the secret information. Once an
attacker has access to the secret information, it is relatively
straightforward to further exploit the system and possibly compromise
other resources with which the application interacts.
Potential Mitigations
Phase
Description
Implementation
Store the sensitive data in a "volatile" memory location if
available.
Build and Compilation
If possible, configure your compiler so that it does not remove dead
stores.
Architecture and Design
Where possible, encrypt sensitive data that are used by a software
system.
The software detects a specific error, but takes no actions to
handle the error.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Likelihood of Exploit
Medium
Demonstrative Examples
Example 1
The following example attempts to allocate memory for a character.
After the call to malloc, an if statement is used to check whether the
malloc function failed.
(Bad Code)
C
foo=malloc(sizeof(char)); //the next line checks to see if malloc
failed
if (foo==NULL) {
//We do nothing so we just ignore the error.
}
The conditional successfully detects a NULL return value from malloc
indicating a failure, however it does not do anything to handle the
problem. Unhandled errors may have unexpected results and may cause the
program to crash or terminate.
Instead, the if block should contain statements that either attempt to
fix the problem or notify the user that an error has occurred and
continue processing or perform some cleanup and gracefully terminate the
program. The following example notifies the user that the malloc
function did not allocate the required memory resources and returns an
error code.
(Good Code)
C
foo=malloc(sizeof(char)); //the next line checks to see if malloc
failed
if (foo==NULL) {
printf("Malloc failed to allocate memory resources");
return -1;
}
Example 2
In the following C++ example the method readFile() will read the
file whose name is provided in the input parameter and will return the
contents of the file in char string. The method calls open() and read() may
result in errors if the file does not exist or does not contain any data to
read. These errors will be thrown when the is_open() method and good()
method indicate errors opening or reading the file. However, these errors
are not handled within the catch statement. Catch statements that do not
perform any processing will have unexpected results. In this case an empty
char string will be returned, and the file will not be properly
closed.
(Bad Code)
C++
char* readfile (char *filename) {
try {
// open input file
ifstream infile;
infile.open(filename);
if (!infile.is_open()) {
throw "Unable to open file " + filename;
}
// get length of file
infile.seekg (0, ios::end);
int length = infile.tellg();
infile.seekg (0, ios::beg);
// allocate memory
char *buffer = new char [length];
// read data from file
infile.read (buffer,length);
if (!infile.good()) {
throw "Unable to read from file " + filename;
}
infile.close();
return buffer;
}
catch (...) {
/* bug: insert code to handle this later */
}
}
The catch statement should contain statements that either attempt to
fix the problem or notify the user that an error has occurred and
continue processing or perform some cleanup and gracefully terminate the
program. The following C++ example contains two catch statements. The
first of these will catch a specific error thrown within the try block,
and the second catch statement will catch all other errors from within
the catch block. Both catch statements will notify the user that an
error has occurred, close the file, and rethrow to the block that called
the readFile() method for further handling or possible termination of
the program.
(Good Code)
C++
char* readFile (char *filename) {
try {
// open input file
ifstream infile;
infile.open(filename);
if (!infile.is_open()) {
throw "Unable to open file " + filename;
}
// get length of file
infile.seekg (0, ios::end);
int length = infile.tellg();
infile.seekg (0, ios::beg);
// allocate memory
char *buffer = new char [length];
// read data from file
infile.read (buffer,length);
if (!infile.good()) {
throw "Unable to read from file " + filename;
}
infile.close();
return buffer;
}
catch (char *str) {
printf("Error: %s \n", str);
infile.close();
throw str;
}
catch (...) {
printf("Error occurred trying to read from file
\n");
infile.close();
throw;
}
}
Example 3
In the following Java example the method readFile will read the file
whose name is provided in the input parameter and will return the contents
of the file in a String object. The constructor of the FileReader object and
the read method call may throw exceptions and therefore must be within a
try/catch block. While the catch statement in this example will catch thrown
exceptions in order for the method to compile, no processing is performed to
handle the thrown exceptions. Catch statements that do not perform any
processing will have unexpected results. In this case, this will result in
the return of a null String.
(Bad Code)
Java
public String readFile(String filename) {
String retString = null;
try {
// initialize File and FileReader objects
File file = new File(filename);
FileReader fr = new FileReader(file);
// initialize character buffer
long fLen = file.length();
char[] cBuf = new char[(int) fLen];
// read data from file
int iRead = fr.read(cBuf, 0, (int) fLen);
// close file
fr.close();
retString = new String(cBuf);
} catch (Exception ex) {
/* do nothing, but catch so it'll compile... */
}
return retString;
}
The catch statement should contain statements that either attempt to
fix the problem, notify the user that an exception has been raised and
continue processing, or perform some cleanup and gracefully terminate
the program. The following Java example contains three catch statements.
The first of these will catch the FileNotFoundException that may be
thrown by the FileReader constructor called within the try/catch block.
The second catch statement will catch the IOException that may be thrown
by the read method called within the try/catch block. The third catch
statement will catch all other exceptions thrown within the try block.
For all catch statements the user is notified that the exception has
been thrown and the exception is rethrown to the block that called the
readFile() method for further processing or possible termination of the
program. Note that with Java it is usually good practice to use the
getMessage() method of the exception class to provide more information
to the user about the exception raised.
(Good Code)
Java
public String readFile(String filename) throws
FileNotFoundException, IOException, Exception {
System.err.println("Error: IOException reading the input
file.\n" + ex.getMessage() );
throw new IOException(ex);
} catch (Exception ex) {
System.err.println("Error: Exception reading the input
file.\n" + ex.getMessage() );
throw new Exception(ex);
}
return retString;
}
Potential Mitigations
Phase
Description
Implementation
Properly handle each exception. This is the recommended solution.
Ensure that all exceptions are handled in such a way that you can be
sure of the state of your system at any given moment.
Implementation
If a function returns an error, it is important to either fix the
problem and try again, alert the user that an error has happened and let
the program continue, or alert the user and close and cleanup the
program.
Testing
Subject the software to extensive testing to discover some of the
possible instances of where/how errors or return values are not handled.
Consider testing techniques such as ad hoc, equivalence partitioning,
robustness and fault tolerance, mutation, and fuzzing.
The web application fails to adequately enforce appropriate
authorization on all restricted URLs, scripts or files.
Extended Description
Web applications susceptible to direct request attacks often make the
false assumption that such resources can only be reached through a given
navigation path and so only apply authorization at certain points in the
path.
Alternate Terms
forced browsing:
The "forced browsing" term could be misinterpreted to include
weaknesses such as CSRF or XSS, so its use is discouraged.
Time of Introduction
Architecture and Design
Implementation
Operation
Applicable Platforms
Languages
All
Demonstrative Examples
Example 1
If forced browsing is possible, an attacker may be able to directly
access a sensitive page by entering a URL similar to the
following.
Overlaps Modification of Assumed-Immutable Data (MAID), authorization
errors, container errors; often primary to other weaknesses such as XSS and
SQL injection.
Theoretical Notes
"Forced browsing" is a step-based manipulation involving the omission of
one or more steps, whose order is assumed to be immutable. The application
does not verify that the first step was performed successfully before the
second step. The consequence is typically "authentication bypass" or "path
disclosure," although it can be primary to all kinds of weaknesses,
especially in languages such as PHP, which allow external modification of
assumed-immutable variables.
A discrepancy information leak is an information leak in which
the product behaves differently, or sends different responses, in a way that
reveals security-relevant information about the state of the product, such as
whether a particular operation was successful or not.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Potential Mitigations
Phase
Description
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.
Setup generic response for error condition. The error page should not
disclose information about the success or failure of a sensitive
operation. For instance, the login page should not confirm that the
login is correct and the password incorrect. The attacker who tries
random account name may be able to guess some of them. Confirming that
the account exists would make the login page more susceptible to brute
force attack.
This weakness typically occurs when an unexpected value is provided to the
product, or if an error occurs that is not properly detected. It frequently
occurs in calculations involving physical dimensions such as size, length,
width, and height.
Time of Introduction
Implementation
Common Consequences
Scope
Effect
Availability
A Divide by Zero results in a crash.
Likelihood of Exploit
Medium
Demonstrative Examples
Example 1
The following Java example contains a function to compute an average
but does not validate that the input value used as the denominator is not
zero. This will create an exception for attempting to divide by zero. If
this error is not handled by Java exception handling, unexpected results can
occur.
(Bad Code)
Java
public int computeAverageResponseTime (int totalTime, int
numRequests) {
return totalTime / numRequests;
}
By validating the input value used as the denominator the following
code will ensure that a divide by zero error will not cause unexpected
results. The following Java code example will validate the input value,
output an error message, and throw an exception.
(Good Code)
public int computeAverageResponseTime (int totalTime, int
numRequests) throws ArithmeticException {
if (numRequests == 0) {
System.out.println("Division by zero attempted!");
throw ArithmeticException;
}
return totalTime / numRequests;
}
Example 2
The following C/C++ example contains a function that divides two
numeric values without verifying that the input value used as the
denominator is not zero. This will create an error for attempting to divide
by zero, if this error is not caught by the error handling capabilities of
the language, unexpected results can occur.
(Bad Code)
C and C++
double divide(double x, double y){
return x/y;
}
By validating the input value used as the denominator the following
code will ensure that a divide by zero error will not cause unexpected
results. If the method is called and a zero is passed as the second
argument a DivideByZero error will be thrown and should be caught by the
calling block with an output message indicating the error.
The following C# example contains a function that divides two
numeric values without verifying that the input value used as the
denominator is not zero. This will create an error for attempting to divide
by zero, if this error is not caught by the error handling capabilities of
the language, unexpected results can occur.
(Bad Code)
C#
int Division(int x, int y){
return (x / y);
}
The method can be modified to raise, catch and handle the
DivideByZeroException if the input value used as the denominator is
zero.
(Good Code)
int SafeDivision(int x, int y){
try{
return (x / y);
}
catch (System.DivideByZeroException dbz){
System.Console.WriteLine("Division by zero
attempted!");
This category includes weaknesses that occur when an
application does not properly handle errors that occur during
processing.
Extended Description
An attacker may discover this type of error, as forcing these errors can
occur with a variety of corrupt input.
Common Consequences
Scope
Effect
Confidentiality
Generally, the consequences of improper error handling are the
disclosure of the internal workings of the application to the attacker,
providing details to use in further attacks. Web applications that do
not properly handle error conditions frequently generate error messages
such as stack traces, detailed diagnostics, and other inner details of
the application.
Demonstrative Examples
Example 1
In the snippet below, an unchecked runtime exception thrown from
within the try block may cause the container to display its default error
page (which may contain a full stack trace, among other
things).
(Bad Code)
Java
Public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {
...
}
catch (ApplicationSpecificException ase) {
logger.error("Caught: " + ase.toString());
}
}
Potential Mitigations
Phase
Description
Use a standard exception handling mechanism to be sure that your
application properly handles all types of processing errors. All error
messages sent to the user should contain as little detail as necessary
to explain what happened.
If the error was caused by unexpected and likely malicious input, it
may be appropriate to send the user no error message other than a simple
"could not process the request" response.
The details of the error and its cause should be recorded in a
detailed diagnostic log for later analysis. Do not allow the application
to throw errors up to the application container, generally the web
application server.
Be sure that the container is properly configured to handle errors if
you choose to let any errors propagate up to it.
The software generates an error message that includes sensitive
information about its environment, users, or associated
data.
Extended Description
The sensitive information may be valuable information on its own (such as
a password), or it may be useful for launching other, more deadly attacks.
If an attack fails, an attacker may use error information provided by the
server to launch another more focused attack. For example, an attempt to
exploit a path traversal weakness (CWE-22) might yield the full pathname of
the installed application. In turn, this could be used to select the proper
number of ".." sequences to navigate to the targeted file. An attack using
SQL injection (CWE-89) might not initially succeed, but an error message
could reveal the malformed query, which would expose query logic and
possibly even passwords or other sensitive information used within the
query.
Time of Introduction
Architecture and Design
Implementation
System Configuration
Applicable Platforms
Languages
PHP: (Often)
All
Common Consequences
Scope
Effect
Confidentiality
Often this will either reveal sensitive information which may be used
for a later attack or private information stored in the server.
Likelihood of Exploit
High
Demonstrative Examples
Example 1
In the following example, you are passing much more data than is
needed.
(Bad Code)
Java
try {
/.../
}
catch (Exception e) {
System.out.println(e);
}
Another example is passing the SQL exceptions to a WebUser without
filtering.
Example 2
The following code generates an error message that leaks the full
pathname of the configuration file.
(Bad Code)
Perl
$ConfigDir = "/home/myprog/config";
$uname = GetUserInput("username");
# avoid CWE-22, CWE-78, others.
ExitError("Bad hacker!") if ($uname !~ /^\w+$/);
$file = "$ConfigDir/$uname.txt";
if (! (-e $file)) {
ExitError("Error: $file does not exist");
}
...
If this code is running on a server, such as a web application, then
the person making the request should not know what the full pathname of
the configuration directory is. By submitting a username that does not
produce a $file that exists, an attacker could get this pathname. It
could then be used to exploit path traversal or symbolic link following
problems that may exist elsewhere in the application.
Composite: application running with high
privileges allows user to specify a restricted file to process, which
generates a parsing error that leaks the contents of the
file.
Malformed input to login page causes leak of full
path when IMAP call fails.
Potential Mitigations
Phase
Description
Implementation
Ensure that error messages only contain minimal information that are
useful to their intended audience, and nobody else. The messages need to
strike the balance between being too cryptic and not being cryptic
enough. They should not necessarily reveal the methods that were used to
determine the error. Such detailed information can help an attacker
craft another attack that now will pass through the validation
filters.
If errors must be tracked in some detail, capture them in log messages
- but consider what could occur if the log messages can be viewed by
attackers. Avoid recording highly sensitive information such as
passwords in any form. Avoid inconsistent messaging that might
accidentally tip off an attacker about internal state, such as whether a
username is valid or not.
Implementation
Handle exceptions internally and do not display errors containing
potentially sensitive information to a user.
Build and Compilation
Debugging information should not make its way into a production
release.
Testing
Identify error conditions that are not likely to occur during normal
usage and trigger them. For example, run the program under low memory
conditions, run with insufficient privileges or permissions, interrupt a
transaction before it is completed, or disable connectivity to basic
network services such as DNS. Monitor the software for any unexpected
behavior. If you trigger an unhandled exception or similar error that
was discovered and handled by the application's environment, it may
still indicate unexpected conditions that were not handled by the
application itself.
Testing
Stress-test the software by calling it simultaneously from a large
number of threads or processes, and look for evidence of any unexpected
behavior. The software's operation may slow down, but it should not
become unstable, crash, or generate incorrect results.
System Configuration
Where available, configure the environment to use less verbose error
messages. For example, in PHP, disable the display_errors setting during
configuration, or at runtime using the error_reporting()
function.
System Configuration
Create default error pages or messages that do not leak any
information.
External Control of Assumed-Immutable Web Parameter
Definition in a New Window
Weakness ID: 472 (Weakness Base)
Status: Draft
Description
Description Summary
The web application does not sufficiently verify inputs that
are assumed to be immutable but are actually externally controllable, such as
hidden form fields.
Extended Description
If a web product does not properly protect assumed-immutable values from
modification in hidden form fields, parameters, cookies, or URLs, this can
lead to modification of critical data. Web applications often mistakenly
make the assumption that data passed to the client in hidden fields or
cookies is not susceptible to tampering. Failure to validate portions of
data that are user-controllable can lead to the application processing
incorrect, and often malicious, input.
For example, custom cookies commonly store session data or persistent
data across sessions. This kind of session data is normally involved in
security related decisions on the server side, such as user authentication
and access control. Thus, the cookies might contain sensitive data such as
user credentials and privileges. This is a dangerous practice, as it can
often lead to improper reliance on the value of the client-provided cookie
by the server side application.
Alternate Terms
Assumed-Immutable Parameter Tampering
Time of Introduction
Implementation
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Integrity
Without appropriate protection mechanisms, the client can easily
tamper with cookies and similar web data. Reliance on the cookies
without detailed validation can lead to problems such as SQL injection.
If you use cookie values for security related decisions on the server
side, manipulating the cookies might lead to violations of security
policies such as authentication bypassing, user impersonation and
privilege escalation. In addition, storing sensitive data in the cookie
without appropriate protection can also lead to disclosure of sensitive
user data, especially data stored in persistent cookies.
Demonstrative Examples
Example 1
Here, a web application uses the value of a hidden form field
(accountID) without having done any input validation because it was assumed
to be immutable.
User user = getUserFromID(Long.parseLong(accountID));
Example 2
Hidden fields should not be trusted as secure parameters. An attacker
can intercept and alter hidden fields in a post to the server as easily
as user input fields. An attacker can simply parse the HTML for the
substring:
< input type "hidden"
or even just "hidden". Hidden field values displayed later in the
session, such as on the following page, can open a site up to cross-site
scripting attacks.
Modification of message number parameter allows
attackers to read other people's messages.
Potential Mitigations
Phase
Description
Architecture and Design
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 displayed or stored. Use an
"accept known good" validation strategy. Input (specifically, unexpected
CRLFs) that is not appropriate should not be processed into HTTP
headers.
Use and specify a strong input/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; 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.
The software allows user input to control or influence paths or
file names that are used in filesystem operations.
Extended Description
This could allow an attacker to access or modify system files or other
files that are critical to the application.
Path manipulation errors occur when the following two conditions are
met:
1. An attacker can specify a path used in an operation on the
filesystem.
2. By specifying the resource, the attacker gains a capability that
would not otherwise be permitted.
For example, the program may give the attacker the ability to overwrite
the specified file or run with a configuration controlled by the attacker.
Time of Introduction
Architecture and Design
Implementation
Operation
Applicable Platforms
Languages
All
Operating Systems
UNIX: (Often)
Windows: (Often)
Mac OS: (Often)
Common Consequences
Scope
Effect
Confidentiality
The application can operate on unexpected files. Confidentiality is
violated when the targeted filename is not directly readable by the
attacker.
Integrity
The application can operate on unexpected files. This may violate
integrity if the filename is written to, or if the filename is for a
program or other form of executable code.
Availability
The application can operate on unexpected files. Availability can be
violated if the attacker specifies an unexpected file that the
application modifies. Availability can also be affected if the attacker
specifies a filename for a large file, or points to a special device or
a file that does not have the format that the application
expects.
Likelihood of Exploit
High to Very High
Demonstrative Examples
Example 1
The following code uses input from an HTTP request to create a file
name. The programmer has not considered the possibility that an attacker
could provide a file name such as "../../tomcat/conf/server.xml", which
causes the application to delete one of its own configuration files
(CWE-22).
File rFile = new File("/usr/local/apfr/reports/" + rName);
...
rFile.delete();
Example 2
The following code uses input from a configuration file to determine
which file to open and echo back to the user. If the program runs with
privileges and malicious users can change the configuration file, they can
use the program to read any file on the system that ends with the extension
.txt.
(Bad Code)
Java
fis = new FileInputStream(cfg.getProperty("sub")+".txt");
Chain: external control of user's target language
enables remote file inclusion.
Potential Mitigations
Phase
Description
Architecture and Design
When the set of filenames is limited or known, create a mapping from a
set of fixed input values (such as numeric IDs) to the actual filenames,
and reject all other inputs. For example, ID 1 could map to "inbox.txt"
and ID 2 could map to "profile.txt". Features such as the ESAPI
AccessReferenceMap provide this capability.
Architecture and Design
Operation
Run your code in a "jail" or similar sandbox environment that enforces
strict boundaries between the process and the operating system. This may
effectively restrict all access to files within a particular
directory.
Examples include the Unix chroot jail and AppArmor. In general,
managed code may provide some protection.
This may not be a feasible solution, and it only limits the impact to
the operating system; the rest of your application may still be subject
to compromise.
Be careful to avoid CWE-243 and other weaknesses related to jails.
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.
Implementation
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.
For filenames, use stringent whitelists that limit the character set
to be used. If feasible, only allow a single "." character in the
filename to avoid weaknesses such as CWE-23, and exclude directory
separators such as "/" to avoid CWE-36. Use a whitelist of allowable
file extensions, which will help to avoid CWE-434.
Implementation
Use a built-in path canonicalization function (such as realpath() in
C) that produces the canonical version of the pathname, which
effectively removes ".." sequences and symbolic links (CWE-23,
CWE-59).
Installation
Operation
Use OS-level permissions and run as a low-privileged user to limit the
scope of any successful attack.
Operation
Implementation
If you are using PHP, configure your application so that it does not
use register_globals. During implementation, develop your application so
that it does not rely on this feature, but be wary of implementing a
register_globals emulation that is subject to weaknesses such as CWE-95,
CWE-621, and similar issues.
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.
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.
Testing
Use tools and techniques that require manual (human) analysis, such as
penetration testing, threat modeling, and interactive tools that allow
the tester to record and modify an active session. These may be more
effective than strictly automated techniques. This is especially the
case with weaknesses that are related to design and business
rules.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)
The external control of filenames can be the primary link in chains with
other file-related weaknesses, as seen in the CanPrecede relationships. This
is because software systems use files for many different purposes: to
execute programs, load code libraries, to store application data, to store
configuration settings, record temporary data, act as signals or semaphores
to other processes, etc.
However, those weaknesses do not always require external control. For
example, link-following weaknesses (CWE-59) often involve pathnames that are
not controllable by the attacker at all.
The external control can be resultant from other issues. For example, in
PHP applications, the register_globals setting can allow an attacker to
modify variables that the programmer thought were immutable, enabling file
inclusion (CWE-98) and path traversal (CWE-22). Operating with excessive
privileges (CWE-250) might allow an attacker to specify an input filename
that is not directly readable by the attacker, but is accessible to the
privileged program. A buffer overflow (CWE-119) might give an attacker
control over nearby memory locations that are related to pathnames, but were
not directly modifiable by the attacker.
Failure to Constrain Operations within the Bounds of a Memory Buffer
Definition in a New Window
Weakness ID: 119 (Weakness Class)
Status: Usable
Description
Description Summary
The software performs operations on a memory buffer, but it can
read from or write to a memory location that is outside of the intended boundary
of the buffer.
Extended Description
Certain languages allow direct addressing of memory locations and do not
automatically ensure that these locations are valid for the memory buffer
that is being referenced. This can cause read or write operations to be
performed on memory locations that may be associated with other variables,
data structures, or internal program data.
As a result, an attacker may be able to execute arbitrary code, alter the
intended control flow, read sensitive information, or cause the system to
crash.
Time of Introduction
Architecture and Design
Implementation
Operation
Applicable Platforms
Languages
C: (Often)
C++: (Often)
All
Platform Notes
It is possible in many programming languages to attempt an operation
outside of the bounds of a memory buffer, but the consequences will vary
widely depending on the language, platform, and chip architecture.
Common Consequences
Scope
Effect
Integrity
If the memory accessible by the attacker can be effectively
controlled, it may be possible to execute arbitrary code, as with a
standard buffer overflow.
If the attacker can overwrite a pointer's worth of memory (usually 32
or 64 bits), he can redirect a function pointer to his own malicious
code. Even when the attacker can only modify a single byte arbitrary
code execution can be possible. Sometimes this is because the same
problem can be exploited repeatedly to the same effect. Other times it
is because the attacker can overwrite security-critical
application-specific data -- such as a flag indicating whether the user
is an administrator.
Availability
Out of bounds memory access will very likely result in the corruption
of relevant memory, and perhaps instructions, possibly leading to a
crash. Other attacks leading to lack of availability are possible,
including putting the program into an infinite loop.
Confidentiality
In the case of an out-of-bounds read, the attacker may have access to
sensitive information. If the sensitive information contains system
details, such as the current buffers position in memory, this knowledge
can be used to craft further attacks, possibly with more severe
consequences.
Likelihood of Exploit
High
Demonstrative Examples
Example 1
This example takes an IP address from a user, verifies that it is
well formed and then looks up the hostname and copies it into a
buffer.
(Bad Code)
C
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);
/*routine that ensures user_supply_addr is in the right format
for conversion */
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr),
AF_INET);
strcpy(&hostname, hp->h_name);
}
This function allocates a buffer of 64 bytes to store the hostname,
however there is no guarantee that the hostname will not be larger than
64 bytes. If an attacker specifies an address which resolves to a very
large hostname, then we may overwrite sensitive data or even relinquish
control flow to the attacker.
Example 2
This example applies an encoding procedure to an input string and
stores it into a buffer.
The programmer attempts to encode the ampersand character in the
user-controlled string, however the length of the string is validated
before the encoding procedure is applied. Furthermore, the programmer
assumes encoding expansion will only expand a given character by a
factor of 4, while the encoding of the ampersand expands by 5. As a
result, when the encoding procedure expands the string it is possible to
overflow the destination buffer if the attacker provides a string of
many ampersands.
Example 3
The following example asks a user for an offset into an array to
select an item.
The programmer allows the user to specify which element in the list to
select, however an attacker can provide an out-of-bounds offset,
resulting in a buffer over-read (CWE-126).
OS kernel trusts userland-supplied length value,
allowing reading of sensitive information
Potential Mitigations
Phase
Description
Requirements
Use a language with features that can automatically mitigate or
eliminate buffer overflows.
For example, many languages that perform their own memory management,
such as Java and Perl, are not subject to buffer overflows. Other
languages, such as Ada and C#, typically provide overflow protection,
but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be
subject to overflows, even if the language itself is theoretically safe.
Architecture and Design
Use languages, libraries, or frameworks that make it easier to manage
buffers without exceeding their boundaries.
Examples include the Safe C String Library (SafeStr) by Messier and
Viega, and the Strsafe.h library from Microsoft. These libraries provide
safer versions of overflow-prone string-handling functions. This is not
a complete solution, since many buffer overflows are not related to
strings.
Build and Compilation
Run or compile your software using features or extensions that
automatically provide a protection mechanism that mitigates or
eliminates buffer overflows.
For example, certain compilers and extensions provide automatic buffer
overflow detection mechanisms that are built into the compiled code.
Examples include the Microsoft Visual Studio /GS flag, Fedora/Red Hat
FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice.
This is not necessarily a complete solution, since these mechanisms
can only detect certain types of overflows. In addition, a buffer
overflow attack can still cause 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 application's 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.
If necessary, truncate all input strings to a reasonable length
before passing them to the copy and concatenation functions.
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.
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.
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. In addition, it cannot be used in
cases in which self-modifying code is required.
The failure to encrypt data passes up the guarantees of
confidentiality, integrity, and accountability that properly implemented
encryption conveys.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Confidentiality
Properly encrypted data channels ensure data confidentiality.
Integrity
Properly encrypted data channels ensure data integrity.
Accountability
Properly encrypted data channels ensure accountability.
Confidentiality
If the application does not use a secure channel, such as SSL, to
exchange sensitive information, it is possible for an attacker with
access to the network traffic to sniff packets from the connection and
uncover the data. This attack is not technically difficult, but does
require physical access to some portion of the network over which the
sensitive data travels. This access is usually somewhere near where the
user is connected to the network (such as a colleague on the company
network) but can be anywhere along the path from the user to the end
server.
Confidentiality
Integrity
Omitting the use of encryption in any program which transfers data
over a network of any kind should be considered on par with delivering
the data sent to each user on the local networks of both the sender and
receiver. Worse, this omission allows for the injection of data into a
stream of communication between two parties -- with no means for the
victims to separate valid data from invalid. In this day of widespread
network attacks and password collection sniffers, it is an unnecessary
risk to omit encryption from the design of any system which might
benefit from it.
Likelihood of Exploit
Very High
Demonstrative Examples
Example 1
(Bad Code)
C
server.sin_family = AF_INET; hp = gethostbyname(argv[1]);
Failure to Preserve Web Page Structure ('Cross-site Scripting')
Definition in a New Window
Weakness ID: 79 (Weakness Base)
Status: Usable
Description
Description Summary
The software does not sufficiently validate, filter, escape,
and encode user-controllable input before it is placed in output that is used as
a web page that is served to other users.
1. Untrusted data enters a web application, typically from a web
request.
2. The web application dynamically generates a web page that contains
this untrusted data.
3. During page generation, the application does not prevent the data
from containing content that is executable by a web browser, such as
JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX,
etc.
4. A victim visits the generated web page through a web browser, which
contains malicious script that was injected using the untrusted
data.
5. Since the script comes from a web page that was sent by the web
server, the web browser executes the malicious script in the context of
the web server's domain.
6. This effectively violates the intention of the web browser's
same-origin policy, which states that scripts in one domain should not
be able to access resources or run code in a different domain.
There are three main kinds of XSS:
Type 1: Reflected XSS (or Non-Persistent)
The server reads data directly from the HTTP request and reflects it
back in the HTTP response. Reflected XSS exploits occur when an attacker
causes a user to supply dangerous content to a vulnerable web
application, which is then reflected back to the user and executed by
the web browser. The most common mechanism for delivering malicious
content is to include it as a parameter in a URL that is posted publicly
or e-mailed directly to victims. URLs constructed in this manner
constitute the core of many phishing schemes, whereby an attacker
convinces victims to visit a URL that refers to a vulnerable site. After
the site reflects the attacker's content back to the user, the content
is executed and proceeds to transfer private information, such as
cookies that may include session information, from the user's machine to
the attacker or perform other nefarious activities.
Type 2: Stored XSS (or Persistent)
The application stores dangerous data in a database, message forum,
visitor log, or other trusted data store. The dangerous data is
subsequently read back into the application and included in dynamic
content. Stored XSS exploits occur when an attacker injects dangerous
content into a data store that is later read and included in dynamic
content. From an attacker's perspective, the optimal place to inject
malicious content is in an area that is displayed to either many users
or particularly interesting users. Interesting users typically have
elevated privileges in the application or interact with sensitive data
that is valuable to the attacker. If one of these users executes
malicious content, the attacker may be able to perform privileged
operations on behalf of the user or gain access to sensitive data
belonging to the user. For example, the attacker might inject XSS into a
log message, which might not be handled properly when an administrator
views the logs.
Type 0: DOM-Based XSS
In DOM-based XSS, the client performs the injection of XSS into the
page; in the other types, the server performs the injection. DOM-based
XSS generally involves server-controlled, trusted script that is sent to
the client, such as Javascript that performs sanity checks on a form
before the user submits it. If the server-supplied script processes
user-supplied data and then injects it back into the web page (such as
with dynamic HTML), then DOM-based XSS is possible.
In many cases, the attack can be launched without the victim even being
aware of it. Even with careful users, attackers frequently use a variety of
methods to encode the malicious portion of the attack, such as URL encoding
or Unicode, so the request looks less suspicious.
Alternate Terms
XSS
CSS:
"CSS" was once used as the acronym for this problem, but this could
cause confusion with "Cascading Style Sheets," so usage of this acronym
has declined significantly.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Architectural Paradigms
Web-based: (Often)
Technology Classes
Web-Server: (Often)
Platform Notes
XSS flaws are very common in web applications since they require a great
deal of developer discipline to avoid them.
Common Consequences
Scope
Effect
Confidentiality
The most common attack performed with cross-site scripting involves
the disclosure of information stored in user cookies. Typically, a
malicious user will craft a client-side script, which -- when parsed by
a web browser -- performs some activity (such as sending all site
cookies to a given E-mail address). This script will be loaded and run
by each user visiting the web site. Since the site requesting to run the
script has access to the cookies in question, the malicious script does
also.
Access Control
In some circumstances it may be possible to run arbitrary code on a
victim's computer when cross-site scripting is combined with other
flaws.
Confidentiality
Integrity
Availability
The consequence of an XSS attack is the same regardless of whether it
is stored or reflected. The difference is in how the payload arrives at
the server.
XSS can cause a variety of problems for the end user that range in
severity from an annoyance to complete account compromise. Some
cross-site scripting vulnerabilities can be exploited to manipulate or
steal cookies, create requests that can be mistaken for those of a valid
user, compromise confidential information, or execute malicious code on
the end user systems for a variety of nefarious purposes. Other damaging
attacks include the disclosure of end user files, installation of Trojan
horse programs, redirecting the user to some other page or site, running
"Active X" controls (under Microsoft Internet Explorer) from sites that
a user perceives as trustworthy, and modifying presentation of
content.
Likelihood of Exploit
High to Very High
Enabling Factors for Exploitation
Cross-site scripting attacks may occur anywhere that possibly malicious
users are allowed to post unregulated material to a trusted web site for the
consumption of other valid users, commonly on places such as bulletin-board
web sites which provide web based mailing list-style functionality.
Detection Factors
It is relatively easy for an attacker to find XSS vulnerabilities.
Some of these vulnerabilities can be found using scanners, and some
exist in older web application servers.
Demonstrative Examples
Example 1
This example covers a Reflected XSS (Type 1) scenario.
The following JSP code segment reads an employee ID, eid, from an HTTP
request and displays it to the user.
(Bad Code)
JSP
<% String eid = request.getParameter("eid");
%>
...
Employee ID: <%= eid %>
The following ASP.NET code segment reads an employee ID number from an
HTTP request and displays it to the user.