CWE
Home > CWE List > VIEW SLICE: CWE-635: Weaknesses Used by NVD (1.6)  

CWE-635: Weaknesses Used by NVD

 
Weaknesses Used by NVD
Definition in a New Window Definition in a New Window
View ID: 635 (View: Explicit Slice)Status: Draft
+ View Data

View Objective

CWE nodes in this view (slice) are used by NIST to categorize vulnerabilities within NVD.

+ View Metrics
CWEs in this viewTotal CWEs
Total19out of791
Views0out of22
Categories6out of106
Weaknesses12out of651
Compound_Elements1out of12
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
HasMemberCategoryCategory16Configuration
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class20Improper Input Validation
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class22Path Traversal
Weaknesses Used by NVD (primary)635
HasMemberWeakness BaseWeakness Base59Improper Link Resolution Before File Access ('Link Following')
Weaknesses Used by NVD (primary)635
HasMemberWeakness BaseWeakness Base78Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')
Weaknesses Used by NVD (primary)635
HasMemberWeakness BaseWeakness Base79Failure to Preserve Web Page Structure ('Cross-site Scripting')
Weaknesses Used by NVD (primary)635
HasMemberWeakness BaseWeakness Base89Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class94Failure to Control Generation of Code ('Code Injection')
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class119Failure to Constrain Operations within the Bounds of a Memory Buffer
Weaknesses Used by NVD (primary)635
HasMemberWeakness BaseWeakness Base134Uncontrolled Format String
Weaknesses Used by NVD (primary)635
HasMemberCategoryCategory189Numeric Errors
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class200Information Leak (Information Disclosure)
Weaknesses Used by NVD (primary)635
HasMemberCategoryCategory255Credentials Management
Weaknesses Used by NVD (primary)635
HasMemberCategoryCategory264Permissions, Privileges, and Access Controls
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class287Improper Authentication
Weaknesses Used by NVD (primary)635
HasMemberCategoryCategory310Cryptographic Issues
Weaknesses Used by NVD (primary)635
HasMemberCompound Element: CompositeCompound Element: Composite352Cross-Site Request Forgery (CSRF)
Weaknesses Used by NVD (primary)635
HasMemberWeakness ClassWeakness Class362Race Condition
Weaknesses Used by NVD (primary)635
HasMemberCategoryCategory399Resource Management Errors
Weaknesses Used by NVD (primary)635
+ References
NIST. "CWE - Common Weakness Enumeration". <http://nvd.nist.gov/cwe.cfm>.
+ Maintenance Notes

The set of CWE elements as used in NVD was created in summer of 2007. Since then, CWE has grown, so it is expected that this list will change. The current organization as used by NVD is captured in the following image.

+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Maintenance Notes, Relationships, References, View Structure
View Components
View Components
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z
 
Configuration
Definition in a New Window Definition in a New Window
Category ID: 16 (Category)Status: Draft
+ Description

Description Summary

Weaknesses in this category are typically introduced during the configuration of the software.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory1Location
Development Concepts (primary)699
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Relationships
 
Credentials Management
Definition in a New Window Definition in a New Window
Category ID: 255 (Category)Status: Draft
+ Description

Description Summary

Weaknesses in this category are related to the management of credentials.
+ Applicable Platforms

Languages

All

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory254Security Features
Development Concepts (primary)699
ChildOfCategoryCategory724OWASP Top Ten 2004 Category A3 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2004) (primary)711
ParentOfWeakness BaseWeakness Base259Hard-Coded Password
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant261Weak Cryptography for Passwords
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant262Not Using Password Aging
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base263Password Aging with Long Expiration
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base521Weak Password Requirements
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base522Insufficiently Protected Credentials
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant549Missing Password Field Masking
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant620Unverified Password Change
Development Concepts699
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfWeakness BaseWeakness Base640Weak Password Recovery Mechanism for Forgotten Password
Development Concepts (primary)699
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
OWASP Top Ten 2004A3CWE More SpecificBroken Authentication and Session Management
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
 
Cross-Site Request Forgery (CSRF)
Definition in a New Window Definition in a New Window
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.

(Bad Code)
HTML
<form action="/url/profile.php" method="post">
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<br/>
input type="text" name="email"/>
<input type="submit" name="submit" value="Update" />
</form>

profile.php contains the following code.

(Bad Code)
// initiate the session in order to validate sessions
session_start();
//if the session is registered to a valid user then allow update
if (! session_is_registered("username")) {
echo "invalid session detected!";
// Redirect user to login page
[...]
exit;
}
// The user session is valid, so process the request
// and update the information
update_profile();
function update_profile {
// read in the data from $POST and send an update
// to the database
SendUpdateToDatabase($_SESSION['username'], $_POST['email']);
[...]
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:

(Attack)
HTML
<SCRIPT>
function SendAttack () {
form.email = "attacker@example.com";
// send to profile.php
form.submit();
}
</SCRIPT>
<BODY onload="javascript:SendAttack();">
<form action="http://victim.example.com/profile.php" id="form" method="post">
<input type="hidden" name="firstname" value="Funny">
<input type="hidden" name="lastname" value="Joke">
<br/>
<input type="hidden" name="email">
</form>

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.

+ Observed Examples
ReferenceDescription
CVE-2004-1703Add user accounts via a URL in an img tag
CVE-2004-1995Add user accounts via a URL in an img tag
CVE-2004-1967Arbitrary code execution by specifying the code in a crafted img tag or URL
CVE-2004-1842Gain administrative privileges via a URL in an img tag
CVE-2005-1947Delete a victim's information via a URL or an img tag
CVE-2005-2059Change another users settings via a URL or an img tag
CVE-2005-1674Perform actions as administrator via a URL or an img tag
+ Potential Mitigations
PhaseDescription
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.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class345Insufficient Verification of Data Authenticity
Development Concepts (primary)699
Research Concepts (primary)1000
RequiresWeakness BaseWeakness Base346Origin Validation Error
Research Concepts1000
RequiresWeakness BaseWeakness Base441Unintended Proxy/Intermediary
Research Concepts1000
RequiresWeakness BaseWeakness Base613Insufficient Session Expiration
Research Concepts1000
RequiresWeakness ClassWeakness Class642External Control of Critical State Data
Research Concepts1000
ChildOfCategoryCategory716OWASP Top Ten 2007 Category A5 - Cross Site Request Forgery (CSRF)
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory751Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
PeerOfWeakness BaseWeakness Base79Failure to Preserve Web Page Structure ('Cross-site Scripting')
Research Concepts1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Relationship Notes

This can be resultant from XSS, although XSS is not necessarily required.

+ Research Gaps

This issue was under-reported in CVE until around 2008, when it began to gain prominence. It is likely to be present in most web applications.

+ Theoretical Notes

The CSRF topology is multi-channel:

1. Attacker (as outsider) to intermediary (as user). The interaction point is either an external or internal channel.

2. Intermediary (as user) to server (as victim). The activation point is an internal channel.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCross-Site Request Forgery (CSRF)
OWASP Top Ten 2007A5ExactCross Site Request Forgery (CSRF)
+ References
Peter W. "Cross-Site Request Forgeries (Re: The Dangers of Allowing Users to Post Images)". Bugtraq. <http://marc.info/?l=bugtraq&m=99263135911884&w=2>.
Edward W. Felten and William Zeller. "Cross-Site Request Forgeries: Exploitation and Prevention". 2008-10-18. <http://freedom-to-tinker.com/sites/default/files/csrf.pdf>.
Robert Auger. "CSRF - The Cross-Site Request Forgery (CSRF/XSRF) FAQ". <http://www.cgisecurity.com/articles/csrf-faq.shtml>.
"Cross-site request forgery". Wikipedia. 2008-12-22. <http://en.wikipedia.org/wiki/Cross-site_request_forgery>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-09-08CWE Content TeamMITREInternal
updated Alternate Terms, Description, Relationships, Other Notes, Relationship Notes, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Applicable Platforms, Description, Likelihood of Exploit, Observed Examples, Other Notes, Potential Mitigations, References, Relationship Notes, Relationships, Research Gaps, Theoretical Notes
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-05-20Tom StracenerExternal
Added demonstrative example for profile.
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples, Related Attack Patterns
 
Cryptographic Issues
Definition in a New Window Definition in a New Window
Category ID: 310 (Category)Status: Draft
+ Description

Description Summary

Weaknesses in this category are related to the use of cryptography.
+ Applicable Platforms

Languages

All

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory254Security Features
Development Concepts (primary)699
CanAlsoBeWeakness BaseWeakness Base208Timing Discrepancy Information Leak
Research Concepts1000
CanAlsoBeWeakness BaseWeakness Base226Sensitive Information Uncleared Before Release
Research Concepts1000
ParentOfWeakness BaseWeakness Base311Failure to Encrypt Sensitive Data
Development Concepts (primary)699
ParentOfCategoryCategory320Key Management Errors
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base325Missing Required Cryptographic Step
Development Concepts (primary)699
ParentOfWeakness ClassWeakness Class326Inadequate Encryption Strength
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base327Use of a Broken or Risky Cryptographic Algorithm
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base328Reversible One-Way Hash
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant329Not Using a Random IV with CBC Mode
Development Concepts (primary)699
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfWeakness VariantWeakness Variant780Use of RSA Algorithm without OAEP
Development Concepts (primary)699
+ Relationship Notes

Some of these can be resultant.

+ Functional Areas
  • Cryptography
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCryptographic Issues
+ Maintenance Notes

This category is incomplete and needs refinement, as there is good documentation of cryptographic flaws and related attacks.

Relationships between CWE-310, CWE-326, and CWE-327 and all their children need to be reviewed and reorganized.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Maintenance Notes, Relationships, Relationship Notes, Taxonomy Mappings
2009-07-27CWE Content TeamMITREInternal
updated Maintenance Notes, Relationship Notes, Relationships
2009-10-29CWE Content TeamMITREInternal
updated Relationships
 
Failure to Constrain Operations within the Bounds of a Memory Buffer
Definition in a New Window 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
ScopeEffect
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.

(Bad Code)
C
char * copy_input(char *user_supplied_string){
int i, dst_index;
char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);
if ( MAX_SIZE <= strlen(user_supplied_string) ){
die("user string too long, die evil hacker!");
}
dst_index = 0;
for ( i = 0; i < strlen; i++ ){
if( '&' == user_supplied_string[i] ){
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = 'a';
dst_buf[dst_index++] = 'm';
dst_buf[dst_index++] = 'p';
dst_buf[dst_index++] = ';';
}
else if ('<' == user_supplied_string[i] ){
/* encode to &lt; */
}
else dst_buf[dst_index++] = user_supplied_string[i];
}
return dst_buf;
}

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.

