This view (graph) organizes weaknesses using a hierarchical structure that is
similar to that used by Seven Pernicious Kingdoms.
View Metrics
CWEs in this view
Total CWEs
Total
96
out of
791
Views
0
out of
22
Categories
7
out of
106
Weaknesses
87
out of
651
Compound_Elements
2
out of
12
View Audience
Stakeholder
Description
Developers
This view is useful for developers because it is organized around
concepts with which developers are familiar, and it focuses on
weaknesses that can be detected using source code analysis tools.
Alternate Terms
7PK:
"7PK" is frequently used by the MITRE team as an abbreviation.
Debugging messages help attackers learn about the system and
plan a form of attack.
Extended Description
ASP .NET applications can be configured to produce debug binaries. These
binaries give detailed debugging messages and should not be used in
production environments. Debug binaries are meant to be used in a
development or testing environment and can pose a security risk if they are
deployed to production.
Time of Introduction
Implementation
Operation
Applicable Platforms
Languages
.NET
Common Consequences
Scope
Effect
Confidentiality
Attackers can leverage the additional information they gain from
debugging output to mount attacks targeted on the framework, database,
or other resources used by the application.
Demonstrative Examples
Example 1
The file web.config contains the debug mode setting. Setting debug
to "true" will let the browser display debugging information.
(Bad Code)
XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
/>
...
</system.web>
</configuration>
Change the debug mode to false when the application is deployed into
production.
Potential Mitigations
Phase
Description
Avoid releasing debug binaries into the production environment. Change
the debug mode to false when the application is deployed into production
(See demonstrative example).
Background Details
The debug attribute of the <compilation> tag defines whether
compiled binaries should include debugging information. The use of debug
binaries causes an application to provide as much information about itself
as possible to the user.
ASP.NET Misconfiguration: Missing Custom Error Page
Definition in a New Window
Weakness ID: 12 (Weakness Variant)
Status: Draft
Description
Description Summary
An ASP .NET application must enable custom error pages in order
to prevent attackers from mining information from the framework's built-in
responses.
Time of Introduction
Implementation
Operation
Applicable Platforms
Languages
.NET
Common Consequences
Scope
Effect
Confidentiality
Default error pages gives detailed information about the error that
occurred, and should not be used in production environments.
Attackers can leverage the additional information provided by a
default error page to mount attacks targeted on the framework, database,
or other resources used by the application.
Demonstrative Examples
Example 1
Custom error message mode is turned off. An ASP.NET error message
with detailed stack trace and platform versions will be
returned.
(Bad Code)
ASP.NET
<customErrors ... mode="Off" />
Example 2
Custom error message mode for remote user only. No defaultRedirect
error page is specified. The local user on the web server will see a
detailed stack trace. For remote users, an ASP.NET error message with the
server customError configuration setting and the platform version will be
returned.
(Good Code)
ASP.NET
<customErrors mode="RemoteOnly" />
Potential Mitigations
Phase
Description
Handle exceptions appropriately in source code. The best practice is
to use a custom error message. Make sure that the mode attribute is set
to "RemoteOnly" in the web.config file as shown in the following
example.
(Good Code)
<customErrors mode="RemoteOnly" />
The mode attribute of the <customErrors> tag in the
Web.config file defines whether custom or default error pages are used.
It should be configured to use a custom page as follows:
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
Demonstrative Examples
Example 1
The following connectionString has clear text
credentials.
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
The program compares classes by name, which can cause it to use
the wrong class when multiple classes can have the same
name.
Extended Description
If the decision to trust the methods and data of an object is based on the
name of a class, it is possible for malicious users to send objects of the
same name as trusted classes and thereby gain the trust afforded to known
classes and types.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
Common Consequences
Scope
Effect
Authorization
If a program relies solely on the name of an object to determine
identity, it may execute the incorrect or unintended code.
Likelihood of Exploit
High
Demonstrative Examples
Example 1
(Bad Code)
Java
if (inputClass.getClass().getName().equals("TrustedClassName"))
{
// Do something assuming you trust inputClass
// ...
}
Potential Mitigations
Phase
Description
Implementation
Use class equivalency to determine type. Rather than use the class
name to determine if an object is of a given type, use the getClass()
method, and == operator.
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 product has a critical public variable that is not final,
which allows the variable to be modified to contain unexpected
values.
Extended Description
If a field is non-final and public, it can be changed once the value is
set by any function that has access to the class which contains the field.
This could lead to a vulnerability if other parts of the program make
assumptions about the contents of that field.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
C++
Common Consequences
Scope
Effect
Integrity
The object could potentially be tampered with.
Confidentiality
The object could potentially allow the object to be read.
Likelihood of Exploit
High
Demonstrative Examples
Example 1
Suppose this WidgetData class is used for an e-commerce web site.
The programmer attempts to prevent price-tampering attacks by setting the
price of the widget using the constructor.
(Bad Code)
Java
public final class WidgetData extends Applet {
public float price;
...
public WidgetData(...) {
this.price = LookupPrice("MyWidgetType");
}
}
The price field is not final. Even though the value is set by the
constructor, it could be modified by anybody that has access to an
instance of WidgetData.
Example 2
Assume the following code is intended to provide the location of a
configuration file that controls execution of the application.
(Bad Code)
C++
public string configPath = "/etc/application/config.dat";
(Bad Code)
Java
public String configPath = new
String("/etc/application/config.dat");
While this field is readable from any function, and thus might allow
an information leak of a pathname, a more serious problem is that it can
be changed by any function.
Potential Mitigations
Phase
Description
Implementation
Declare all public fields as final when possible, especially if it is
used to maintain internal state of an Applet or of classes used by an
Applet. If a field must be public, then perform all appropriate sanity
checks before accessing the field from your code.
Background Details
Mobile code, such as a Java Applet, is code that is transmitted across a
network and executed on a remote machine. Because mobile code developers
have little if any control of the environment in which their code will
execute, special security concerns become relevant. One of the biggest
environmental threats results from the risk that the mobile code will run
side-by-side with other, potentially malicious, mobile code. Because all of
the popular web browsers execute code from multiple sources together in the
same JVM, many of the security guidelines for mobile code are focused on
preventing manipulation of your objects' state and behavior by adversaries
who have access to the same virtual machine where your program is
running.
Final provides security by only allowing non-mutable objects to be changed
after being set. However, only objects which are not extended can be made
final.
The product does not sufficiently enforce boundaries between
the states of different sessions, causing data to be provided to, or used by,
the wrong session.
Extended Description
Data can "bleed" from one session to another through member variables of
singleton objects, such as Servlets, and objects from a shared pool.
In the case of Servlets, developers sometimes do not understand that,
unless a Servlet implements the SingleThreadModel interface, the Servlet is
a singleton; there is only one instance of the Servlet, and that single
instance is used and re-used to handle multiple requests that are processed
simultaneously by different threads. A common result is that developers use
Servlet member fields in such a way that one user may inadvertently see
another user's data. In other words, storing user data in Servlet member
fields introduces a data access race condition.
Time of Introduction
Implementation
Applicable Platforms
Languages
All
Demonstrative Examples
Example 1
The following Servlet stores the value of a request parameter in a
member field and then later echoes the parameter value to the response
output stream.
While this code will work perfectly in a single-user environment, if
two users access the Servlet at approximately the same time, it is
possible for the two request handler threads to interleave in the
following way: Thread 1: assign "Dick" to name Thread 2: assign "Jane"
to name Thread 1: print "Jane, thanks for visiting!" Thread 2: print
"Jane, thanks for visiting!" Thereby showing the first user the second
user's name.
Potential Mitigations
Phase
Description
Protect the application's sessions from information leakage. Make sure
that a session's data is not used or visible by other sessions.
Use a static analysis tool to scan the code for information leakage
vulnerabilities (e.g. Singleton Member Field).
In multithreading environment, storing user data in Servlet member
fields introduces a data access race condition. Do not use member fields
to store information in the Servlet.
Catching overly broad exceptions promotes complex error
handling code that is more likely to contain security
vulnerabilities.
Extended Description
Multiple catch blocks can get ugly and repetitive, but "condensing" catch
blocks by catching a high-level class like Exception can obscure exceptions
that deserve special treatment or that should not be caught at this point in
the program. Catching an overly broad exception essentially defeats the
purpose of Java's typed exceptions, and can become particularly dangerous if
the program grows and begins to throw new types of exceptions. The new
exception types will not receive any attention.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C++
Java
.NET
Demonstrative Examples
Example 1
The following code excerpt handles three types of exceptions in an
identical fashion.
(Good Code)
Java
try {
doExchange();
}
catch (IOException e) {
logger.error("doExchange failed", e);
}
catch (InvocationTargetException e) {
logger.error("doExchange failed", e);
}
catch (SQLException e) {
logger.error("doExchange failed", e);
}
At first blush, it may seem preferable to deal with these exceptions
in a single catch block, as follows:
(Bad Code)
try {
doExchange();
}
catch (Exception e) {
logger.error("doExchange failed", e);
}
However, if doExchange() is modified to throw a new type of exception
that should be handled in some different kind of way, the broad catch
block will prevent the compiler from pointing out the situation.
Further, the new catch block will now also handle exceptions derived
from RuntimeException such as ClassCastException, and
NullPointerException, which is not the programmer's intent.
Throwing overly broad exceptions promotes complex error
handling code that is more likely to contain security
vulnerabilities.
Extended Description
Declaring a method to throw Exception or Throwable makes it difficult for
callers to perform proper error handling and error recovery. Java's
exception mechanism, for example, is set up to make it easy for callers to
anticipate what can go wrong and write code to handle each specific
exceptional circumstance. Declaring that a method throws a generic form of
exception defeats this system.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C++
Java
.NET
Demonstrative Examples
Example 1
The following method throws three types of exceptions.
(Good Code)
Java
public void doExchange() throws IOException,
InvocationTargetException, SQLException {
...
}
While it might seem tidier to write
(Bad Code)
public void doExchange() throws Exception {
...
}
doing so hampers the caller's ability to understand and handle the
exceptions that occur. Further, if a later revision of doExchange()
introduces a new type of exception that should be treated differently
than previous exceptions, there is no easy way to enforce this
requirement.
When a Java application uses the Java Native Interface (JNI) to
call code written in another programming language, it can expose the application
to weaknesses in that code, even if those weaknesses cannot occur in
Java.
Extended Description
Many safety features that programmers may take for granted simply do not
apply for native code, so you must carefully review all such code for
potential problems. The languages used to implement native code may be more
susceptible to buffer overflows and other attacks. Native code is
unprotected by the security features enforced by the runtime environment,
such as strong typing and array bounds checking.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
Demonstrative Examples
Example 1
The following code defines a class named Echo. The class declares
one native method (defined below), which uses C to echo commands entered on
the console back to the user. The following C code defines the native method
implemented in the Echo class:
Java
class Echo {
public native void runEcho();
static {
System.loadLibrary("echo");
}
public static void main(String[] args) {
new Echo().runEcho();
}
}
C
#include <jni.h>
#include "Echo.h"//the java class above compiled with javah
#include <stdio.h>
JNIEXPORT void JNICALL
Java_Echo_runEcho(JNIEnv *env, jobject obj)
{
char buf[64];
gets(buf);
printf(buf);
}
Because the example is implemented in Java, it may appear that it is
immune to memory issues like buffer overflow vulnerabilities. Although
Java does do a good job of making memory operations safe, this
protection does not extend to vulnerabilities occurring in source code
written in other languages that are accessed using the Java Native
Interface. Despite the memory protections offered in Java, the C code in
this example is vulnerable to a buffer overflow because it makes use of
gets(), which does not perform any bounds checking on its input. The Sun
Java(TM) Tutorial provides the following description of JNI [See
Reference]: The JNI framework lets your native method utilize Java
objects in the same way that Java code uses these objects. A native
method can create Java objects, including arrays and strings, and then
inspect and use these objects to perform its tasks. A native method can
also inspect and use objects created by Java application code. A native
method can even update Java objects that it created or that were passed
to it, and these updated objects are available to the Java application.
Thus, both the native language side and the Java side of an application
can create, update, and access Java objects and then share these objects
between them. The vulnerability in the example above could easily be
detected through a source code audit of the native method
implementation. This may not be practical or possible depending on the
availability of the C source code and the way the project is built, but
in many cases it may suffice. However, the ability to share objects
between Java and native methods expands the potential risk to much more
insidious cases where improper data handling in Java may lead to
unexpected vulnerabilities in native code or unsafe operations in native
code corrupt data structures in Java. Vulnerabilities in native code
accessed through a Java application are typically exploited in the same
manner as they are in applications written in the native language. The
only challenge to such an attack is for the attacker to identify that
the Java application uses native code to perform certain operations.
This can be accomplished in a variety of ways, including identifying
specific behaviors that are often implemented with native code or by
exploiting a system information leak in the Java application that
exposes its use of JNI [See Reference].
Potential Mitigations
Phase
Description
Implement error handling around the JNI call.
Do not use JNI calls if you don't trust the native library.
Be reluctant to use JNI calls. A Java API equivalent may exist.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)
The product calls free() twice on the same memory address,
potentially leading to modification of unexpected memory
locations.
Extended Description
When a program calls free() twice with the same argument, the program's
memory management data structures become corrupted. This corruption can
cause the program to crash or, in some circumstances, cause two later calls
to malloc() to return the same pointer. If malloc() returns the same value
twice and the program later gives the attacker control over the data that is
written into this doubly-allocated memory, the program becomes vulnerable to
a buffer overflow attack.
Alternate Terms
Double-free
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
C
C++
Common Consequences
Scope
Effect
Access Control
Doubly freeing memory may result in a write-what-where condition,
allowing an attacker to execute arbitrary code.
Likelihood of Exploit
Low to Medium
Demonstrative Examples
Example 1
The following code shows a simple example of a double free
vulnerability.
(Bad Code)
C
char* ptr = (char*)malloc (SIZE);
...
if (abrt) {
free(ptr);
}
...
free(ptr);
Double free vulnerabilities have two common (and sometimes
overlapping) causes:
Error conditions and other exceptional circumstances
Confusion over which part of the program is responsible for
freeing the memory
Although some double free vulnerabilities are not much more
complicated than the previous example, most are spread out across
hundreds of lines of code or even different files. Programmers seem
particularly susceptible to freeing global variables more than
once.
Example 2
While contrived, this code should be exploitable on Linux
distributions which do not ship with heap-chunk check summing turned
on.
Choose a language that provides automatic memory management.
Implementation
Ensure that each allocation is freed only once. After freeing a chunk,
set the pointer to NULL to ensure the pointer cannot be freed again. In
complicated error conditions, be sure that clean-up routines respect the
state of allocation properly. If the language is object oriented, ensure
that object destructors delete each chunk of memory only once.
Implementation
Use a static analysis tool to find double free instances.
This is usually resultant from another weakness, such as an unhandled
error or race condition between threads. It could also be primary to
weaknesses such as buffer overflows.
Affected Resources
Memory
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
PLOVER
DFREE - Double-Free Vulnerability
7 Pernicious Kingdoms
Double Free
CLASP
Doubly freeing memory
CERT C Secure Coding
MEM00-C
Allocate and free memory in the same module, at the same level
of abstraction
CERT C Secure Coding
MEM01-C
Store a new value in pointers immediately after
free()
CERT C Secure Coding
MEM31-C
Free dynamically allocated memory exactly
once
White Box Definitions
A weakness where code path has:
1. start statement that relinquishes a dynamically allocated memory
resource
2. end statement that relinquishes the dynamically allocated memory
resource
Maintenance Notes
It could be argued that Double Free would be most appropriately located as
a child of "Use after Free", but "Use" and "Release" are considered to be
distinct operations within vulnerability theory, therefore this is more
accurately "Release of a Resource after Expiration or Release", which
doesn't exist yet.
Content History
Submissions
Submission Date
Submitter
Organization
Source
PLOVER
Externally Mined
Modifications
Modification Date
Modifier
Organization
Source
2008-07-01
Eric Dalci
Cigital
External
updated Potential Mitigations,
Time of Introduction
2008-08-01
KDM Analytics
External
added/updated white box definitions
2008-09-08
CWE Content Team
MITRE
Internal
updated Applicable Platforms, Common Consequences,
Description, Maintenance Notes, Relationships, Other Notes,
Relationship Notes, Taxonomy Mappings
Passwords should be at least eight characters long -- the longer the
better. Avoid passwords that are in any way similar to other passwords
you have. Avoid using words that may be found in a dictionary, names
book, on a map, etc. Consider incorporating numbers and/or punctuation
into your password. If you do use common words, consider replacing
letters in that word with numbers and punctuation. However, do not use
"similar-looking" punctuation. For example, it is not a good idea to
change cat to c@t, ca+, (@+, or anything similar. Finally, it is never
appropriate to use an empty string as a password.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)
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 performs an operation at a privilege level that is
higher than the minimum level required, which creates new weaknesses or
amplifies the consequences of other weaknesses.
Extended Description
New weaknesses can be exposed because running with extra privileges, such
as root or Administrator, can disable the normal security checks being
performed by the operating system or surrounding environment. Other
pre-existing weaknesses can turn into security vulnerabilities if they occur
while operating at raised privileges.
Privilege management functions can behave in some less-than-obvious ways,
and they have different quirks on different platforms. These inconsistencies
are particularly pronounced if you are transitioning from one non-root user
to another. Signal handlers and spawned processes run at the privilege of
the owning process, so if a process is running as root when a signal fires
or a sub-process is executed, the signal handler or sub-process will operate
with root privileges.
Time of Introduction
Installation
Architecture and Design
Operation
Applicable Platforms
Languages
All
Modes of Introduction
If an application has this design problem, then it can be easier for the
developer to make implementation-related errors such as CWE-271 (Privilege
Dropping / Lowering Errors). In addition, the consequences of Privilege
Chaining (CWE-268) can become more severe.
Common Consequences
Scope
Effect
Confidentiality
Integrity
Availability
An attacker will be able to gain access to any resources that are
allowed by the extra privileges. Common results include executing code,
disabling services, and reading restricted data.
FTP client program on a certain OS runs with
setuid privileges and has a buffer overflow. Most clients do not need extra
privileges, so an overflow is not a vulnerability for those clients.
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.
Installation script installs some programs as
setuid when they shouldn't be.
Potential Mitigations
Phase
Description
Architecture and Design
Identify the functionality that requires additional privileges, such
as access to privileged operating system resources. Wrap and centralize
this functionality if possible, and isolate the privileged code as much
as possible from other code. Raise your privileges as late as possible,
and drop them as soon as possible. Avoid weaknesses such as CWE-288 and
CWE-420 by protecting all possible communication channels that could
interact with your privileged code, such as a secondary socket that you
only intend to be accessed by administrators.
Implementation
Perform extensive input validation for any privileged code that must
be exposed to the user and reject anything that does not fit your strict
requirements.
Implementation
Ensure that you drop privileges as soon as possible (CWE-271), and
make sure that you check to ensure that privileges have been dropped
successfully (CWE-273).
Implementation
If circumstances force you to run with extra privileges, then
determine the minimum access level necessary. First identify the
different permissions that the software and its users will need to
perform their actions, such as file read and write permissions, network
socket permissions, and so forth. Then explicitly allow those actions
while denying all else. Perform extensive input validation and
canonicalization to minimize the chances of introducing a separate
vulnerability. This mitigation is much more prone to error than dropping
the privileges in the first place.
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.
Testing
Use monitoring tools that examine the software's process as it
interacts with the operating system and the network. This technique is
useful in cases when source code is unavailable, if the software was not
developed by you, or if you want to verify that the build phase did not
introduce any new weaknesses. Examples include debuggers that directly
attach to the running process; system-call tracing utilities such as
truss (Solaris) and strace (Linux); system activity monitors such as
FileMon, RegMon, Process Monitor, and other Sysinternals utilities
(Windows); and sniffers and protocol analyzers that monitor network
traffic.
Attach the monitor to the process and perform a login. Look for
library functions and system calls that indicate when privileges are
being raised or dropped. Look for accesses of resources that are
restricted to normal users.
Note that this technique is only useful for privilege issues related
to system resources. It is not likely to detect application-level
business rules that are related to privileges, such as if a blog system
allows a user to delete a blog entry without first checking that the
user has administrator privileges.
Testing
System Configuration
Ensure that your software runs properly under the Federal Desktop Core
Configuration (FDCC) or an equivalent hardening configuration guide,
which many organizations use to limit the attack surface and potential
risk of deployed software.
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
Relationship Notes
There is a close association with CWE-653 (Insufficient Separation of
Privileges). CWE-653 is about providing separate components for each
privilege; CWE-250 is about ensuring that each component has the least
amount of privileges possible.
CWE-271, CWE-272, and CWE-250 are all closely related and possibly
overlapping. CWE-271 is probably better suited as a category. Both CWE-272
and CWE-250 are in active use by the community. The "least privilege" phrase
has multiple interpretations.
Content History
Submissions
Submission Date
Submitter
Organization
Source
7 Pernicious Kingdoms
Externally Mined
Modifications
Modification Date
Modifier
Organization
Source
2008-09-08
CWE Content Team
MITRE
Internal
updated Description, Modes of Introduction, Relationships,
Other Notes, Relationship Notes, Taxonomy Mappings
2008-10-14
CWE Content Team
MITRE
Internal
updated Description,
Maintenance Notes
2009-01-12
CWE Content Team
MITRE
Internal
updated Common Consequences, Description,
Likelihood of Exploit, Maintenance Notes, Name, Observed Examples,
Other Notes, Potential Mitigations, Relationships,
Time of Introduction
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.
External Control of System or Configuration Setting
Definition in a New Window
Weakness ID: 15 (Weakness Base)
Status: Incomplete
Description
Description Summary
One or more system settings or configuration elements can be
externally controlled by a user.
Extended Description
Allowing external control of system settings can disrupt service or cause
an application to behave in unexpected, and potentially malicious
ways.
Time of Introduction
Implementation
Modes of Introduction
Setting manipulation vulnerabilities occur when an attacker can control
values that govern the behavior of the system, manage specific resources, or
in some way affect the functionality of the application.
Demonstrative Examples
Example 1
The following C code accepts a number as one of its command line
parameters and sets it as the host ID of the current machine.
(Bad Code)
C
...
sethostid(argv[1]);
...
Although a process must be privileged to successfully invoke
sethostid(), unprivileged users may be able to invoke the program. The
code in this example allows user input to directly control the value of
a system setting. If an attacker provides a malicious value for host ID,
the attacker can misidentify the affected machine on the network or
cause other unintended behavior.
Example 2
The following Java code snippet reads a string from an
HttpServletRequest and sets it as the active catalog for a database
Connection.
(Bad Code)
Java
...
conn.setCatalog(request.getParameter("catalog"));
...
In this example, an attacker could cause an error by providing a
nonexistent catalog name or connect to an unauthorized portion of the
database.
Potential Mitigations
Phase
Description
Compartmentalize your system and determine where the trust boundaries
exist. Any input/control outside the trust boundary should be treated as
potentially hostile.
Because setting manipulation covers a diverse set of functions, any
attempt at illustrating it will inevitably be incomplete. Rather than
searching for a tight-knit relationship between the functions addressed
in the setting manipulation category, take a step back and consider the
sorts of system values that an attacker should not be allowed to
control.
In general, do not allow user-provided or otherwise untrusted data to
control sensitive values. The leverage that an attacker gains by
controlling these values is not always immediately obvious, but do not
underestimate the creativity of your attacker.
Failure to Change Working Directory in chroot Jail
Definition in a New Window
Weakness ID: 243 (Weakness Variant)
Status: Draft
Description
Description Summary
The program uses the chroot() system call to create a jail, but
does not change the working directory afterward. This does not prevent access to
files outside of the jail.
Extended Description
Improper use of chroot() may allow attackers to escape from the chroot
jail. The chroot() function call does not change the process's current
working directory, so relative paths may still refer to file system
resources outside of the chroot jail after chroot() has been called.
Time of Introduction
Implementation
Applicable Platforms
Languages
C
C++
Operating Systems
UNIX
Likelihood of Exploit
High
Demonstrative Examples
Example 1
Consider the following source code from a (hypothetical) FTP
server:
(Bad Code)
C
chroot("/var/ftproot");
...
fgets(filename, sizeof(filename), network);
localfile = fopen(filename, "r");
while ((len = fread(buf, 1, sizeof(buf), localfile)) != EOF)
{
fwrite(buf, 1, sizeof(buf), network);
}
fclose(localfile);
This code is responsible for reading a filename from the network,
opening the corresponding file on the local machine, and sending the
contents over the network. This code could be used to implement the FTP
GET command. The FTP server calls chroot() in its initialization
routines in an attempt to prevent access to files outside of
/var/ftproot. But because the server fails to change the current working
directory by calling chdir("/"), an attacker could request the file
"../../../../../etc/passwd" and obtain a copy of the system password
file.
Background Details
The chroot() system call allows a process to change its perception of the
root directory of the file system. After properly invoking chroot(), a
process cannot access any files outside the directory tree defined by the
new root directory. Such an environment is called a chroot jail and is
commonly used to prevent the possibility that a processes could be subverted
and used to access unauthorized files. For instance, many FTP servers run in
chroot jails to prevent an attacker who discovers a new vulnerability in the
server from being able to download the password file or other sensitive
files on the system.
Weakness Ordinalities
Ordinality
Description
Resultant
(where the
weakness is typically related to the presence of some other
weaknesses)
Failure to Clear Heap Memory Before Release ('Heap Inspection')
Definition in a New Window
Weakness ID: 244 (Weakness Variant)
Status: Draft
Description
Description Summary
Using realloc() to resize buffers that store sensitive
information can leave the sensitive information exposed to attack, because it is
not removed from memory.
Extended Description
When sensitive data such as a password or an encryption key is not removed
from memory, it could be exposed to an attacker using a "heap inspection"
attack that reads the sensitive data using memory dumps or other methods.
The realloc() function is commonly used to increase the size of a block of
allocated memory. This operation often requires copying the contents of the
old memory block into a new and larger block. This operation leaves the
contents of the original block intact but inaccessible to the program,
preventing the program from being able to scrub sensitive data from memory.
If an attacker can later examine the contents of a memory dump, the
sensitive data could be exposed.
Time of Introduction
Implementation
Applicable Platforms
Languages
C
C++
Common Consequences
Scope
Effect
Confidentiality
Be careful using vfork() and fork() in security sensitive code. The
process state will not be cleaned up and will contain traces of data
from past use.
Demonstrative Examples
Example 1
The following code calls realloc() on a buffer containing sensitive
data:
There is an attempt to scrub the sensitive data from memory, but
realloc() is used, so a copy of the data can still be exposed in the
memory originally allocated for cleartext_buffer.
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 software uses an API in a manner contrary to its intended
use.
Extended Description
An API is a contract between a caller and a callee. The most common forms
of API misuse are caused by the caller failing to honor its end of this
contract. For example, if a program fails to call chdir() after calling
chroot(), it violates the contract that specifies how to change the active
root directory in a secure fashion. Another good example of library abuse is
expecting the callee to return trustworthy DNS information to the caller. In
this case, the caller misuses the callee API by making certain assumptions
about its behavior (that the return value can be used for authentication
purposes). One can also violate the caller-callee contract from the other
side. For example, if a coder subclasses SecureRandom and returns a
non-random value, the contract is violated.
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.
The code in this example operates correctly if the Employee ID
variable contains only standard alphanumeric text. If it has a value
that includes meta-characters or source code, then the code will be
executed by the web browser as it displays the HTTP response. Initially
this might not appear to be much of a vulnerability. After all, why
would someone enter a URL that causes malicious code to run on their own
computer? The real danger is that an attacker will create the malicious
URL, then use e-mail or social engineering tricks to lure victims into
visiting a link to the URL. When victims click the link, they
unwittingly reflect the malicious content through the vulnerable web
application back to their own computers. This mechanism of exploiting
vulnerable web applications is known as Reflected XSS.
Example 2
This example covers a Stored XSS (Type 2) scenario.
The following JSP code segment queries a database for an employee with
a given ID and prints the corresponding employee's name.
(Bad Code)
JSP
<%
...
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp where
id="+eid);
if (rs != null) {
rs.next();
String name = rs.getString("name");
%>
Employee Name: <%= name %>
The following ASP.NET code segment queries a database for an employee
with a given employee ID and prints the name corresponding with the
ID.
string query = "select * from emp where id=" + eid;
sda = new SqlDataAdapter(query, conn);
sda.Fill(dt);
string name = dt.Rows[0]["Name"];
...
EmployeeName.Text = name;
This code functions correctly when the values of name are
well-behaved, but it does nothing to prevent exploits if they are not.
This code can appear less dangerous because the value of name is read
from a database, whose contents are apparently managed by the
application. However, if the value of name originates from user-supplied
data, then the database can be a conduit for malicious content. Without
proper input validation on all data stored in the database, an attacker
can execute malicious commands in the user's web browser. This type of
exploit, known as Stored XSS, is particularly insidious because the
indirection caused by the data store makes it more difficult to identify
the threat and increases the possibility that the attack will affect
multiple users.
XSS got its start in this form with web sites that offered a
"guestbook" to visitors. Attackers would include JavaScript in their
guestbook entries, and all subsequent visitors to the guestbook page
would execute the malicious code. As the examples demonstrate, XSS
vulnerabilities are caused by code that includes unvalidated data in an
HTTP response. To summarize the basic points of Stored XSS:
A source outside the application stores dangerous data in a
database or other data store
The dangerous data is subsequently read back into the application
as trusted data
Use languages, libraries, or frameworks that make it easier to
generate properly encoded output.
Examples include Microsoft's Anti-XSS library, the OWASP ESAPI
Encoding module, and Apache Wicket.
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
Architecture and Design
Understand the context in which your data will be used and the
encoding that will be expected. This is especially important when
transmitting data between different components, or when generating
outputs that can contain multiple encodings at the same time, such as
web pages or multi-part mail messages. Study all expected communication
protocols and data representations to determine the required encoding
strategies.
For any data that will be output to another web page, especially any
data that was received from external inputs, use the appropriate
encoding on all non-alphanumeric characters. This encoding will vary
depending on whether the output is part of the HTML body, element
attributes, URIs, JavaScript sections, Cascading Style Sheets, etc. Note
that HTML Entity Encoding is only appropriate for the HTML body.
Implementation
Use and specify a strong character encoding such as ISO-8859-1 or
UTF-8. When an encoding is not specified, the web browser may choose a
different encoding by guessing which encoding is actually being used by
the web page. This can open you up to subtle XSS attacks related to that
encoding. See CWE-116 for more mitigations related to
encoding/escaping.
Implementation
With Struts, you should write all data from form beans with the bean's
filter attribute set to true.
Implementation
To help mitigate XSS attacks against the user's session cookie, set
the session cookie to be HttpOnly. In browsers that support the HttpOnly
feature (such as more recent versions of Internet Explorer and Firefox),
this attribute can prevent the user's session cookie from being
accessible to malicious client-side scripts that use document.cookie.
This is not a complete solution, since HttpOnly is not supported by all
browsers. More importantly, XMLHTTPRequest and other powerful browser
technologies provide read access to HTTP headers, including the
Set-Cookie header in which the HttpOnly flag is set.
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.
Use a standard input validation mechanism to validate all input for
length, type, syntax, and business rules before accepting the input for
further processing. 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."
When dynamically constructing web pages, use stringent whitelists that
limit the character set based on the expected value of the parameter in
the request. All input should be validated and cleansed, not just
parameters that the user is supposed to specify, but all data in the
request, including hidden fields, cookies, headers, the URL itself, and
so forth. A common mistake that leads to continuing XSS vulnerabilities
is to validate only fields that are expected to be redisplayed by the
site. It is common to see data from the request that is reflected by the
application server or the application that the development team did not
anticipate. Also, a field that is not currently reflected may be used by
a future developer. Therefore, validating ALL parts of the HTTP request
is recommended.
Note that proper output encoding, escaping, and quoting is the most
effective solution for preventing XSS, although input validation may
provide some defense-in-depth. This is because it effectively limits
what will appear in output. Input validation will not always prevent
XSS, especially if you are required to support free-form text fields
that could contain arbitrary characters. For example, in a chat
application, the heart emoticon ("<3") would likely pass the
validation step, since it is commonly used. However, it cannot be
directly inserted into the web page because it contains the "<"
character, which would need to be escaped or otherwise handled. In this
case, stripping the "<" might reduce the risk of XSS, but it
would produce incorrect behavior because the emoticon would not be
recorded. This might seem to be a minor inconvenience, but it would be
more important in a mathematical forum that wants to represent
inequalities.
Even if you make a mistake in your validation (such as forgetting one
out of 100 input fields), appropriate encoding is still likely to
protect you from injection-based attacks. As long as it is not done in
isolation, input validation is still a useful technique, since it may
significantly reduce your attack surface, allow you to detect some
attacks, and provide other security benefits that proper encoding does
not address.
Ensure that you perform input validation at well-defined interfaces
within the application. This will help protect the application even if a
component is reused or moved elsewhere.
Testing
Implementation
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 the XSS Cheat Sheet (see references) to launch a wide variety of
attacks against your web application. The Cheat Sheet contains many
subtle XSS variations that are specifically targeted against weak XSS
defenses.
Operation
Use an application firewall that can detect attacks against this
weakness. This might not catch all attacks, and it might require some
effort for customization. However, it can be beneficial in cases in
which the code cannot be fixed (because it is controlled by a third
party), as an emergency prevention measure while more comprehensive
software assurance measures are applied, or to provide defense in
depth.
Background Details
Same Origin Policy
The same origin policy states that browsers should limit the resources
accessible to scripts running on a given web site , or "origin", to the
resources associated with that web site on the client-side, and not the
client-side resources of any other sites or "origins". The goal is to
prevent one site from being able to modify or read the contents of an
unrelated site. Since the World Wide Web involves interactions between many
sites, this policy is important for browsers to enforce.
Domain
The Domain of a website when referring to XSS is roughly equivalent to the
resources associated with that website on the client-side of the connection.
That is, the domain can be thought of as all resources the browser is
storing for the user's interactions with this particular site.
Weakness Ordinalities
Ordinality
Description
Resultant
(where the
weakness is typically related to the presence of some other
weaknesses)