CWE nodes in this view (graph) are associated with the OWASP Top Ten, as
released in 2007.
View Metrics
CWEs in this view
Total CWEs
Total
38
out of
791
Views
0
out of
22
Categories
10
out of
106
Weaknesses
25
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 (2007 version), providing a good starting point for web
application developers who want to code more securely.
Software Customers
This view outlines the most important issues as identified by the
OWASP Top Ten (2007 version), providing customers with a way of asking
their software developers to follow minimum expectations for secure
code.
Educators
Since the OWASP Top Ten covers the most frequently encountered issues,
this view can be used by educators as training material for
students.
The relationships in this view are a direct extraction of the CWE mappings
that are in the 2007 OWASP document. CWE has changed since the release of
that document.
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.
Authentication Bypass Using an Alternate Path or Channel
Definition in a New Window
Weakness ID: 288 (Weakness Base)
Status: Incomplete
Description
Description Summary
A product requires authentication, but the product has an
alternate path or channel that does not require authentication.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Modes of Introduction
This is often seen in web applications that assume that access to a
particular CGI program can only be obtained through a "front" screen, when
the supporting programs are directly accessible. But this problem is not
just in web apps.
User can avoid lockouts by using an API instead of
the GUI to conduct brute force password
guessing.
Potential Mitigations
Phase
Description
Funnel all access through a single choke point to simplify how users
can access a resource. For every access, perform a check to determine if
the user has permissions to access the resource.
Compound Element ID: 352 (Compound Element Variant: Composite)
Status: Draft
Description
Description Summary
The web application does not, or can not, sufficiently verify
whether a well-formed, valid, consistent request was intentionally provided by
the user who submitted the request.
Extended Description
When a web server is designed to receive a request from a client without
any mechanism for verifying that it was intentionally sent, then it might be
possible for an attacker to trick a client into making an unintentional
request to the web server which will be treated as an authentic request.
This can be done via a URL, image load, XMLHttpRequest, etc. and can result
in data disclosure or unintended code execution.
Alternate Terms
Session Riding
Cross Site Reference Forgery
XSRF
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Technology Classes
Web-Server
Likelihood of Exploit
High
Demonstrative Examples
Example 1
This example PHP code attempts to secure the form submission process
by validating that the user submitting the form has a valid session. A CSRF
attack would not be prevented by this countermeasure because the attacker
forges a request through the user's web browser in which a valid session
already exists.
The following HTML is intended to allow a user to update a
profile.
echo "Your profile has been successfully updated.";
}
This code may look protected since it checks for a valid session.
However, CSRF attacks can be staged from virtually any tag or HTML
construct, including image tags, links, embed or object tags, or other
attributes that load background images.
The attacker can then host code that will silently change the username
and email address of any user that visits the page while remaining
logged in to the target web application. The code might be an
innocent-looking web page such as:
Notice how the form contains hidden fields, so when it is loaded into
the browser, the user will not notice it. Because SendAttack() is
defined in the body's onload attribute, it will be automatically called
when the victim loads the web page.
Assuming that the user is already logged in to victim.example.com,
profile.php will see that a valid user session has been established,
then update the email address to the attacker's own address. At this
stage, the user's identity has been compromised, and messages sent
through this profile could be sent to the attacker's address.
Perform actions as administrator via a URL or an
img tag
Potential Mitigations
Phase
Description
Architecture and Design
Use anti-CSRF packages such as the OWASP CSRFGuard.
Implementation
Ensure that your application is free of cross-site scripting issues
(CWE-79), because most CSRF defenses can be bypassed using
attacker-controlled script.
Architecture and Design
Generate a unique nonce for each form, place the nonce into the form,
and verify the nonce upon receipt of the form. Be sure that the nonce is
not predictable (CWE-330).
Note that this can be bypassed using XSS (CWE-79).
Architecture and Design
Identify especially dangerous operations. When the user performs a
dangerous operation, send a separate confirmation request to ensure that
the user intended to perform that operation.
Note that this can be bypassed using XSS (CWE-79).
Architecture and Design
Use the "double-submitted cookie" method as described by Felten and
Zeller.
Note that this can probably be bypassed using XSS (CWE-79).
Architecture and Design
Use the ESAPI Session Management control.
This control includes a component for CSRF.
Architecture and Design
Do not use the GET method for any request that triggers a state
change.
Implementation
Check the HTTP Referer header to see if the request originated from an
expected page. This could break legitimate functionality, because users
or proxies may have disabled sending the Referer for privacy
reasons.
Note that this can be bypassed using XSS (CWE-79). An attacker could
use XSS to generate a spoofed Referer, or to generate a malicious
request from a page whose Referer would be allowed.
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.
Use OWASP CSRFTester to identify potential issues.
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.
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 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.
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)
Failure to Sanitize CRLF Sequences ('CRLF Injection')
Definition in a New Window
Weakness ID: 93 (Weakness Base)
Status: Draft
Description
Description Summary
The software uses CRLF (carriage return line feeds) as a
special element, e.g. to separate lines or records, but it does not properly
sanitize CRLF sequences from inputs.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Demonstrative Examples
Example 1
If user input data that eventually makes it to a log message isn't
checked for CRLF characters, it may be possible for an attacker to forge
entries in a log file.
(Bad Code)
Java
logger.info("User's street address: " +
request.getParameter("streetAddress"));
Failure to Sanitize Data into LDAP Queries ('LDAP Injection')
Definition in a New Window
Weakness ID: 90 (Weakness Base)
Status: Draft
Description
Description Summary
The software does not sufficiently sanitize special elements
that are used in LDAP queries or responses, allowing attackers to modify the
syntax, contents, or commands of the LDAP query before it is
executed.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Technology Classes
Database-Server
Demonstrative Examples
Example 1
In the code excerpt below, user input data (address) isn't properly
sanitized before it's used to construct an LDAP query.
Assume all input is malicious. Use an appropriate combination of black
lists and white lists to filter or quote LDAP syntax from
user-controlled input.
Factors: resultant to special character mismanagement, MAID, or
blacklist/whitelist problems. Can be primary to authentication and
verification errors.
Research Gaps
Under-reported. This is likely found very frequently by third party code
auditors, but there are very few publicly reported examples.
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
PLOVER
LDAP injection
OWASP Top Ten 2007
A2
CWE More Specific
Injection Flaws
References
SPI Dynamics. "Web Applications and LDAP Injection".
Content History
Submissions
Submission Date
Submitter
Organization
Source
PLOVER
Externally Mined
Modifications
Modification Date
Modifier
Organization
Source
2008-07-01
Sean Eidemiller
Cigital
External
added/updated demonstrative
examples
2008-07-01
Eric Dalci
Cigital
External
updated Time of Introduction
2008-09-08
CWE Content Team
MITRE
Internal
updated Applicable Platforms, Relationships, Other Notes,
Taxonomy Mappings
The software does not perform or incorrectly performs access
control checks across all potential execution paths.
Extended Description
When access control checks are not applied consistently - or not at all -
users are able to access data or perform actions that they should not be
allowed to perform. This can lead to a wide range of problems, including
information leaks, denial of service, and arbitrary code execution.
Time of Introduction
Architecture and Design
Implementation
Operation
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Availability
Confidentiality
Integrity
Allowing access to unauthorized users can result in an attacker
gaining access to the sensitive resources being protected, possibly
modifying or removing them, or performing unauthorized actions.
Likelihood of Exploit
High
Potential Mitigations
Phase
Description
Architecture and Design
Divide your application into anonymous, normal, privileged, and
administrative areas. Reduce the attack surface by carefully mapping
roles with data and functionality. Use role-based access control (RBAC)
to enforce the roles at the appropriate boundaries.
Note that this approach may not protect against horizontal
authorization, i.e., it will not protect a user from attacking others
with the same role.
Architecture and Design
Ensure that you perform access control checks related to your business
logic. These may be different than the access control checks that you
apply to the resources that support your business logic.
Architecture and Design
Use authorization frameworks such as the JAAS Authorization Framework
and the OWASP ESAPI Access Control feature.
Architecture and Design
For web applications, make sure that the access control mechanism is
enforced correctly at the server side on every page. Users should not be
able to access any unauthorized functionality or information by simply
requesting direct access to that page.
One way to do this is to ensure that all pages containing sensitive
information are not cached, and that all such pages restrict access to
requests that are accompanied by an active and authenticated session
token associated with a user who has the required permissions to access
that page.
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.
System Configuration
Installation
Use the access control capabilities of your operating system and
server environment and define your access control lists accordingly. Use
a "default deny" policy when defining these ACLs.
Improper Control of Filename for Include/Require Statement in PHP Program ('PHP File Inclusion')
Definition in a New Window
Compound Element ID: 98 (Compound Element Base: Composite)
Status: Draft
Description
Description Summary
The PHP application receives input from an upstream component,
but it does not restrict or incorrectly restricts the input before its usage in
"require," "include," or similar functions.
Extended Description
In certain versions and configurations of PHP, this can allow an attacker
to specify a URL to a remote location from which the software will obtain
the code to execute. In other cases in association with path traversal, the
attacker can specify a local file that may contain executable statements
that can be parsed by PHP.
PHP file inclusion issue, both remote and local;
local include uses ".." and "%00" characters as a manipulation, but many
remote file inclusion issues probably have this
vector.
Potential Mitigations
Phase
Description
Assume all input is malicious. Use an appropriate combination of black
lists and white lists to ensure only valid and expected input is
processed by the system.
This is frequently a functional consequence of other weaknesses. It is
usually multi-factor with other factors (e.g. MAID), although not all
inclusion bugs involve assumed-immutable data. Direct request weaknesses
frequently play a role.
Can overlap directory traversal in local inclusion problems.
Research Gaps
Under-researched and under-reported. Other interpreted languages with
"require" and "include" functionality could also product vulnerable
applications, but as of 2007, PHP has been the focus. Any web-accessible
language that uses executable file extensions is likely to have this type of
issue, such as ASP, since .asp extensions are typically executable.
Languages such as Perl are less likely to exhibit these problems because the
.pl extension isn't always configured to be executable by the web
server.
Improper Sanitization of Directives in Dynamically Evaluated Code ('Eval Injection')
Definition in a New Window
Weakness ID: 95 (Weakness Base)
Status: Incomplete
Description
Description Summary
The software receives input from an upstream component, but it
does not sanitize or incorrectly sanitizes code syntax before using the input in
a dynamic evaluation call (e.g. "eval").
Extended Description
This may allow an attacker to execute arbitrary code, or at least modify
what code can be executed.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
Java
Javascript
Python
Perl
PHP
Ruby
Interpreted Languages
Modes of Introduction
This weakness is prevalent in handler/dispatch procedures that might want
to invoke a large number of functions, or set a large number of
variables.
Likelihood of Exploit
Medium
Demonstrative Examples
Example 1
edit-config.pl: This CGI script is used to modify settings in a
configuration file.
(Bad Code)
Perl
use CGI qw(:standard);
sub config_file_add_key {
my ($fname, $key, $arg) = @_;
# code to add a field/key to a file goes here
}
sub config_file_set_key {
my ($fname, $key, $arg) = @_;
# code to set key to a particular file goes here
}
sub config_file_delete_key {
my ($fname, $key, $arg) = @_;
# code to delete key from a particular file goes here
}
sub handleConfigAction {
my ($fname, $action) = @_;
my $key = param('key');
my $val = param('val');
# this is super-efficient code, especially if you have to
invoke
# any one of dozens of different functions!
my $code = "config_file_$action_key(\$fname, \$key,
\$val);";
eval($code);
}
$configfile = "/home/cwe/config.txt";
print header;
if (defined(param('action'))) {
handleConfigAction($configfile, param('action'));
}
else {
print "No action specified!\n";
}
The script intends to take the 'action' parameter and invoke one of a
variety of functions based on the value of that parameter -
config_file_add_key(), config_file_set_key(), or
config_file_delete_key(). It could set up a conditional to invoke each
function separately, but eval() is a powerful way of doing the same
thing in fewer lines of code, especially when a large number of
functions or variables are involved. Unfortunately, in this case, the
attacker can provide other values in the action parameter, such as:
add_key(",","); system("/bin/ls"); This would produce the following
string in handleConfigAction(): config_file_add_key(",",");
system("/bin/ls"); Any arbitrary Perl code could be added after the
attacker has "closed off" the construction of the original function
call, in order to prevent parsing errors from causing the malicious
eval() to fail before the attacker's payload is activated. This
particular manipulation would fail after the system() call, because the
"_key(\$fname, \$key, \$val)" portion of the string would cause an
error, but this is irrelevant to the attack because the payload has
already been activated.
chain: Resultant eval injection. An invalid value
prevents initialization of variables, which can be modified by attacker and
later injected into PHP eval statement.
Potential Mitigations
Phase
Description
Refactor your code so that it does not need to use eval() at
all.
Assume all input is malicious. Use an appropriate combination of black
lists and white lists to ensure only valid and expected input is
processed by the system.
Other Notes
Factors: special character errors can play a role in increasing the
variety of code that can be injected, although some vulnerabilities do not
require special characters at all, e.g. when a single function without
arguments can be referenced and a terminator character is not
necessary.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)
This issue is probably under-reported. Most relevant CVEs have been for
Perl and PHP, but eval injection applies to most interpreted languages.
Javascript eval injection is likely to be heavily under-reported.
Improper Sanitization of Special Elements used in a Command ('Command Injection')
Definition in a New Window
Weakness ID: 77 (Weakness Class)
Status: Draft
Description
Description Summary
The software constructs all or part of a command using
externally-influenced input from an upstream component, but it does not sanitize
or incorrectly sanitizes special elements that could modify the intended command
when it is sent to a downstream component.
Extended Description
Command injection vulnerabilities typically occur when:
1. Data enters the application from an untrusted source.
2. The data is part of a string that is executed as a command by the
application.
3. By executing the command, the application gives an attacker a
privilege or capability that the attacker would not otherwise
have.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Access Control
Command injection allows for the execution of arbitrary commands and
code by the attacker.
Integrity
If a malicious user injects a character (such as a semi-colon) that
delimits the end of one command and the beginning of another, it may be
possible to then insert an entirely new and unrelated command that was
not intended to be executed.
Likelihood of Exploit
Very High
Demonstrative Examples
Example 1
The following simple program accepts a filename as a command line
argument and displays the contents of the file back to the user. The program
is installed setuid root because it is intended for use as a learning tool
to allow system administrators in-training to inspect privileged system
files without giving them the ability to modify them or damage the
system.
C
int main(char* argc, char** argv) {
char cmd[CMD_MAX] = "/usr/bin/cat ";
strcat(cmd, argv[1]);
system(cmd);
}
Because the program runs with root privileges, the call to system()
also executes with root privileges. If a user specifies a standard
filename, the call works as expected. However, if an attacker passes a
string of the form ";rm -rf /", then the call to system() fails to
execute cat due to a lack of arguments and then plows on to recursively
delete the contents of the root partition.
Example 2
The following code is from an administrative web application
designed to allow users to kick off a backup of an Oracle database using a
batch-file wrapper around the rman utility and then run a cleanup.bat script
to delete some temporary files. The script rmanDB.bat accepts a single
command line parameter, which specifies what type of backup to perform.
Because access to the database is restricted, the application runs the
backup as a privileged user.
The problem here is that the program does not do any validation on the
backuptype parameter read from the user. Typically the Runtime.exec()
function will not execute multiple commands, but in this case the
program first runs the cmd.exe shell in order to run multiple commands
with a single call to Runtime.exec(). Once the shell is invoked, it will
happily execute multiple commands separated by two ampersands. If an
attacker passes a string of the form "& del c:\\dbms\\*.*", then
the application will execute this command along with the others
specified by the program. Because of the nature of the application, it
runs with the privileges necessary to interact with the database, which
means whatever command the attacker injects will run with those
privileges as well.
Example 3
The following code from a system utility uses the system property
APPHOME to determine the directory in which it is installed and then
executes an initialization script based on a relative path from the
specified directory.
(Bad Code)
Java
...
String home = System.getProperty("APPHOME");
String cmd = home + INITCMD;
java.lang.Runtime.getRuntime().exec(cmd);
...
The code above allows an attacker to execute arbitrary commands with
the elevated privilege of the application by modifying the system
property APPHOME to point to a different path containing a malicious
version of INITCMD. Because the program does not validate the value read
from the environment, if an attacker can control the value of the system
property APPHOME, then they can fool the application into running
malicious code and take control of the system.
Example 4
The following code is from a web application that allows users
access to an interface through which they can update their password on the
system. Part of the process for updating passwords in certain network
environments is to run a make command in the /var/yp directory, the code for
which is shown below.
(Bad Code)
Java
...
System.Runtime.getRuntime().exec("make");
...
The problem here is that the program does not specify an absolute path
for make and fails to clean its environment prior to executing the call
to Runtime.exec(). If an attacker can modify the $PATH variable to point
to a malicious binary called make and cause the program to be executed
in their environment, then the malicious binary will be loaded instead
of the one intended. Because of the nature of the application, it runs
with the privileges necessary to perform system operations, which means
the attacker's make will now be run with these privileges, possibly
giving the attacker complete control of the system.
Example 5
The following code is a wrapper around the UNIX command cat which
prints the contents of a file to standard out. It is also
injectable:
Used normally, the output is simply the contents of the file
requested:
$ ./catWrapper Story.txt
When last we left our heroes...
However, if we add a semicolon and another command to the end of this
line, the command is executed by catWrapper with no complaint:
(Attack)
$ ./catWrapper Story.txt; ls
When last we left our heroes...
Story.txt
SensitiveFile.txt
PrivateData.db
a.out*
If catWrapper had been set to have a higher privilege level than the
standard user, arbitrary commands could be executed with that higher
privilege.
Potential Mitigations
Phase
Description
Architecture and Design
If at all possible, use library calls rather than external processes
to recreate the desired functionality
Implementation
If possible, ensure that all external commands called from the program
are statically created.
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.
Run time: Run time policy enforcement may be used in a white-list
fashion to prevent use of any non-sanctioned commands.
Assign permissions to the software system that prevents the user from
accessing/opening privileged files.
Other Notes
Command injection is a common problem with wrapper programs.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)
Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')
Definition in a New Window
Weakness ID: 78 (Weakness Base)
Status: Draft
Description
Description Summary
The software constructs all or part of an OS command using
externally-influenced input from an upstream component, but it does not sanitize
or incorrectly sanitizes special elements that could modify the intended OS
command when it is sent to a downstream component.
Extended Description
This could allow attackers to execute unexpected, dangerous commands
directly on the operating system. This weakness can lead to a vulnerability
in environments in which the attacker does not have direct access to the
operating system, such as in web applications. Alternately, if the weakness
occurs in a privileged program, it could allow the attacker to specify
commands that normally would not be accessible, or to call alternate
commands with privileges that the attacker does not have. The problem is
exacerbated if the compromised process fails to follow the principle of
least privilege, because the attacker-controlled commands may run with
special system privileges that increases the amount of damage.
There are at least two subtypes of OS command injection:
1) The application intends to execute a single, fixed program that is
under its own control. It intends to use externally-supplied inputs as
arguments to that program. For example, the program might use
system("nslookup [HOSTNAME]") to run nslookup and allow the user to
supply a HOSTNAME, which is used as an argument. Attackers cannot
prevent nslookup from executing. However, if the program does not remove
command separators from the HOSTNAME argument, attackers could place the
separators into the arguments, which allows them to execute their own
program after nslookup has finished executing.
2) The application accepts an input that it uses to fully select which
program to run, as well as which commands to use. The application simply
redirects this entire command to the operating system. For example, the
program might use "exec([COMMAND])" to execute the [COMMAND] that was
supplied by the user. If the COMMAND is under attacker control, then the
attacker can execute arbitrary commands or programs. If the command is
being executed using functions like exec() and CreateProcess(), the
attacker might not be able to combine multiple commands together in the
same line.
From a weakness standpoint, these variants represent distinct programmer
errors. In the first variant, the programmer clearly intends that input from
untrusted parties will be part of the arguments in the command to be
executed. In the second variant, the programmer does not intend for the
command to be accessible to any untrusted party, but the programmer probably
has not accounted for alternate ways in which malicious attackers can
provide input.
Alternate Terms
Shell injection
Shell metacharacters
Terminology Notes
The "OS command injection" phrase carries different meanings to different
people. For some, it refers to any type of attack that can allow the
attacker to execute OS commands of his or her choosing. This usage could
include untrusted search path weaknesses (CWE-426) that cause the
application to find and execute an attacker-controlled program. For others,
it only refers to the first variant, in which the attacker injects command
separators into arguments for an application-controlled program that is
being invoked. Further complicating the issue is the case when argument
injection (CWE-88) allows alternate command-line switches or options to be
inserted into the command line, such as an "-exec" switch whose purpose may
be to execute the subsequent argument as a command (this -exec switch exists
in the UNIX "find" command, for example). In this latter case, however,
CWE-88 could be regarded as the primary weakness in a chain with
CWE-78.
Time of Introduction
Architecture and Design
Implementation
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Confidentiality
Integrity
Availability
Non-Repudiation
Attackers could execute unauthorized commands, which could then be
used to disable the software, or read and modify data for which the
attacker does not have permissions to access directly. Since the
targeted application is directly executing the commands instead of the
attacker, any malicious activities may appear to come from the
application or the application's owner.
Likelihood of Exploit
High
Demonstrative Examples
Example 1
This example is a web application that intends to perform a DNS
lookup of a user-supplied domain name. It is subject to the first variant of
OS command injection.
(Bad Code)
Perl
use CGI qw(:standard);
$name = param('name');
$nslookup = "/path/to/nslookup";
print header;
if (open($fh, "$nslookup $name|")) {
while (<$fh>) {
print escapeHTML($_);
print "<br>\n";
}
close($fh);
}
Suppose an attacker provides a domain name like this:
(Attack)
cwe.mitre.org%20%3B%20/bin/ls%20-l
The "%3B" sequence decodes to the ";" character, and the %20 decodes
to a space. The open() statement would then process a string like
this:
/path/to/nslookup cwe.mitre.org ; /bin/ls -l
As a result, the attacker executes the "/bin/ls -l" command and gets a
list of all the files in the program's working directory. The input
could be replaced with much more dangerous commands, such as installing
a malicious program on the server.
Example 2
The example below reads the name of a shell script to execute from
the system properties. It is subject to the second variant of OS command
injection.
(Bad Code)
Java
String script = System.getProperty("SCRIPTNAME");
if (script != null)
System.exec(script);
If an attacker has control over this property, then he or she could
modify the property to point to a dangerous program.
Language interpreter's mail function accepts
another argument that is concatenated to a string used in a dangerous
popen() call. Since there is no sanitization against this argument, both OS
Command Injection (CWE-78) and Argument Injection (CWE-88) are
possible.
Chain: incomplete blacklist for OS command
injection
Potential Mitigations
Phase
Description
Architecture and Design
If at all possible, use library calls rather than external processes
to recreate the desired functionality.
Architecture and Design
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 which commands can be executed by your
software.
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 data that will be used to generate a command to be executed,
keep as much of that data out of external control as possible. For
example, in web applications, this may require storing the command
locally in the session's state instead of sending it out to the client
in a hidden form field.
Architecture and Design
Use languages, libraries, or frameworks that make it easier to
generate properly encoded output.
Examples include the ESAPI Encoding control.
Implementation
Properly quote arguments and escape any special characters within
those arguments. If some special characters are still needed, wrap the
arguments in quotes, and escape all other characters that do not pass a
strict whitelist. Be careful of argument injection (CWE-88).
Implementation
If the program to be executed allows arguments to be specified within
an input file or from standard input, then consider using that mode to
pass arguments instead of the command line.
Implementation
If available, use structured mechanisms that automatically enforce the
separation between data and code. These mechanisms may be able to
provide the relevant quoting, encoding, and validation automatically,
instead of relying on the developer to provide this capability at every
point where output is generated.
Some languages offer multiple functions that can be used to invoke
commands. Where possible, identify any function that invokes a command
shell using a single string, and replace it with a function that
requires individual arguments. These functions typically perform
appropriate quoting and filtering of arguments. For example, in C, the
system() function accepts a string that contains the entire command to
be executed, whereas execl(), execve(), and others require an array of
strings, one for each argument. In Windows, CreateProcess() only accepts
one command at a time. In Perl, if system() is provided with an array of
arguments, then it will quote each of the arguments.
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 constructing OS command strings, use stringent whitelists that
limit the character set based on the expected value of the parameter in
the request. This will indirectly limit the scope of an attack, but this
technique is less important than proper output encoding and
escaping.
Note that proper output encoding, escaping, and quoting is the most
effective solution for preventing OS command injection, 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 OS command injection, especially if you are required to
support free-form text fields that could contain arbitrary characters.
For example, when invoking a mail program, you might need to allow the
subject field to contain otherwise-dangerous inputs like ";" and
">" characters, which would need to be escaped or otherwise
handled. In this case, stripping the character might reduce the risk of
OS command injection, but it would produce incorrect behavior because
the subject field would not be recorded as the user intended. This might
seem to be a minor inconvenience, but it could be more important when
the program relies on well-structured subject lines in order to pass
messages to other components.
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.
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.
Operation
Run the code in an environment that performs automatic taint
propagation and prevents any command execution that uses tainted
variables, such as Perl's "-T" switch. This will force you to perform
validation steps that remove the taint, although you must be careful to
correctly validate your inputs so that you do not accidentally mark
dangerous inputs as untainted (see CWE-183 and CWE-184).
Operation
Use runtime policy enforcement to create a whitelist of allowable
commands, then prevent use of any command that does not appear in the
whitelist. Technologies such as AppArmor are available to do
this.
System Configuration
Assign permissions to the software system that prevent the user from
accessing/opening privileged files. Run the application with the lowest
privileges possible (CWE-250).
More investigation is needed into the distinction between the OS command
injection variants, including the role with argument injection (CWE-88).
Equivalent distinctions may exist in other injection-related problems such
as SQL injection.
Affected Resources
System Process
Functional Areas
Program invocation
Taxonomy Mappings
Mapped Taxonomy Name
Node ID
Fit
Mapped Node Name
PLOVER
OS Command Injection
OWASP Top Ten 2007
A3
CWE More Specific
Malicious File Execution
OWASP Top Ten 2004
A6
CWE More Specific
Injection Flaws
CERT C Secure Coding
ENV03-C
Sanitize the environment when invoking external
programs
CERT C Secure Coding
ENV04-C
Do not call system() if you do not need a command
processor
Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')
Definition in a New Window
Weakness ID: 89 (Weakness Base)
Status: Draft
Description
Description Summary
The software constructs all or part of an SQL command using
externally-influenced input from an upstream component, but it does not sanitize
or incorrectly sanitizes special elements that could modify the intended SQL
command when it is sent to a downstream component.
Extended Description
Without sufficient removal or quoting of SQL syntax in user-controllable
inputs, the generated SQL query can cause those inputs to be interpreted as
SQL instead of ordinary user data. This can be used to alter query logic to
bypass security checks, or to insert additional statements that modify the
back-end database, possibly including execution of system commands.
SQL injection has become a common issue with database-driven web sites.
The flaw is easily detected, and easily exploited, and as such, any site or
software package with even a minimal user base is likely to be subject to an
attempted attack of this kind. This flaw depends on the fact that SQL makes
no real distinction between the control and data planes.
Time of Introduction
Architecture and Design
Implementation
Operation
Applicable Platforms
Languages
All
Technology Classes
Database-Server
Modes of Introduction
This weakness typically appears in data-rich applications that save user
inputs in a database.
Common Consequences
Scope
Effect
Confidentiality
Since SQL databases generally hold sensitive data, loss of
confidentiality is a frequent problem with SQL injection
vulnerabilities.
Authentication
If poor SQL commands are used to check user names and passwords, it
may be possible to connect to a system as another user with no previous
knowledge of the password.
Authorization
If authorization information is held in a SQL database, it may be
possible to change this information through the successful exploitation
of a SQL injection vulnerability.
Integrity
Just as it may be possible to read sensitive information, it is also
possible to make changes or even delete this information with a SQL
injection attack.
Likelihood of Exploit
Very High
Enabling Factors for Exploitation
The application dynamically generates queries that contain user
input.
Demonstrative Examples
Example 1
In 2008, a large number of web servers were compromised using the
same SQL injection attack string. This single string worked against many
different programs. The SQL injection was then used to modify the web sites
to serve malicious code. [1]
Example 2
The following code dynamically constructs and executes a SQL query
that searches for items matching a specified name. The query restricts the
items displayed to those where owner matches the user name of the
currently-authenticated user.
(Bad Code)
C#
...
string userName = ctx.getAuthenticatedUserName();
string query = "SELECT * FROM items WHERE owner = '" + userName +
"' AND itemname = '" + ItemName.Text + "'";
sda = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
...
The query that this code intends to execute follows:
SELECT * FROM items WHERE owner = <userName> AND
itemname = <itemName>;
However, because the query is constructed dynamically by concatenating
a constant base query string and a user input string, the query only
behaves correctly if itemName does not contain a single-quote character.
If an attacker with the user name wiley enters the string:
(Attack)
name' OR 'a'='a
for itemName, then the query becomes the following:
(Attack)
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR
'a'='a';
The addition of the:
(Attack)
OR 'a'='a'
condition causes the WHERE clause to always evaluate to true, so the
query becomes logically equivalent to the much simpler query:
(Attack)
SELECT * FROM items;
This simplification of the query allows the attacker to bypass the
requirement that the query only return items owned by the authenticated
user; the query now returns all entries stored in the items table,
regardless of their specified owner.
Example 3
This example examines the effects of a different malicious value
passed to the query constructed and executed in the previous
example.
If an attacker with the user name wiley enters the string:
(Attack)
name'; DELETE FROM items; --
for itemName, then the query becomes the following two queries:
(Attack)
SQL
SELECT * FROM items WHERE owner = 'wiley' AND itemname =
'name';
DELETE FROM items;
--'
Many database servers, including Microsoft(R) SQL Server 2000, allow
multiple SQL statements separated by semicolons to be executed at once.
While this attack string results in an error on Oracle and other
database servers that do not allow the batch-execution of statements
separated by semicolons, on databases that do allow batch execution,
this type of attack allows the attacker to execute arbitrary commands
against the database.
Notice the trailing pair of hyphens (--), which specifies to most
database servers that the remainder of the statement is to be treated as
a comment and not executed. In this case the comment character serves to
remove the trailing single-quote left over from the modified query. On a
database where comments are not allowed to be used in this way, the
general attack could still be made effective using a trick similar to
the one shown in the previous example.
If an attacker enters the string
(Attack)
name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a
Then the following three valid statements will be created:
(Attack)
SELECT * FROM items WHERE owner = 'wiley' AND itemname =
'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
One traditional approach to preventing SQL injection attacks is to
handle them as an input validation problem and either accept only
characters from a whitelist of safe values or identify and escape a
blacklist of potentially malicious values. Whitelisting can be a very
effective means of enforcing strict input validation rules, but
parameterized SQL statements require less maintenance and can offer more
guarantees with respect to security. As is almost always the case,
blacklisting is riddled with loopholes that make it ineffective at
preventing SQL injection attacks. For example, attackers can:
- Target fields that are not quoted
- Find ways to bypass the need for certain escaped
meta-characters
- Use stored procedures to hide the injected meta-characters.
Manually escaping characters in input to SQL queries can help, but it
will not make your application secure from SQL injection attacks.
Another solution commonly proposed for dealing with SQL injection
attacks is to use stored procedures. Although stored procedures prevent
some types of SQL injection attacks, they fail to protect against many
others. For example, the following PL/SQL procedure is vulnerable to the
same SQL injection attack shown in the first example.
(Bad Code)
procedure get_item ( itm_cv IN OUT ItmCurTyp, usr in varchar2, itm
in varchar2)
is open itm_cv for
' SELECT * FROM items WHERE ' || 'owner = '|| usr || ' AND
itemname = ' || itm || ';
end get_item;
Stored procedures typically help prevent SQL injection attacks by
limiting the types of statements that can be passed to their parameters.
However, there are many ways around the limitations and many interesting
statements that can still be passed to stored procedures. Again, stored
procedures can prevent some exploits, but they will not make your
application secure against SQL injection attacks.
Example 4
MS SQL has a built in function that enables shell command execution.
An SQL injection in such a context could be disastrous. For example, a query
of the form:
(Bad Code)
SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='$user_input'
ORDER BY PRICE
Where $user_input is taken from the user and unfiltered.
If the user provides the string:
(Attack)
' exec master..xp_cmdshell 'vol' --
The query will take the following form: "
(Attack)
SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='' exec
master..xp_cmdshell 'vol' --' ORDER BY PRICE
Now, this query can be broken down into:
[1] a first SQL query: SELECT ITEM,PRICE FROM PRODUCT WHERE
ITEM_CATEGORY=''
[2] a second SQL query, which executes a shell command: exec
master..xp_cmdshell 'vol'
[3] an MS SQL comment: --' ORDER BY PRICE
As can be seen, the malicious input changes the semantics of the query
into a query, a shell command execution and a comment.
Example 5
This code intends to print a message summary given the message
ID.
(Bad Code)
PHP
$id = $_COOKIE["mid"];
mysql_query("SELECT MessageID, Subject FROM messages WHERE
MessageID = '$id'");
The programmer may have skipped any input validation on $id under the
assumption that attackers cannot modify the cookie. However, this is
easy to do with custom client code or even in the web browser.
While $id is wrapped in single quotes in the call to mysql_query(), an
attacker could simply change the incoming mid cookie to:
1432' or '1' = '1
This would produce the resulting query:
SELECT MessageID, Subject FROM messages WHERE MessageID = '1432'
or '1' = '1'
Not only will this retrieve message number 1432, it will retrieve all
other messages.
In this case, the programmer could apply a simple modification to the
code to eliminate the SQL injection:
(Good Code)
PHP
$id = intval($_COOKIE["mid"]);
mysql_query("SELECT MessageID, Subject FROM messages WHERE
MessageID = '$id'");
However, if this code is intended to support multiple users with
different message boxes, the code would need an access control check
(CWE-285) to ensure that the application user has the permission to see
that message.
Example 6
This example attempts to take a last name provided by a user and
enter it into a database.
(Bad Code)
Perl
$userKey = getUserID();
$name = getUserInput();
# ensure only letters, hyphens and apostrophe are allowed
$name = whiteList($name, "^a-zA-z'-$");
$query = "INSERT INTO last_names VALUES('$userKey',
'$name')";
While the programmer applies a whitelist to the user input, it has
shortcomings. First of all, the user is still allowed to provide hyphens
which are used as comment structures in SQL. If a user specifies -- then
the remainder of the statement will be treated as a comment, which may
bypass security logic. Furthermore, the whitelist permits the apostrophe
which is also a data / command separator in SQL. If a user supplies a
name with an apostrophe, they may be able to alter the structure of the
whole statement and even change control flow of the program, possibly
accessing or modifying confidential information. In this situation, both
the hyphen and apostrophe are legitimate characters for a last name and
permitting them is required. Instead, a programmer may want to use a
prepared statement or apply an encoding routine to the input to prevent
any data / directive misinterpretations.
Use languages, libraries, or frameworks that make it easier to
generate properly encoded output.
For example, consider using persistence layers such as Hibernate or
Enterprise Java Beans, which can provide significant protection against
SQL injection if used properly.
Architecture and Design
If available, use structured mechanisms that automatically enforce the
separation between data and code. These mechanisms may be able to
provide the relevant quoting, encoding, and validation automatically,
instead of relying on the developer to provide this capability at every
point where output is generated.
Process SQL queries using prepared statements, parameterized queries,
or stored procedures. These features should accept parameters or
variables and support strong typing. Do not dynamically construct and
execute query strings within these features using "exec" or similar
functionality, since you may re-introduce the possibility of SQL
injection.
Architecture and Design
Follow the principle of least privilege when creating user accounts to
a SQL database. The database users should only have the minimum
privileges necessary to use their account. If the requirements of the
system indicate that a user can read and modify their own data, then
limit their privileges so they cannot read/write others' data. Use the
strictest permissions possible on all database objects, such as
execute-only for stored procedures.
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
If you need to use dynamically-generated query strings in spite of the
risk, use proper encoding and escaping of inputs. Instead of building
your own implementation, such features may be available in the database
or programming language. For example, the Oracle DBMS_ASSERT package can
check or enforce that parameters have certain properties that make them
less vulnerable to SQL injection. For MySQL, the
mysql_real_escape_string() API function is available in both C and
PHP.
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 constructing SQL query strings, use stringent whitelists that
limit the character set based on the expected value of the parameter in
the request. This will indirectly limit the scope of an attack, but this
technique is less important than proper output encoding and
escaping.
Note that proper output encoding, escaping, and quoting is the most
effective solution for preventing SQL injection, 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 SQL injection, especially if you are required to support
free-form text fields that could contain arbitrary characters. For
example, the name "O'Reilly" would likely pass the validation step,
since it is a common last name in the English language. However, it
cannot be directly inserted into the database because it contains the
"'" apostrophe character, which would need to be escaped or otherwise
handled. In this case, stripping the apostrophe might reduce the risk of
SQL injection, but it would produce incorrect behavior because the wrong
name would be recorded.
When feasible, it may be safest to disallow meta-characters entirely,
instead of escaping them. This will provide some defense in depth. After
the data is entered into the database, later processes may neglect to
escape meta-characters before use, and you may not have control over
those processes.
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.
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.
SQL injection can be resultant from special character mismanagement, MAID,
or blacklist/whitelist problems. It can be primary to authentication
errors.
The software stores or transmits sensitive data using an
encryption scheme that is theoretically sound, but is not strong enough for the
level of protection required.
Extended Description
A weak encryption scheme can be subjected to brute force attacks that have
a reasonable chance of succeeding using current attack methods and
resources.
Time of Introduction
Architecture and Design
Applicable Platforms
Languages
All
Common Consequences
Scope
Effect
Confidentiality
An attacker may be able to decrypt the data using brute force
attacks.