(Bad Code)
C
int main (int argc, char **argv) {
char *items[] = {"boat", "car", "truck", "train"};
int index = GetUntrustedOffset();
printf("You selected %s\n", items[index-1]);
}

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).

+ Observed Examples
ReferenceDescription
CVE-2009-2550Classic stack-based buffer overflow in media player using a long entry in a playlist
CVE-2009-2403Heap-based buffer overflow in media player using a long entry in a playlist
CVE-2009-0689large precision value in a format string triggers overflow
CVE-2009-0690negative offset value leads to ouf-of-bounds read
CVE-2009-1532malformed inputs cause accesses of uninitialized or previously-deleted objects, leading to memory corruption
CVE-2009-1528chain: lack of synchronization leads to memory corruption
CVE-2009-0558attacker-controlled array index leads to code execution
CVE-2009-0269chain: -1 value from a function call was intended to indicate an error, but is used as an array index instead.
CVE-2009-0566chain: incorrect calculations lead to incorrect pointer dereference and memory corruption
CVE-2009-1350product accepts crafted messages that lead to a dereference of an arbitrary pointer
CVE-2009-0191chain: malformed input causes dereference of uninitialized memory
CVE-2008-4113OS kernel trusts userland-supplied length value, allowing reading of sensitive information
+ Potential Mitigations
PhaseDescription
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.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)Named Chain(s) this relationship pertains toChain(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Development Concepts699
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class118Improper Access of Indexable Resource ('Range Error')
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory726OWASP Top Ten 2004 Category A5 - Buffer Overflows
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory740CERT C Secure Coding Section 06 - Arrays (ARR)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory741CERT C Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory744CERT C Secure Coding Section 10 - Environment (ENV)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory752Risky Resource Management
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ParentOfCompound Element: CompositeCompound Element: Composite120Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base123Write-what-where Condition
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base125Out-of-bounds Read
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowWeakness BaseWeakness Base128Wrap-around Error
Research Concepts1000
CanFollowWeakness BaseWeakness Base129Improper Validation of Array Index
Research Concepts1000
CanFollowWeakness BaseWeakness Base131Incorrect Calculation of Buffer Size
Development Concepts699
Research Concepts1000
CanFollowWeakness BaseWeakness Base190Integer Overflow or Wraparound
Research Concepts1000
Integer Overflow to Buffer Overflow680
CanFollowWeakness BaseWeakness Base193Off-by-one Error
Research Concepts1000
CanFollowWeakness VariantWeakness Variant195Signed to Unsigned Conversion Error
Research Concepts1000
ParentOfWeakness BaseWeakness Base466Return of Pointer Value Outside of Expected Range
Research Concepts (primary)1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfWeakness BaseWeakness Base786Access of Memory Location Before Start of Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base787Out-of-bounds Write
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base788Access of Memory Location After End of Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
+ Affected Resources
  • Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
OWASP Top Ten 2004A5ExactBuffer Overflows
CERT C Secure CodingARR00-CUnderstand how arrays work
CERT C Secure CodingARR33-CGuarantee that copies are made into storage of sufficient size
CERT C Secure CodingARR34-CEnsure that array types in expressions are compatible
CERT C Secure CodingARR35-CDo not allow loops to iterate beyond the end of an array
CERT C Secure CodingENV01-CDo not make assumptions about the size of an environment variable
CERT C Secure CodingFIO37-CDo not assume character data has been read
CERT C Secure CodingMEM09-CDo not assume memory allocation routines initialize memory
CERT C Secure CodingSTR31-CGuarantee that storage for strings has sufficient space for character data and the null terminator
CERT C Secure CodingSTR32-CNull-terminate byte strings as required
CERT C Secure CodingSTR33-CSize wide character strings correctly
+ References
Microsoft. "Using the Strsafe.h Functions". <http://msdn.microsoft.com/en-us/library/ms647466.aspx>.
Matt Messier and John Viega. "Safe C String Library v1.0.3". <http://www.zork.org/safestr/>.
Michael Howard. "Address Space Layout Randomization in Windows Vista". <http://blogs.msdn.com/michael_howard/archive/2006/05/26/address-space-layout-randomization-in-windows-vista.aspx>.
Arjan van de Ven. "Limiting buffer overflows with ExecShield". <http://www.redhat.com/magazine/009jul05/features/execshield/>.
"PaX". <http://en.wikipedia.org/wiki/PaX>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Taxonomy Mappings
2008-10-14CWE Content TeamMITREInternal
updated Relationships
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Demonstrative Examples, Likelihood of Exploit, Name, Potential Mitigations, References, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-07-27CWE Content TeamMITREInternal
updated Observed Examples
2009-10-29CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Demonstrative Examples, Description, Relationships, Time of Introduction
 
Failure to Control Generation of Code ('Code Injection')
Definition in a New Window Definition in a New Window
Weakness ID: 94 (Weakness Class)Status: Draft
+ Description

Description Summary

The product does not sufficiently filter code (control-plane) syntax from user-controlled input (data plane) when that input is used within code that the product generates.

Extended Description

When software allows a user's input to contain code syntax, it might be possible for an attacker to craft the code in such a way that it will alter the intended control flow of the software. Such an alteration could lead to arbitrary code execution.

Injection problems encompass a wide variety of issues -- all mitigated in very different ways. For this reason, the most effective way to discuss these weaknesses is to note the distinct features which classify them as injection weaknesses. The most important issue to note is that all injection problems share one thing in common -- i.e., they allow for the injection of control plane data into the user-controlled data plane. This means that the execution of the process may be altered by sending code in through legitimate data channels, using no other mechanism. While buffer overflows, and many other flaws, involve the use of some further issue to gain execution, injection problems need only for the data to be parsed. The most classic instantiations of this category of weakness are SQL injection and format string vulnerabilities.

+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

Interpreted languages: (Sometimes)

+ Common Consequences
ScopeEffect
Confidentiality

The injected code could access restricted data / files

Authentication

In some cases, injectable code controls authentication; this may lead to a remote vulnerability

Access Control

Injected code can access resources that the attacker is directly prevented from accessing

Integrity

Code injection attacks can lead to loss of data integrity in nearly all cases as the control-plane data injected is always incidental to data recall or writing. Additionally, code injection can often result in the execution of arbitrary code.

Accountability

Often the actions performed by injected control code are unlogged.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

This example attempts to write user messages to a message file and allow users to view them.

(Bad Code)
PHP
$MessageFile = "cwe-94/messages.out";
if ($_GET["action"] == "NewMessage") {
$name = $_GET["name"];
$message = $_GET["message"];
$handle = fopen($MessageFile, "a+");
fwrite($handle, "<b>$name</b> says '$message'<hr>\n");
fclose($handle);
echo "Message Saved!<p>\n";
}
else if ($_GET["action"] == "ViewMessages") {
include($MessageFile);
}

While the programmer intends for the MessageFile to only include data, an attacker can provide a message such as:

(Attack)
name=h4x0r
message=%3C?php%20system(%22/bin/ls%20-l%22);?%3E

which will decode to the following:

(Attack)
<?php system("/bin/ls -l");?>

The programmer thought they were just including the contents of a regular data file, but PHP parsed it and executed the code. Now, this code is executed any time people view messages.

Notice that XSS (CWE-79) is also possible in this situation.

+ Potential Mitigations
PhaseDescription
Architecture and Design

Refactor your program so that you do not have to dynamically generate code.

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 code 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.

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.

To reduce the likelihood of code injection, use stringent whitelists that limit which constructs are allowed. If you are dynamically constructing code that invokes a function, then verifying that the input is alphanumeric might be insufficient. An attacker might still be able to reference a dangerous function that you did not intend to allow, such as system(), exec(), or exit().

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

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).

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class74Failure to Sanitize Data into a Different Plane ('Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfWeakness ClassWeakness Class691Insufficient Control Flow Management
Research Concepts1000
ChildOfCategoryCategory752Risky Resource Management
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ParentOfWeakness BaseWeakness Base95Improper Sanitization of Directives in Dynamically Evaluated Code ('Eval Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base96Improper Sanitization of Directives in Statically Saved Code ('Static Code Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowCompound Element: CompositeCompound Element: Composite98Improper Control of Filename for Include/Require Statement in PHP Program ('PHP File Inclusion')
Development Concepts (primary)699
Research Concepts1000
ParentOfWeakness BaseWeakness Base621Variable Extraction Error
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base627Dynamic Variable Evaluation
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Research Gaps

Many of these weaknesses are under-studied and under-researched, and terminology is not sufficiently precise.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCODECode Evaluation and Injection
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-09-08CWE Content TeamMITREInternal
updated Applicable Platforms, Relationships, Research Gaps, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Common Consequences, Demonstrative Examples, Description, Likelihood of Exploit, Name, Potential Mitigations, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples, Name
 
Failure to Preserve Web Page Structure ('Cross-site Scripting')
Definition in a New Window 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.

Extended Description

Cross-site scripting (XSS) vulnerabilities occur when:

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
ScopeEffect
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.

(Bad Code)
ASP.NET
...
protected System.Web.UI.WebControls.TextBox Login;
protected System.Web.UI.WebControls.Label EmployeeID;
...
EmployeeID.Text = Login.Text;
... (HTML follows) ...
<p><asp:label id="EmployeeID" runat="server" /></p>
...

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.

(Bad Code)
ASP.NET
protected System.Web.UI.WebControls.Label EmployeeName;
...
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

The data is then included in dynamic content.

+ Observed Examples
ReferenceDescription
CVE-2008-5080Chain: protection mechanism failure allows XSS
CVE-2006-4308Chain: only checks "javascript:" tag
CVE-2007-5727Chain: only removes SCRIPT tags, enabling XSS
CVE-2008-5770Reflected XSS using the PATH INFO in a URL
CVE-2008-4730Reflected XSS not properly handled when generating an error message
CVE-2008-5734Reflected XSS sent through email message
CVE-2008-0971Stored XSS in a security product
CVE-2008-5249Stored XSS using a wiki page
+ Potential Mitigations
PhaseDescription
Architecture and Design

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
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)Named Chain(s) this relationship pertains toChain(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class74Failure to Sanitize Data into a Different Plane ('Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
PeerOfCompound Element: CompositeCompound Element: Composite352Cross-Site Request Forgery (CSRF)
Research Concepts1000
ChildOfCategoryCategory442Web Problems
Development Concepts699
CanPrecedeWeakness BaseWeakness Base494Download of Code Without Integrity Check
Research Concepts1000
ChildOfCategoryCategory712OWASP Top Ten 2007 Category A1 - Cross Site Scripting (XSS)
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004)711
ChildOfCategoryCategory725OWASP Top Ten 2004 Category A4 - Cross-Site Scripting (XSS) Flaws
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory751Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ParentOfWeakness VariantWeakness Variant80Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS)
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant81Improper Sanitization of Script in an Error Message Web Page
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant83Failure to Sanitize Script in Attributes in a Web Page
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant84Failure to Resolve Encoded URI Schemes in a Web Page
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant85Doubled Character XSS Manipulations
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant86Failure to Sanitize Invalid Characters in Identifiers in Web Pages
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant87Failure to Sanitize Alternate XSS Syntax
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowWeakness BaseWeakness Base113Failure to Sanitize CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
Research Concepts1000
CanFollowWeakness BaseWeakness Base184Incomplete Blacklist
Research Concepts1000
Incomplete Blacklist to Cross-Site Scripting692
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCross-site scripting (XSS)
7 Pernicious KingdomsCross-site Scripting
CLASPCross-site scripting
OWASP Top Ten 2007A1ExactCross Site Scripting (XSS)
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
OWASP Top Ten 2004A4ExactCross-Site Scripting (XSS) Flaws
+ References
Jeremiah Grossman, Robert "RSnake" Hansen, Petko "pdp" D. Petkov, Anton Rager and Seth Fogie. "XSS Attacks". Syngress. 2007.
"Cross-site scripting". Wikipedia. 2008-08-26. <http://en.wikipedia.org/wiki/Cross-site_scripting>.
M. Howard and D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003.
RSnake. "XSS (Cross Site Scripting) Cheat Sheet". <http://ha.ckers.org/xss.html>.
Microsoft. "Mitigating Cross-site Scripting With HTTP-only Cookies". <http://msdn.microsoft.com/en-us/library/ms533046.aspx>.
Mark Curphey, Microsoft. "Anti-XSS 3.0 Beta and CAT.NET Community Technology Preview now Live!". <http://blogs.msdn.com/cisg/archive/2008/12/15/anti-xss-3-0-beta-and-cat-net-community-technology-preview-now-live.aspx>.
"OWASP Enterprise Security API (ESAPI) Project". <http://www.owasp.org/index.php/ESAPI>.
Ivan Ristic. "XSS Defense HOWTO". <http://blog.modsecurity.org/2008/07/do-you-know-how.html>.
OWASP. "Web Application Firewall". <http://www.owasp.org/index.php/Web_Application_Firewall>.
Web Application Security Consortium. "Web Application Firewall Evaluation Criteria". <http://www.webappsec.org/projects/wafec/v1/wasc-wafec-v1.0.html>.
RSnake. "Firefox Implements httpOnly And is Vulnerable to XMLHTTPRequest". 2007-07-19.
"XMLHttpRequest allows reading HTTPOnly cookies". Mozilla. <https://bugzilla.mozilla.org/show_bug.cgi?id=380418>.
"Apache Wicket". <http://wicket.apache.org/>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08CWE Content TeamMITREInternal
updated Alternate Terms, Applicable Platforms, Background Details, Common Consequences, Description, Relationships, Other Notes, References, Taxonomy Mappings, Weakness Ordinalities
2009-01-12CWE Content TeamMITREInternal
updated Alternate Terms, Applicable Platforms, Background Details, Common Consequences, Demonstrative Examples, Description, Detection Factors, Enabling Factors for Exploitation, Name, Observed Examples, Other Notes, Potential Mitigations, References, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Name
2009-07-27CWE Content TeamMITREInternal
updated Description
2009-10-29CWE Content TeamMITREInternal
updated Observed Examples, Relationships
 
Improper Authentication
Definition in a New Window Definition in a New Window
Weakness ID: 287 (Weakness Class)Status: Draft
+ Description

Description Summary

When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
+ Alternate Terms
authentification:

An alternate term is "authentification", which appears to be most commonly used by people from non-English-speaking countries.

+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Integrity
Access Control

Authentication bypass

+ Observed Examples
ReferenceDescription
CVE-2009-3421login script for guestbook allows bypassing authentication by setting a "login ok" parameter to 1.
CVE-2009-2382admin script allows authentication bypass by setting a cookie value to "LOGGEDIN".
CVE-2009-1048VOIP product allows authentication bypass using 127.0.0.1 in the Host header.
CVE-2009-2213product uses default "Allow" action, instead of default deny, leading to authentication bypass.
CVE-2009-2168chain: redirect without exit (CWE-698) leads to resultant authentication bypass.
CVE-2009-3107product does not restrict access to a listening port for a critical service, allowing authentication to be bypassed.
CVE-2009-1596product does not properly implement a security-related configuration setting, allowing authentication bypass.
CVE-2009-2422authentication routine returns "nil" instead of "false" in some situations, allowing authentication bypass using an invalid username.
CVE-2009-3232authentication update script does not properly handle when admin does not select any authentication modules, allowing authentication bypass.
CVE-2009-3231use of LDAP authentication with anonymous binds causes empty password to result in successful authentication
CVE-2005-3435product authentication succeeds if user-provided MD5 hash matches the hash in its database; this can be subjected to replay attacks.
CVE-2005-0408chain: product generates predictable MD5 hashes using a constant value combined with username, allowing authentication bypass.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory254Security Features
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class693Protection Mechanism Failure
Research Concepts (primary)1000
ChildOfCategoryCategory718OWASP Top Ten 2007 Category A7 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory724OWASP Top Ten 2004 Category A3 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2004) (primary)711
ParentOfWeakness ClassWeakness Class300Channel Accessible by Non-Endpoint ('Man-in-the-Middle')
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant301Reflection Attack in an Authentication Protocol
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base303Incorrect Implementation of Authentication Algorithm
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base304Missing Critical Step in Authentication
Development Concepts (primary)699
CanFollowWeakness BaseWeakness Base304Missing Critical Step in Authentication
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant306No Authentication for Critical Function
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base307Failure to Restrict Excessive Authentication Attempts
Development Concepts (primary)699
Research Concepts1000
ParentOfWeakness BaseWeakness Base308Use of Single-factor Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base309Use of Password System for Primary Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base322Key Exchange without Entity Authentication
Research Concepts (primary)1000
ParentOfCompound Element: CompositeCompound Element: Composite384Session Fixation
Development Concepts699
Research Concepts (primary)1000
ParentOfWeakness ClassWeakness Class592Authentication Bypass Issues
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base603Use of Client-Side Authentication
Development Concepts (primary)699
Research Concepts1000
CanFollowWeakness BaseWeakness Base613Insufficient Session Expiration
Development Concepts (primary)699
Research Concepts1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfWeakness BaseWeakness Base645Overly Restrictive Account Lockout Mechanism
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant784Reliance on Cookies without Validation and Integrity Checking in a Security Decision
Research Concepts1000
+ Relationship Notes

This can be resultant from SQL injection vulnerabilities and other issues.

+ Functional Areas
  • Authentication
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERAuthentication Error
OWASP Top Ten 2007A7CWE More SpecificBroken Authentication and Session Management
OWASP Top Ten 2004A3CWE More SpecificBroken Authentication and Session Management
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08CWE Content TeamMITREInternal
updated Alternate Terms, Common Consequences, Relationships, Relationship Notes, Taxonomy Mappings
2008-10-14CWE Content TeamMITREInternal
updated Relationships
2009-01-12CWE Content TeamMITREInternal
updated Name
2009-05-27CWE Content TeamMITREInternal
updated Description, Related Attack Patterns
2009-07-27CWE Content TeamMITREInternal
updated Relationships
2009-10-29CWE Content TeamMITREInternal
updated Common Consequences, Observed Examples
 
Improper Input Validation
Definition in a New Window Definition in a New Window
Weakness ID: 20 (Weakness Class)Status: Usable
+ Description

Description Summary

The product does not validate or incorrectly validates input that can affect the control flow or data flow of a program.

Extended Description

When software fails to validate input properly, an attacker is able to craft the input in a form that is not expected by the rest of the application. This will lead to parts of the system receiving unintended input, which may result in altered control flow, arbitrary control of a resource, or arbitrary code execution.

+ Terminology Notes

The "input validation" term is extremely common, but it is used in many different ways. In some cases its usage can obscure the real underlying weakness or otherwise hide chaining and composite relationships.

Some people use "input validation" as a general term that covers many different techniques for ensuring that input is appropriate, such as cleansing/filtering, canonicalization, and escaping. Others use the term in a more narrow context to simply mean "checking if an input conforms to expectations without changing it."

+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

Platform Notes

Input validation can be a problem in any system that handles data from an external source.

+ Modes of Introduction

If a programmer believes that an attacker cannot modify certain inputs, then the programmer might not perform any input validation at all. For example, in web applications, many programmers believe that cookies and hidden form fields can not be modified from a web browser (CWE-472), although they can be altered using a proxy or a custom program. In a client-server architecture, the programmer might assume that client-side security checks cannot be bypassed, even when a custom client could be written that skips those checks (CWE-602).

+ Common Consequences
ScopeEffect
Availability

An attacker could provide unexpected values and cause a program crash or excessive consumption of resources, such as memory and CPU.

Confidentiality

An attacker could read confidential data if they are able to control resource references.

Integrity

An attacker could use malicious input to modify data or possibly alter control flow in unexpected ways, including arbitrary command execution.

+ Likelihood of Exploit

High

+ Demonstrative Examples

Example 1

This example demonstrates a shopping interaction in which the user is free to specify the quantity of items to be purchased and a total is calculated.

(Bad Code)
Java
...
public static final double price = 20.00;
int quantity = currentUser.getAttribute("quantity");
double total = price * quantity;
chargeUser(total);
...

The user has no control over the price variable, however the code does not prevent a negative value from being specified for quantity. If an attacker were to provide a negative value, then the user would have their account credited instead of debited.

Example 2

This example asks the user for a height and width of an m X n game board with a maximum dimension of 100 squares.

(Bad Code)
C
...
#define MAX_DIM 100
...
int m,n, error; /* board dimensions */
board_square_t *board;
printf("Please specify the board height: \n");
error = scanf("%d", &m);
if ( EOF == error ){
die("No integer passed: Die evil hacker!\n");
}
printf("Please specify the board width: \n");
error = scanf("%d", &n);
if ( EOF == error ){
die("No integer passed: Die evil hacker!\n");
}
if ( m > MAX_DIM || n > MAX_DIM ) {
die("Value too large: Die evil hacker!\n");
}
board = (board_square_t*) malloc( m * n * sizeof(board_square_t));
...

While this code checks to make sure the user cannot specify large, positive integers and consume too much memory, it fails to check for negative values supplied by the user. As a result, an attacker can perform a resource consumption (CWE-400) attack against this program by specifying two, large negative values that will not overflow, resulting in a very large memory allocation (CWE-789) and possibly a system crash. Alternatively, an attacker can provide very large negative values which will cause an integer overflow (CWE-190) and unexpected behavior will follow depending on how the values are treated in the remainder of the program.

Example 3

The following example shows a PHP application in which the programmer attempts to display a user's birthday and homepage.

(Bad Code)
PHP
$birthday = $_GET['birthday'];
$homepage = $_GET['homepage'];
echo "Birthday: $birthday<br>Homepage: <a href=$homepage>click here</a>"

The programmer intended for $birthday to be in a date format and $homepage to be a valid URL. However, since the values are derived from an HTTP request, if an attacker can trick a victim into clicking a crafted URL with <script> tags providing the values for birthday and / or homepage, then the script will run on the client's browser when the webserver echoes the content. Notice that even if the programmer were to defend the $birthday variable by restricting input to integers and dashes, it would still be possible for an attacker to provide a string of the form:

(Attack)
2009-01-09--

If this data were used in a SQL statement, it would treat the remainder of the statement as a comment. The comment could disable other security-related logic in the statement. In this case, encoding combined with input validation would be a more useful protection mechanism.

Furthermore, an XSS (CWE-79) attack or SQL injection (CWE-89) are just a few of the potential consequences in a failed protection mechanism of this nature. Depending on the context of the code, CRLF Injection (CWE-93), Argument Injection (CWE-88), or Command Injection (CWE-77) may also be possible.

Example 4

This function attempts to extract a pair of numbers from a user-supplied string.

(Bad Code)
C
void parse_data(char *untrusted_input){
int m, n, error;
error = sscanf(untrusted_input, "%d:%d", &m, &n);
if ( EOF == error ){
die("Did not specify integer value. Die evil hacker!\n");
}
/* proceed assuming n and m are initialized correctly */
}

This code attempts to extract two integer values out of a formatted, user-supplied input. However, if an attacker were to provide an input of the form:

(Attack)
123:

then only the m variable will be initialized. Subsequent use of n may result in the use of an uninitialized variable (CWE-457).

Example 5

The following example takes a user-supplied value to allocate an array of objects and then operates on the array.

(Bad Code)
Java
private void buildList ( int untrustedListSize ){
if ( 0 > untrustedListSize ){
die("Negative value supplied for list size, die evil hacker!");
}
Widget[] list = new Widget [ untrustedListSize ];
list[0] = new Widget();
}

This example attempts to build a list from a user-specified value, and even checks to ensure a non-negative value is supplied. If, however, a 0 value is provided, the code will build an array of size 0 and then try to store a new Widget in the first location, causing an exception to be thrown.

+ Observed Examples
ReferenceDescription
CVE-2008-5305Eval injection in Perl program using an ID that should only contain hyphens and numbers.
CVE-2008-2223SQL injection through an ID that was supposed to be numeric.
CVE-2008-3477lack of input validation in spreadsheet program leads to buffer overflows, integer overflows, array index errors, and memory corruption.
CVE-2008-3843insufficient validation enables XSS
CVE-2008-3174driver in security product allows code execution due to insufficient validation
CVE-2007-3409infinite loop from DNS packet with a label that points to itself
CVE-2006-6870infinite loop from DNS packet with a label that points to itself
CVE-2008-1303missing parameter leads to crash
CVE-2007-5893HTTP request with missing protocol version number leads to crash
CVE-2006-6658request with missing parameters leads to information leak
CVE-2008-4114system crash with offset value that is inconsistent with packet size
CVE-2006-3790size field that is inconsistent with packet size leads to buffer over-read
CVE-2008-2309product uses a blacklist to identify potentially dangerous content, allowing attacker to bypass a warning
CVE-2008-3494security bypass via an extra header
CVE-2006-5462use of extra data in a signature allows certificate signature forging
CVE-2008-3571empty packet triggers reboot
CVE-2006-5525incomplete blacklist allows SQL injection
CVE-2008-1284NUL byte in theme name cause directory traversal impact to be worse
CVE-2008-0600kernel does not validate an incoming pointer before dereferencing it
CVE-2008-1738anti-virus product has insufficient input validation of hooked SSDT functions, allowing code execution
CVE-2008-1737anti-virus product allows DoS via zero-length field
CVE-2008-3464driver does not validate input from userland to the kernel
CVE-2008-2252kernel does not validate parameters sent in from userland, allowing code execution
CVE-2008-2374lack of validation of string length fields allows memory consumption or buffer over-read
CVE-2008-1440lack of validation of length field leads to infinite loop
CVE-2008-1625lack of validation of input to an IOCTL allows code execution
CVE-2008-3177zero-length attachment causes crash
CVE-2007-2442zero-length input causes free of uninitialized pointer
CVE-2008-5563crash via a malformed frame structure
CVE-2008-5285infinite loop from a long SMTP request
CVE-2008-3812router crashes with a malformed packet
CVE-2008-3680packet with invalid version number leads to NULL pointer dereference
CVE-2008-3660crash via multiple "." characters in file extension
+ Potential Mitigations
PhaseDescription
Architecture and Design

Use an input validation framework such as Struts or the OWASP ESAPI Validation API. If you use Struts, be mindful of weaknesses covered by the CWE-101 category.

Architecture and Design

Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, request headers as well as content, URL components, e-mail, files, databases, and any external systems that provide data to the application. Perform input validation at well-defined interfaces.

Architecture and Design

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."

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.

Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.

Architecture and Design

Do not rely exclusively on blacklist validation to detect malicious input or to encode output (CWE-184). There are too many ways to encode the same character, so you're likely to miss some variants.

Implementation

When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.

Implementation

Be especially careful to validate your input when you invoke code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.

Implementation

Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.

Implementation

Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.

Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.

Implementation

When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.

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.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory19Data Handling
Development Concepts (primary)699
CanPrecedeWeakness ClassWeakness Class22Path Traversal
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base41Improper Resolution of Path Equivalence
Research Concepts1000
CanPrecedeWeakness ClassWeakness Class74Failure to Sanitize Data into a Different Plane ('Injection')
Research Concepts1000
ChildOfWeakness ClassWeakness Class693Protection Mechanism Failure
Research Concepts (primary)1000
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory738CERT C Secure Coding Section 04 - Integers (INT)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory746CERT C Secure Coding Section 12 - Error Handling (ERR)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory747CERT C Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory751Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ParentOfWeakness BaseWeakness Base15External Control of System or Configuration Setting
Seven Pernicious Kingdoms (primary)700
ParentOfCategoryCategory21Pathname Traversal and Equivalence Errors
Development Concepts (primary)699
ParentOfWeakness ClassWeakness Class73External Control of File Name or Path
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness ClassWeakness Class77Improper Sanitization of Special Elements used in a Command ('Command Injection')
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base79Failure to Preserve Web Page Structure ('Cross-site Scripting')
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base89Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base99Improper Control of Resource Identifiers ('Resource Injection')
Seven Pernicious Kingdoms (primary)700
ParentOfCategoryCategory100Technology-Specific Input Validation Problems
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant102Struts: Duplicate Validation Forms
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant103Struts: Incomplete validate() Method Definition
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant104Struts: Form Bean Does Not Extend Validation Class
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant105Struts: Form Field Without Validator
Seven Pernicious Kingdoms (primary)700
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant106Struts: Plug-in Framework not in Use
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant107Struts: Unused Validation Form
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant108Struts: Unvalidated Action Form
Seven Pernicious Kingdoms (primary)700
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant109Struts: Validator Turned Off
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant110Struts: Validator Without Form Field
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base111Direct Use of Unsafe JNI
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base112Missing XML Validation
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base113Failure to Sanitize CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base114Process Control
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base117Improper Output Sanitization for Logs
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness ClassWeakness Class119Failure to Constrain Operations within the Bounds of a Memory Buffer
Development Concepts699
Seven Pernicious Kingdoms (primary)700
ParentOfCompound Element: CompositeCompound Element: Composite120Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base129Improper Validation of Array Index
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base134Uncontrolled Format String
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base170Improper Null Termination
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base190Integer Overflow or Wraparound
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base466Return of Pointer Value Outside of Expected Range
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness BaseWeakness Base470Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant554ASP.NET Misconfiguration: Not Using Input Validation Framework
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant601URL Redirection to Untrusted Site ('Open Redirect')
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base606Unchecked Input for Loop Condition
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base621Variable Extraction Error
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant622Unvalidated Function Hook Arguments
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant626Null Byte Interaction Error (Poison Null Byte)
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfCompound Element: ChainCompound Element: Chain680Integer Overflow to Buffer Overflow
Research Concepts (primary)1000
ParentOfCompound Element: ChainCompound Element: Chain690Unchecked Return Value to NULL Pointer Dereference
Research Concepts (primary)1000
ParentOfCompound Element: ChainCompound Element: Chain692Incomplete Blacklist to Cross-Site Scripting
Research Concepts (primary)1000
MemberOfViewView700Seven Pernicious Kingdoms
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant781Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant785Use of Path Manipulation Function without Maximum-sized Buffer
Development Concepts699
Seven Pernicious Kingdoms (primary)700
ParentOfWeakness VariantWeakness Variant789Uncontrolled Memory Allocation
Research Concepts1000
+ Relationship Notes

CWE-116 and CWE-20 have a close association because, depending on the nature of the structured message, proper input validation can indirectly prevent special characters from changing the meaning of a structured message. For example, by validating that a numeric ID field should only contain the 0-9 characters, the programmer effectively prevents injection attacks.

However, input validation is not always sufficient, especially when less stringent data types must be supported, such as free-form text. Consider a SQL injection scenario in which a last name is inserted into a query. 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.

+ Research Gaps

There is not much research into the classification of input validation techniques and their application. Many publicly-disclosed vulnerabilities simply characterize a problem as "input validation" without providing more specific details that might contribute to a deeper understanding of validation techniques and the weaknesses they can prevent or reduce. Validation is over-emphasized in contrast to other sanitization techniques such as cleansing and enforcement by conversion. See the vulnerability theory paper.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsInput validation and representation
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
CERT C Secure CodingERR07-CPrefer functions that support error checking over equivalent functions that don't
CERT C Secure CodingINT06-CUse strtol() or a related function to convert a string token to an integer
CERT C Secure CodingMEM10-CDefine and use a pointer validation function
CERT C Secure CodingMSC08-CLibrary functions should validate their parameters
+ References
Jim Manico. "Input Validation with ESAPI - Very Important". 2008-08-15. <http://manicode.blogspot.com/2008/08/input-validation-with-esapi.html>.
"OWASP Enterprise Security API (ESAPI) Project". <http://www.owasp.org/index.php/ESAPI>.
Joel Scambray, Mike Shema and Caleb Sima. "Hacking Exposed Web Applications, Second Edition". McGraw-Hill. 2006-06-05.
Jeremiah Grossman. "Input validation or output filtering, which is better?". 2007-01-30. <http://jeremiahgrossman.blogspot.com/2007/01/input-validation-or-output-filtering.html>.
Kevin Beaver. "The importance of input validation". 2006-09-06. <http://searchsoftwarequality.techtarget.com/tip/0,289483,sid92_gci1214373,00.html>.
+ Maintenance Notes

Input validation - whether missing or incorrect - is such an essential and widespread part of secure development that it is implicit in many different weaknesses. Traditionally, problems such as buffer overflows and XSS have been classified as input validation problems by many security professionals. However, input validation is not necessarily the only protection mechanism available for avoiding such problems, and in some cases it is not even sufficient. The CWE team has begun capturing these subtleties in chains within the Research Concepts view (CWE-1000), but more work is needed.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential Mitigations, Time of Introduction
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other Notes, Taxonomy Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Demonstrative Examples, Description, Likelihood of Exploit, Name, Observed Examples, Other Notes, Potential Mitigations, References, Relationship Notes, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Description, Potential Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Related Attack Patterns
2009-07-27CWE Content TeamMITREInternal
updated Relationships
2009-10-29CWE Content TeamMITREInternal
updated Common Consequences, Demonstrative Examples, Maintenance Notes, Modes of Introduction, Observed Examples, Relationships, Research Gaps, Terminology Notes
 
Improper Link Resolution Before File Access ('Link Following')
Definition in a New Window Definition in a New Window
Weakness ID: 59 (Weakness Base)Status: Draft
+ Description

Description Summary

The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
+ Alternate Terms
insecure temporary file:

Some people use the phrase "insecure temporary file" when referring to a link following weakness, but other weaknesses can produce insecure temporary files without any symlink involvement at all.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

Operating Systems

Windows: (Sometimes)

UNIX: (Often)

+ Likelihood of Exploit

Low to Medium

+ Potential Mitigations
PhaseDescription

Follow the principle of least privilege when assigning access rights to files. Denying access to a file can prevent an attacker from replacing that file with a link to a sensitive file. Ensure good compartmentalization in the system to provide protected areas that can be trusted.

+ Background Details

: Soft links are a UNIX term that is synonymous with simple shortcuts on windows based platforms.

+ Other Notes

Windows simple shortcuts, sometimes referred to as soft links, can be exploited remotely since an ".LNK" file can be uploaded like a normal file.

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory21Pathname Traversal and Equivalence Errors
Development Concepts (primary)699
ChildOfCategoryCategory632Weaknesses that Affect Files or Directories
Resource-specific Weaknesses (primary)631
ChildOfWeakness ClassWeakness Class706Use of Incorrectly-Resolved Name or Reference
Research Concepts (primary)1000
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory748CERT C Secure Coding Section 50 - POSIX (POS)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ParentOfCategoryCategory60UNIX Path Link Problems
Development Concepts (primary)699
ParentOfCompound Element: CompositeCompound Element: Composite61UNIX Symbolic Link (Symlink) Following
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant62UNIX Hard Link
Research Concepts (primary)1000
ParentOfCategoryCategory63Windows Path Link Problems
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant64Windows Shortcut Following (.LNK)
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant65Windows Hard Link
Research Concepts (primary)1000
CanFollowWeakness ClassWeakness Class73External Control of File Name or Path
Research Concepts1000
CanFollowWeakness BaseWeakness Base363Race Condition Enabling Link Following
Research Concepts1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Relationship Notes

Link following vulnerabilities are Multi-factor Vulnerabilities (MFV). They are the combination of multiple elements: file or directory permissions, filename predictability, race conditions, and in some cases, a design limitation in which there is no mechanism for performing atomic file creation operations.

Some potential factors are race conditions, permissions, and predictability.

+ Research Gaps

UNIX hard links, and Windows hard/soft links are under-studied and under-reported.

+ Affected Resources
  • File/Directory
+ Functional Areas
  • File processing, temporary files
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERLink Following
CERT C Secure CodingFIO02-CCanonicalize path names originating from untrusted sources
CERT C Secure CodingPOS01-CCheck for the existence of links when dealing with files
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-09-08CWE Content TeamMITREInternal
updated Alternate Terms, Applicable Platforms, Relationships, Other Notes, Relationship Notes, Taxonomy Mappings, Weakness Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Relationships
2009-05-27CWE Content TeamMITREInternal
updated Description, Name
2009-10-29CWE Content TeamMITREInternal
updated Background Details, Other Notes
 
Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')
Definition in a New Window 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
ScopeEffect
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.

+ Observed Examples
ReferenceDescription
CVE-1999-0067Canonical example. CGI program does not sanitize "|" metacharacter when invoking a phonebook program.
CVE-2001-1246Language 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.
CVE-2002-0061Web server allows command execution using "|" (pipe) character.
CVE-2003-0041FTP client does not filter "|" from filenames returned by the server, allowing for OS command injection.
CVE-2008-2575Shell metacharacters in a filename in a ZIP archive
CVE-2002-1898Shell metacharacters in a telnet:// link are not properly handled when the launching application processes the link.
CVE-2008-4304OS command injection through environment variable.
CVE-2008-4796OS command injection through https:// URLs
CVE-2007-3572Chain: incomplete blacklist for OS command injection
+ Potential Mitigations
PhaseDescription
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).

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class77Improper Sanitization of Special Elements used in a Command ('Command Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
CanAlsoBeWeakness BaseWeakness Base88Argument Injection or Modification
Research Concepts1000
ChildOfCategoryCategory634Weaknesses that Affect System Processes
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory714OWASP Top Ten 2007 Category A3 - Malicious File Execution
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory727OWASP Top Ten 2004 Category A6 - Injection Flaws
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory741CERT C Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory744CERT C Secure Coding Section 10 - Environment (ENV)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory751Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
CanFollowWeakness BaseWeakness Base184Incomplete Blacklist
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Research Gaps

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 NameNode IDFitMapped Node Name
PLOVEROS Command Injection
OWASP Top Ten 2007A3CWE More SpecificMalicious File Execution
OWASP Top Ten 2004A6CWE More SpecificInjection Flaws
CERT C Secure CodingENV03-CSanitize the environment when invoking external programs
CERT C Secure CodingENV04-CDo not call system() if you do not need a command processor
CERT C Secure CodingSTR02-CSanitize data passed to complex subsystems
+ White Box Definitions

A weakness where the code path has:

1. start statement that accepts input

2. end statement that executes an operating system command where

a. the input is used as a part of the operating system command and

b. the operating system command is undesirable

Where "undesirable" is defined through the following scenarios:

1. not validated

2. incorrectly validated

+ References
G. Hoglund and G. McGraw. "Exploiting Software: How to Break Code". Addison-Wesley. 2004-02.
Pascal Meunier. "Meta-Character Vulnerabilities". 2008-02-20. <http://www.cs.purdue.edu/homes/cs390s/slides/week09.pdf>.
Robert Auger. "OS Commanding". 2009-06. <http://projects.webappsec.org/OS-Commanding>.
Lincoln Stein and John Stewart. "The World Wide Web Security FAQ". 2002-02-04. <http://www.w3.org/Security/Faq/wwwsf4.html>.
Jordan Dimov, Cigital. "Security Issues in Perl Scripts". <http://www.cgisecurity.com/lib/sips.html>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other Notes, Taxonomy Mappings
2008-10-14CWE Content TeamMITREInternal
updated Description
2008-11-24CWE Content TeamMITREInternal
updated Observed Examples, Relationships, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Common Consequences, Demonstrative Examples, Description, Likelihood of Exploit, Name, Observed Examples, Other Notes, Potential Mitigations, Relationships, Research Gaps, Terminology Notes
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Name, Related Attack Patterns
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated Description, Name, White Box Definitions
2009-10-29CWE Content TeamMITREInternal
updated Observed Examples, References
 
Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')
Definition in a New Window 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
ScopeEffect
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.

+ Observed Examples
ReferenceDescription
CVE-2004-0366chain: SQL injection in library intended for database authentication allows SQL injection and authentication bypass.
CVE-2008-2790SQL injection through an ID that was supposed to be numeric.
CVE-2008-2223SQL injection through an ID that was supposed to be numeric.
CVE-2007-6602SQL injection via user name.
CVE-2008-5817SQL injection via user name or password fields.
CVE-2003-0377SQL injection in security product, using a crafted group name.
CVE-2008-2380SQL injection in authentication library.
+ Potential Mitigations
PhaseDescription
Architecture and Design
Requirements

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.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class74Failure to Sanitize Data into a Different Plane ('Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory713OWASP Top Ten 2007 Category A2 - Injection Flaws
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004)711
ChildOfCategoryCategory727OWASP Top Ten 2004 Category A6 - Injection Flaws
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory751Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
CanFollowWeakness BaseWeakness Base456Missing Initialization
Research Concepts1000
ParentOfWeakness VariantWeakness Variant564SQL Injection: Hibernate
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Relationship Notes

SQL injection can be resultant from special character mismanagement, MAID, or blacklist/whitelist problems. It can be primary to authentication errors.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERSQL injection
7 Pernicious KingdomsSQL Injection
CLASPSQL injection
OWASP Top Ten 2007A2CWE More SpecificInjection Flaws
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
OWASP Top Ten 2004A6CWE More SpecificInjection Flaws
+ White Box Definitions

A weakness where the code path has:

1. start statement that accepts input and

2. end statement that performs an SQL command where

a. the input is part of the SQL command and

b. input contains SQL syntax (esp. query separator)

+ References
M. Howard and D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003.
Steven Friedl. "SQL Injection Attacks by Example". 2007-10-10. <http://www.unixwiz.net/techtips/sql-injection.html>.
Ferruh Mavituna. "SQL Injection Cheat Sheet". 2007-03-15. <http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/>.
David Litchfield, Chris Anley, John Heasman and Bill Grindlay. "The Database Hacker's Handbook: Defending Database Servers". Wiley. 2005-07-14.
David Litchfield. "The Oracle Hacker's Handbook: Hacking and Defending Oracle". Wiley. 2007-01-30.
Microsoft. "SQL Injection". December 2008. <http://msdn.microsoft.com/en-us/library/ms161953.aspx>.
Microsoft Security Vulnerability Research & Defense. "SQL Injection Attack". <http://blogs.technet.com/swi/archive/2008/05/29/sql-injection-attack.aspx>.
Michael Howard. "Giving SQL Injection the Respect it Deserves". 2008-05-15. <http://blogs.msdn.com/sdl/archive/2008/05/15/giving-sql-injection-the-respect-it-deserves.aspx>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
7 Pernicious KingdomsExternally Mined
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Modes of Introduction, Name, Relationships, Other Notes, Relationship Notes, Taxonomy Mappings
2008-10-14CWE Content TeamMITREInternal
updated Description
2008-11-24CWE Content TeamMITREInternal
updated Observed Examples
2009-01-12CWE Content TeamMITREInternal
updated Demonstrative Examples, Description, Enabling Factors for Exploitation, Modes of Introduction, Name, Observed Examples, Other Notes, Potential Mitigations, References, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples, Name, Related Attack Patterns
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated Description, Name, White Box Definitions
 
Information Leak (Information Disclosure)
Definition in a New Window Definition in a New Window
Weakness ID: 200 (Weakness Class)Status: Incomplete
+ Description

Description Summary

An information leak is the intentional or unintentional disclosure of information to an actor that is not explicitly authorized to have access to that information.

Extended Description

The information either

(1) is regarded as sensitive within the product's own functionality, such as a private message; or

(2) provides information about the product or its environment that could be useful in an attack but is normally not available to the attacker, such as the installation path of a product that is remotely accessible.

Many information leaks are resultant (e.g. path disclosure in PHP script error), but they can also be primary (e.g. timing discrepancies in crypto). There are many different types of problems that involve information leaks. Their severity can range widely depending on the type of information that is leaked.

+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Likelihood of Exploit

High

+ Potential Mitigations
PhaseDescription

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.

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory199Information Management Errors
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class668Exposure of Resource to Wrong Sphere
Research Concepts (primary)1000
ChildOfCategoryCategory717OWASP Top Ten 2007 Category A6 - Information Leakage and Improper Error Handling
Weaknesses in OWASP Top Ten (2007) (primary)629
ParentOfWeakness VariantWeakness Variant201Information Leak Through Sent Data
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant202Privacy Leak through Data Queries
Development Concepts (primary)699
ParentOfWeakness ClassWeakness Class203Discrepancy Information Leaks
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base209Error Message Information Leak
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base212Cross-boundary Cleansing Information Leak
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base213Intended Information Leak
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant214Process Environment Information Leak
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant215Information Leak Through Debug Information
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base226Sensitive Information Uncleared Before Release
Development Concepts (primary)699
Research Concepts1000
ParentOfWeakness ClassWeakness Class359Privacy Violation
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant497Information Leak of System Data
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowWeakness VariantWeakness Variant498Information Leak through Class Cloning
Development Concepts699
Research Concepts1000
CanFollowWeakness VariantWeakness Variant499Serializable Class Containing Sensitive Data
Development Concepts699
Research Concepts1000
ParentOfWeakness VariantWeakness Variant524Information Leak Through Caching
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant526Information Leak Through Environmental Variables
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base538File and Directory Information Leaks
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant598Information Leak Through Query Strings in GET Request
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant612Information Leak Through Indexing of Private Data
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERInformation Leak (information disclosure)
OWASP Top Ten 2007A6CWE More SpecificInformation Leakage and Improper Error Handling
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-09-08CWE Content TeamMITREInternal
updated Likelihood of Exploit, Relationships, Taxonomy Mappings, Weakness Ordinalities
2008-10-14CWE Content TeamMITREInternal
updated Description
 
Numeric Errors
Definition in a New Window Definition in a New Window
Category ID: 189 (Category)Status: Draft
+ Description

Description Summary

Weaknesses in this category are related to improper calculation or conversion of numbers.
+ Applicable Platforms

Languages

All

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory19Data Handling
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base128Wrap-around Error
Development Concepts699
ParentOfWeakness BaseWeakness Base129Improper Validation of Array Index
Development Concepts699
ParentOfWeakness BaseWeakness Base190Integer Overflow or Wraparound
Development Concepts699
ParentOfWeakness VariantWeakness Variant195Signed to Unsigned Conversion Error
Development Concepts699
ParentOfWeakness BaseWeakness Base198Use of Incorrect Byte Ordering
Development Concepts (primary)699
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
ParentOfWeakness BaseWeakness Base681Incorrect Conversion between Numeric Types
Development Concepts699
ParentOfWeakness ClassWeakness Class682Incorrect Calculation
Development Concepts (primary)699
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERNumeric Errors
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-10-29CWE Content TeamMITREInternal
updated Relationships
 
Path Traversal
Definition in a New Window Definition in a New Window
Weakness ID: 22 (Weakness Class)Status: Draft
+ Description

Description Summary

The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly sanitize special elements that can resolve to a location that is outside of that directory.

Extended Description

This allows attackers to traverse the file system to access files or directories that are outside of the restricted directory.

One of the most common special elements is the ".." sequence, which in most modern operating systems is interpreted as the parent directory of the current location.

+ Alternate Terms
Directory traversal
Path traversal:

"Path traversal" is preferred over "directory traversal."

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Potential Mitigations
PhaseDescription

Assume all input is malicious. Attackers can insert paths into input vectors and traverse the file system. Use an appropriate combination of black lists and white lists to ensure only valid and expected input is processed by the system. Warning: if you attempt to cleanse your data, then do so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then the file may be compromised. See CWE-182 (Collapse of Data Into Unsafe Value).

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.

+ Other Notes

Some pathname equivalence issues are not directly related to directory traversal, rather are used to bypass security-relevant checks for whether a file/directory can be accessed by the attacker (e.g. a trailing "/" on a filename could bypass access rules that don't expect a trailing /, causing a server to provide the file when it normally would not).

Incomplete diagnosis or reporting of vulnerabilities can make it difficult to know which variant is affected. For example, a researcher might say that "..\" is vulnerable, but not test "../" which may also be vulnerable.

Any combination of the items below can provide its own variant, e.g. "//../" is not listed (CVE-2004-0325).

Like other Weaknesses, terminology is often based on the types of manipulations used, instead of the underlying Weaknesses.

Some people use "directory traversal" only to refer to the injection of ".." and equivalent sequences whose specific meaning is to traverse directories. Other variants like "absolute pathname" and "drive letter" have the *effect* of directory traversal, but some people may not call it such, since it doesn't involve ".." or equivalent.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory21Pathname Traversal and Equivalence Errors
Development Concepts (primary)699
ChildOfCategoryCategory632Weaknesses that Affect Files or Directories
Resource-specific Weaknesses (primary)631
ChildOfWeakness ClassWeakness Class668Exposure of Resource to Wrong Sphere
Research Concepts1000
ChildOfWeakness ClassWeakness Class706Use of Incorrectly-Resolved Name or Reference
Research Concepts (primary)1000
ChildOfCategoryCategory715OWASP Top Ten 2007 Category A4 - Insecure Direct Object Reference
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory723OWASP Top Ten 2004 Category A2 - Broken Access Control
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
CanFollowWeakness ClassWeakness Class20Improper Input Validation
Research Concepts1000
ParentOfWeakness BaseWeakness Base23Relative Path Traversal
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base36Absolute Path Traversal
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowWeakness ClassWeakness Class73External Control of File Name or Path
Research Concepts1000
CanFollowWeakness ClassWeakness Class172Encoding Error
Research Concepts1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635